Skip to content

Commit

Permalink
Merge pull request #17 from ppizarror/added-custom-template-latex
Browse files Browse the repository at this point in the history
Added custom template latex
  • Loading branch information
ppizarror authored Oct 26, 2021
2 parents 72f16d6 + 20b70e9 commit dce2081
Show file tree
Hide file tree
Showing 9 changed files with 198 additions and 100 deletions.
9 changes: 6 additions & 3 deletions pydetex/_gui_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,9 +459,12 @@ def _update_buttons(self, enable: bool = True) -> None:
syn, mean, _, ant = self._dictionary._langs[self._lang]
except KeyError:
syn, mean, ant = False, False, False
self._syn['state'] = tk.NORMAL if (syn and enable) else tk.DISABLED
self._mean['state'] = tk.NORMAL if (mean and enable) else tk.DISABLED
self._ant['state'] = tk.NORMAL if (ant and enable) else tk.DISABLED
try:
self._syn['state'] = tk.NORMAL if (syn and enable) else tk.DISABLED
self._mean['state'] = tk.NORMAL if (mean and enable) else tk.DISABLED
self._ant['state'] = tk.NORMAL if (ant and enable) else tk.DISABLED
except tk.TclError:
pass

@staticmethod
def _process_out_key(event: 'tk.Event') -> Optional['tk.Event']:
Expand Down
2 changes: 2 additions & 0 deletions pydetex/_utils_lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,13 @@ def __init__(self) -> None:
self._lang = {
'en': {
'caption': 'CAPTION: {0}\n',
'figure_caption': 'FIGURE_CAPTION: {0}\n',
'multi_char_equ': 'EQUATION_{0}',
'sub_figure_title': 'SUB_FIGURE TITLE: {0}\n'
},
'ens': {
'caption': 'LEYENDA: {0}\n',
'figure_caption': 'LEYENDA_FIGURA: {0}\n',
'multi_char_equ': 'ECUACIÓN_{0}',
'sub_figure_title': 'TÍTULO SUB_FIGURA: {0}\n'
}
Expand Down
3 changes: 2 additions & 1 deletion pydetex/_utils_tex.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
'find_tex_command_char',
'find_tex_commands',
'find_tex_commands_noargv',
'get_tex_commands_args'
'get_tex_commands_args',
'VALID_TEX_COMMAND_CHARS'
]

from typing import Tuple, Union, List
Expand Down
2 changes: 2 additions & 0 deletions pydetex/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,8 @@ def _process(self) -> None:
PARSER_FONT_FORMAT['equation'] = FONT_TAGS['italic'] if font_format else ''
PARSER_FONT_FORMAT['normal'] = FONT_TAGS['normal'] if font_format else ''
PARSER_FONT_FORMAT['ref'] = FONT_TAGS['link'] if font_format else ''
PARSER_FONT_FORMAT['tex_text_tag'] = FONT_TAGS['bold'] if font_format else ''
PARSER_FONT_FORMAT['tex_text_tag_content'] = FONT_TAGS['italic'] if font_format else ''

# Process the text and get the language
out = self.pipeline(text, self._detected_lang_tag)
Expand Down
228 changes: 139 additions & 89 deletions pydetex/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
'FONT_FORMAT_SETTINGS',
'process_chars_equations',
'process_cite',
'process_cite_replace_tags',
'process_inputs',
'process_labels',
'process_quotes',
Expand All @@ -32,7 +33,9 @@
# Files
_NOT_FOUND_FILES = []
_PRINT_LOCATION = False
_TAG_FILE_ERROR = '|FILEERROR|'
_TAG_FILE_ERROR = '⇱FILEERROR⇲'
_TAG_OPEN_CITE = '⇱OPEN_CITE⇲'
_TAG_CLOSE_CITE = '⇱CLOSE_CITE⇲'

# Parser font format. This dict stores the font of some tex elements to be represented
# in the GUI text editor. The values are the same of _fonts.FONT_TAGS. By default
Expand All @@ -41,10 +44,77 @@
'cite': '',
'equation': '',
'normal': '',
'ref': ''
'ref': '',
'tex_text_tag': '',
'tex_text_tag_content': ''
}

LANG_TEX_TAGS = ut.LangTexTextTags()
LANG_TEX_TEXT_TAGS = ut.LangTexTextTags()

# Replace symbols
REPLACE_SYMBOLS_LIBRARY: List[Tuple[str, str]] = [
# Common
('\\item', '-'),
('--', '–'),
('\\\\', '\n'),
('\\ ', ' '),

# Letters
('fi', 'fi'),
]
REPLACE_UNIQUE_SYMBOLS_LIBRARY: List[Tuple[str, str]] = [
# Greek
('\\alpha', 'α'),
('\\beta', 'β'),
('\\chi', 'χ'),
('\\delta', 'δ'),
('\\Delta', 'Δ'),
('\\epsilon', 'ϵ'),
('\\eta', 'η'),
('\\gamma', 'γ'),
('\\Gamma', 'Γ'),
('\\iota', 'ι'),
('\\kappa', 'κ'),
('\\lambda', 'λ'),
('\\Lambda', 'Λ'),
('\\mu', 'μ'),
('\\nu', 'ν'),
('\\omega', 'ω'),
('\\Omega', 'Ω'),
('\\phi', 'φ'),
('\\Phi', 'Φ'),
('\\pi', 'π'),
('\\Pi', 'Π'),
('\\psi', 'ψ'),
('\\Psi', 'Ψ'),
('\\rho', 'ρ'),
('\\sigma', 'σ'),
('\\Sigma', 'Σ'),
('\\tau', 'τ'),
('\\theta', 'θ'),
('\\Theta', 'Θ'),
('\\upsilon', 'υ'),
('\\varepsilon', 'ε'),
('\\varphi', 'φ'),
('\\varrho', 'ϱ'),
('\\vartheta', '𝜗'),
('\\xi', 'ξ'),
('\\Xi', 'Ξ'),
('\\zeta', 'ζ'),

# Arrows
('\\leftarrow', '←'),
('\\rightarrow', '→'),
('\\Leftarrow', '⇐'),
('\\Rightarrow', '⇒'),
('\\uparrow', '↑'),
('\\downarrow', '↓'),
('\\Uparrow', '⇑'),
('\\Downarrow', '⇓'),
('\\leftrightarrow', '↔'),
('\\longleftarrow', '⟵'),
('\\longrightarrow', '⟶')
]


def _find_str(s: str, char: str) -> int:
Expand Down Expand Up @@ -204,17 +274,31 @@ def process_cite(s: str) -> str:
if w not in cites.keys():
cites[w] = len(cites.keys()) + 1
c = c.replace(w, str(cites[w]))
s = s[:k] + FONT_FORMAT_SETTINGS['cite'] + '[' + c + ']' + \
FONT_FORMAT_SETTINGS['normal'] + s[k + j + 1:]
s = s[:k] + FONT_FORMAT_SETTINGS['cite'] + _TAG_OPEN_CITE + c + \
_TAG_CLOSE_CITE + FONT_FORMAT_SETTINGS['normal'] + s[k + j + 1:]
break


def process_cite_replace_tags(s: str, cite_format: Tuple[str, str] = ('[', ']')) -> str:
"""
Replaces cite tags to an specific format.
:param s: String
:param cite_format: Cite format
:return: String with no cites
"""
assert len(cite_format) == 2
s = s.replace(_TAG_OPEN_CITE, (cite_format[0]))
s = s.replace(_TAG_CLOSE_CITE, (cite_format[1]))
return s


def process_labels(s: str) -> str:
"""
Removes labels.
:param s: String
:return:
:return: String with no labels
"""
while True:
k = find_str(s, '\\label{')
Expand Down Expand Up @@ -333,70 +417,23 @@ def simple_replace(s: str) -> str:
:param s: String
:return: String with replaced items
"""
library: List[Tuple[str, str]] = [
# Common
('\\item', '-'),
('--', '–'),
('\\\\', '\n'),
('\\ ', ' '),

# Letters
('fi', 'fi'),

# Greek
('\\alpha', 'α'),
('\\beta', 'β'),
('\\chi', 'χ'),
('\\delta', 'δ'),
('\\Delta', 'Δ'),
('\\epsilon', 'ϵ'),
('\\eta', 'η'),
('\\gamma', 'γ'),
('\\Gamma', 'Γ'),
('\\iota', 'ι'),
('\\kappa', 'κ'),
('\\lambda', 'λ'),
('\\Lambda', 'Λ'),
('\\mu', 'μ'),
('\\nu', 'ν'),
('\\omega', 'ω'),
('\\Omega', 'Ω'),
('\\phi', 'φ'),
('\\Phi', 'Φ'),
('\\pi', 'π'),
('\\Pi', 'Π'),
('\\psi', 'ψ'),
('\\Psi', 'Ψ'),
('\\rho', 'ρ'),
('\\sigma', 'σ'),
('\\Sigma', 'Σ'),
('\\tau', 'τ'),
('\\theta', 'θ'),
('\\Theta', 'Θ'),
('\\upsilon', 'υ'),
('\\varepsilon', 'ε'),
('\\varphi', 'φ'),
('\\varrho', 'ϱ'),
('\\vartheta', '𝜗'),
('\\xi', 'ξ'),
('\\Xi', 'Ξ'),
('\\zeta', 'ζ'),

# Arrows
('\\leftarrow', '←'),
('\\rightarrow', '→'),
('\\Leftarrow', '⇐'),
('\\Rightarrow', '⇒'),
('\\uparrow', '↑'),
('\\downarrow', '↓'),
('\\Uparrow', '⇑'),
('\\Downarrow', '⇓'),
('\\leftrightarrow', '↔'),
('\\longleftarrow', '⟵'),
('\\longrightarrow', '⟶')
]
for w in library:
for w in REPLACE_SYMBOLS_LIBRARY:
s = s.replace(w[0], w[1])

# Replace unique symbols
s += ' '
invalid_tag = '⇱SYMBOL_REPLACE_TAG_TOKEN⇲'
for w in REPLACE_UNIQUE_SYMBOLS_LIBRARY:
word, repl = w
while True:
k = s.find(word)
if k == -1:
break
if s[k + len(word)] not in ut.VALID_TEX_COMMAND_CHARS:
s = s[0:k] + repl + s[k + len(word):]
else:
s = s[0:k + 1] + invalid_tag + s[k + 1:]
s = s[0:len(s) - 1].replace(invalid_tag, '')
return s


Expand Down Expand Up @@ -487,23 +524,34 @@ def output_text_for_some_commands(s: str, lang: str) -> str:
:return: Text string or empty if error
"""
# Stores the commands to be transformed
# 'command name': (argument number, argument is optional, LANG_TEX_TAGS tag to be replaced)
commands = {
'caption': (1, False, 'caption'),
'subfloat': (1, True, 'sub_figure_title')
}
# (command name, argument number, argument is optional, LANG_TEX_TAGS tag to be replaced, total commands)
commands = [
('caption', 1, False, 'caption', 1),
('insertimage', 3, False, 'figure_caption', 3), # Format \insertimage{file}{args}{caption}
('insertimage', 4, False, 'figure_caption', 4), # Format \insertimage[opt. keywords]{file}{args}{caption}
('insertimageboxed', 4, False, 'figure_caption', 4),
('insertimageboxed', 5, False, 'figure_caption', 5),
('subfloat', 1, True, 'sub_figure_title', 1)
]
new_s = ''

# Get the commands
cmd_args = ut.get_tex_commands_args(s)
for c in cmd_args:
if c[0] in commands.keys():
cmd_argnum, cmd_is_optional, cmd_tag = commands[c[0]]
if len(c) - 1 >= cmd_argnum:
if c[cmd_argnum][1] == cmd_is_optional:
argv = c[cmd_argnum][0].replace('\n', ' ') # Command's argument to process
argv = remove_commands_param(argv, lang) # Remove commands within the argument
new_s += LANG_TEX_TAGS.get(lang, cmd_tag).format(argv)
for cmd in commands:
if c[0] == cmd[0]:
_, cmd_argnum, cmd_is_optional, cmd_tag, total_commands = cmd
if len(c) - 1 >= cmd_argnum and len(c) - 1 == total_commands:
if c[cmd_argnum][1] == cmd_is_optional:
argv = c[cmd_argnum][0].replace('\n', ' ') # Command's argument to process
argv = remove_commands_param(argv, lang) # Remove commands within the argument
argv = argv.strip()
if argv != '':
argv = FONT_FORMAT_SETTINGS['tex_text_tag_content'] + argv # Add format text
text = LANG_TEX_TEXT_TAGS.get(lang, cmd_tag).format(argv)
new_s += FONT_FORMAT_SETTINGS['tex_text_tag'] + text + FONT_FORMAT_SETTINGS['normal']

break

return new_s

Expand All @@ -529,25 +577,27 @@ def remove_commands_param(s: str, lang: str) -> str:
elif i < tex_tags[k][3] + 1:
pass
else: # advance to other tag
new_s += output_text_for_some_commands(s[tex_tags[k][0]:tex_tags[k][3] + 2], lang)
sub_s = s[tex_tags[k][0]:tex_tags[k][3] + 2]
if not tex_tags[k][4]: # If the command does not continue
new_s += output_text_for_some_commands(sub_s, lang)
k += 1
else:
new_s += s[i]

# Replace all command symbols
parenthesis_open_symbol = '⇱PARENTHESIS_OPEN_SYMBOL⇲'
parenthesis_close_symbol = '⇱PARENTHESIS_CLOSE_SYMBOL⇲'
# parenthesis_sq_open_symbol = '⇱PARENTHESIS_SQ_OPEN_SYMBOL⇲'
# parenthesis_sq_close_symbol = '⇱PARENTHESIS_SQ_CLOSE_SYMBOL⇲'
parenthesis_sq_open_symbol = '⇱PARENTHESIS_SQ_OPEN_SYMBOL⇲'
parenthesis_sq_close_symbol = '⇱PARENTHESIS_SQ_CLOSE_SYMBOL⇲'
new_s = new_s.replace('\\{', parenthesis_open_symbol)
new_s = new_s.replace('\\}', parenthesis_close_symbol)
# new_s = new_s.replace('\\[', parenthesis_sq_open_symbol)
# new_s = new_s.replace('\\]', parenthesis_sq_close_symbol)
new_s = new_s.replace('\\[', parenthesis_sq_open_symbol)
new_s = new_s.replace('\\]', parenthesis_sq_close_symbol)
new_s = new_s.replace('{', '').replace('}', '') # .replace('[', '').replace(']', '')
new_s = new_s.replace(parenthesis_open_symbol, '\\{')
new_s = new_s.replace(parenthesis_close_symbol, '\\}')
# new_s = new_s.replace(parenthesis_sq_open_symbol, '\\[')
# new_s = new_s.replace(parenthesis_sq_close_symbol, '\\]')
new_s = new_s.replace(parenthesis_sq_open_symbol, '\\[')
new_s = new_s.replace(parenthesis_sq_close_symbol, '\\]')

return new_s

Expand Down Expand Up @@ -605,7 +655,7 @@ def process_chars_equations(s: str, lang: str, single_only: bool) -> str:
else: # advance to other tag
if tex_tags[k][1] - tex_tags[k][0] > 2:
if not single_only:
new_s += LANG_TEX_TAGS.get(lang, 'multi_char_equ').format(eqn_number)
new_s += LANG_TEX_TEXT_TAGS.get(lang, 'multi_char_equ').format(eqn_number)
eqn_number += 1
else:
new_s += s[tex_tags[k][0]:tex_tags[k][1] + 1]
Expand Down
8 changes: 6 additions & 2 deletions pydetex/pipelines.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
PipelineType = Callable[[str, str], str]


def simple(s: str, lang: str = 'en') -> str:
def simple(s: str, lang: str = 'en', cite_replace_tags: bool = True) -> str:
"""
The most simple pipeline ever.
:param s: String latex
:param lang: Language tag of the code
:param cite_replace_tags: Replace cite tags
:return: String with no latex!
"""
if len(s) == 0:
Expand All @@ -41,6 +42,8 @@ def simple(s: str, lang: str = 'en') -> str:
s = par.process_chars_equations(s, lang, True)
if len(s) > 0 and s[-1] == '\\':
s = s[0:len(s) - 1]
if cite_replace_tags:
s = par.process_cite_replace_tags(s)
return s


Expand All @@ -52,10 +55,11 @@ def strict(s: str, lang: str = 'en') -> str:
:param lang: Language tag of the code
:return: String with no latex!
"""
s = simple(s, lang)
s = simple(s, lang, cite_replace_tags=False)
s = par.process_chars_equations(s, lang, False)
s = par.remove_commands_char(s, '$')
s = par.remove_commands_param(s, lang)
s = par.remove_commands_param_noargv(s)
s = par.remove_comments(s)
s = par.process_cite_replace_tags(s)
return s
Loading

0 comments on commit dce2081

Please sign in to comment.