Skip to content

Commit

Permalink
API changes: delay kwarg -> ready kwarg
Browse files Browse the repository at this point in the history
  • Loading branch information
kiwi0fruit committed Oct 11, 2018
1 parent 81c7036 commit 7d6520d
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 35 deletions.
1 change: 0 additions & 1 deletion examples/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
eval: False
pandoctools:
profile: Kiwi
out: "*.md.md"
...

```
Expand Down
1 change: 0 additions & 1 deletion examples/examples.md.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ nameInLink: False
numberSections: False
pairDelim: ','
pandoctools:
out: '\*.md.md'
profile: Kiwi
rangeDelim: '\-'
refDelim: ','
Expand Down
6 changes: 3 additions & 3 deletions scripts/sugartex_kiwi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import panflute as pf
from sugartex import SugarTeX

sugartex = SugarTeX(delay=True)
sugartex = SugarTeX(ready=False)
# Tuning SugarTeX options:
sugartex.mjx_hack()
sugartex.subscripts['ᵩ'] = 'ψ' # Consolas font specific
sugartex.superscripts['ᵠ'] = 'ψ' # Consolas font specific
# sugartex.subscripts['ᵩ'] = 'ψ' # Consolas font specific
# sugartex.superscripts['ᵠ'] = 'ψ' # Consolas font specific
# Applying SugarTeX options:
sugartex.ready()

Expand Down
2 changes: 1 addition & 1 deletion sugartex.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ pandoc -f json -o doc.md.md

SugarTeX is written in python and has a tweakable architecture. As you can see in [this filter](scripts/sugartex_kiwi.py) tweaks can be made in between:
```py
sugartex = SugarTeX(delay=True)
sugartex = SugarTeX(ready=False)
...
sugartex.ready()
```
Expand Down
6 changes: 5 additions & 1 deletion sugartex/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from .sugartex_filter import SugarTeX # noqa
from .pre_sugartex import sugartex_preprocess, sugartex, stex, stex2 # noqa
from .pre_sugartex import (
sugartex,
sugartex_replace_all, sugartex_replace_all as all,
sugartex_preprocess, sugartex_preprocess as pre
) # noqa

from ._version import get_versions
__version__ = get_versions()['version']
Expand Down
34 changes: 18 additions & 16 deletions sugartex/pre_sugartex.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,35 @@
import sys
import re
from .sugartex_filter import SugarTeX
import time

SESSION_ID = '§' + str(int(round(time.time() * 1000)))[-4:] + '§'


def sugartex_preprocess(source: str) -> str:
"""
Preprocess text for SugarTeX Pandoc filter.
Replaces 'ˎ' with `$` (except `\ˎ`), replaces `\ˎ` with `ˎ`
"""
rep = {r'\ˎ': 'ˎ', 'ˎ': '$'}
return re.sub(r'\\ˎ|ˎ', lambda m: rep[m.group(0)], source)


sugartex = SugarTeX(delay=True)

sugartex = SugarTeX(ready=False)

def stex2(string):
return sugartex_preprocess(re.sub(
r'((?<=[^\\]ˎ)|(?<=^ˎ))[^ˎ]*(?=ˎ)',
lambda m: sugartex.replace(m.group(0)),
string
))


def stex(string):
return sugartex_preprocess(re.sub(
r'((?<=[^\\][ˎ$])|(?<=^[ˎ$]))[^ˎ$]*(?=[ˎ$])',
def sugartex_replace_all(string):
"""
Replace all with SugarTeX.
Runs ``sugartex_preprocess`` then iterates via regex and
replaces each math between '$...$'.
"""
string = sugartex_preprocess(string).replace(r'\$', SESSION_ID)
return re.sub(
r'(?<=$)[^$]*(?=$)',
lambda m: sugartex.replace(m.group(0)),
string
))
).replace(SESSION_ID, r'\$')


_help = '''pre-sugartex reads from stdin and writes to stdout. Usage:
Expand All @@ -48,10 +50,10 @@ def main():
if arg1 == '--all' or arg1 == '--kiwi':
if arg1 == '--kiwi':
sugartex.mjx_hack()
sugartex.subscripts['ᵩ'] = 'ψ' # Consolas font specific
sugartex.superscripts['ᵠ'] = 'ψ' # Consolas font specific
# sugartex.subscripts['ᵩ'] = 'ψ' # Consolas font specific
# sugartex.superscripts['ᵠ'] = 'ψ' # Consolas font specific
sugartex.ready()
sys.stdout.write(stex(sys.stdin.read()))
sys.stdout.write(sugartex_replace_all(sys.stdin.read()))
elif arg1 == '--help' or arg1 == '-h':
print(_help)
else:
Expand Down
25 changes: 17 additions & 8 deletions sugartex/sugartex_filter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
import copy
from collections import OrderedDict
from typing import Type, Callable
from typing import Type, Callable, Iterable
from itertools import chain


Expand Down Expand Up @@ -152,14 +152,13 @@
_default_postf = r'$|(?=\n)|(?<!\\)(?=[ ˲\}])'


def _ops_regex(ops_) -> str:
"""ops is a iterable of str"""
def _ops_regex(ops_: Iterable[str]) -> str:
ops = list(ops_)
singles = re.escape(''.join(op for op in ops if len(op) == 1)) # language=PythonRegExp
singles = [r'[{}]'.format(singles)] if (singles != '') else []
longs = [op for op in ops if len(op) > 1]
longs.sort(key=lambda s: -len(s))
longs = [re.escape(op) for op in longs] # language=PythonRegExp
longs = [re.escape(op) for op in longs]
return '|'.join(longs + singles)


Expand All @@ -171,7 +170,7 @@ def _search_regex(ops: dict, regex_pat: str):
"""
custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic]))
op_names = [op for op, dic in ops.items() if 'regex' not in dic]
regex = [regex_pat.format(_ops_regex(op_names))] if len(op_names) > 0 else [] # language=PythonRegExp
regex = [regex_pat.format(_ops_regex(op_names))] if len(op_names) > 0 else []
return re.compile('|'.join(custom_regexps + regex))


Expand Down Expand Up @@ -563,6 +562,7 @@ def big_pat(pat: str, dic): # has 2 slots: big op id, optional limits display m
def fill(self):
big_spec = [(op, {'pat': self.big_pat(self.big_ops[op], self.big_limits), 'regex': None})
for op in self.big_ops.keys()]
# noinspection PyTypeChecker
big_spec[0][1]['regex'] = self.big_regex_pat.format(_ops_regex(self.big_ops.keys()),
_ops_regex(self.big_limits.keys()))
self.ops = OrderedDict(
Expand Down Expand Up @@ -627,15 +627,19 @@ class SugarTeX:
escapes = ['⋲', '›', '˺', '↕', 'ˌ']
escapes_regex = None # it's assigned later

def __init__(self, delay: bool=False):
def __init__(self, ready: bool=True):
self.pref_un_ops = PrefUnOps()
self.postf_un_ops = PostfUnOps()
self.bin_centr_ops = BinCentrOps()
self.null_ops = NullOps()
if not delay:

self.readied = False
if ready:
self.ready()

def ready(self):
self.readied = True

self.bin_centr_ops.fill()
self.postf_un_ops.fill()
styles_postf = self.postf_un_ops.one_symbol_ops_str()
Expand All @@ -658,7 +662,7 @@ def ready(self):
@staticmethod
def _dict_replace(dic: dict or Type[OrderedDict], source: str) -> str:
if len(dic) > 0 and source != '':
rep = {re.escape(key): val for key, val in dic.items()} # language=PythonRegExp
rep = {re.escape(key): val for key, val in dic.items()}
regex = re.compile(r'(?<!\\)(?:{})'.format("|".join(rep.keys())))
return regex.sub(lambda m: rep[re.escape(m.group(0))], source)
else:
Expand Down Expand Up @@ -825,9 +829,11 @@ def null_replace(match) -> str:
else:
term2 = string[match.end():rmatch.start()]
if loc == 'l':
# noinspection PyUnboundLocalVariable
terms = list(lmatch.groups()) + [term1] + regex_terms[1:]
start, end = lmatch.start(), match.end()
elif loc == 'r':
# noinspection PyUnboundLocalVariable
terms = regex_terms[1:] + [term2] + list(rmatch.groups())
start, end = match.start(), rmatch.end()
elif loc == 'lr':
Expand Down Expand Up @@ -862,6 +868,9 @@ def replace(self, src: str) -> str:
:return: str
New LaTeX string
"""
if not self.readied:
self.ready()

# Brackets + simple pre replacements:
src = self._dict_replace(self.simple_pre, src)

Expand Down
6 changes: 3 additions & 3 deletions sugartex/sugartex_pandoc_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import panflute as pf
from .sugartex_filter import SugarTeX

sugartex = SugarTeX(delay=True)
sugartex = SugarTeX(ready=False)


def kiwi_hack():
sugartex.mjx_hack()
sugartex.subscripts['ᵩ'] = 'ψ' # Consolas font specific
sugartex.superscripts['ᵠ'] = 'ψ' # Consolas font specific
# sugartex.subscripts['ᵩ'] = 'ψ' # Consolas font specific
# sugartex.superscripts['ᵠ'] = 'ψ' # Consolas font specific


def action(elem, doc):
Expand Down
2 changes: 1 addition & 1 deletion update_version.bat
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
set tagname=0.1.9
set tagname=0.1.10
git tag -d %tagname%
git push --delete origin %tagname%
git tag -a %tagname%
Expand Down

0 comments on commit 7d6520d

Please sign in to comment.