Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a switch for processing function names #35

Merged
merged 2 commits into from
Oct 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions latexify/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@
class LatexifyVisitor(node_visitor_base.NodeVisitorBase):
"""Latexify AST visitor."""

def __init__(self, math_symbol):
def __init__(self, math_symbol=False, raw_func_name=False):
self.math_symbol = math_symbol
self.raw_func_name = raw_func_name # True:do not treat underline as label of subscript(#31)
super().__init__()

def _parse_math_symbols(self, val: str) -> str:
Expand All @@ -52,6 +53,8 @@ def visit_FunctionDef(self, node, action): # pylint: disable=invalid-name
del action

name_str = r'\mathrm{' + str(node.name) + '}'
if self.raw_func_name:
name_str = name_str.replace(r"_", r"\_") # fix #31
arg_strs = [
self._parse_math_symbols(str(arg.arg)) for arg in node.args.args]
body_str = self.visit(node.body[0])
Expand Down Expand Up @@ -225,26 +228,26 @@ def visit_If(self, node, action): # pylint: disable=invalid-name
return latex + r', & \mathrm{otherwise} \end{array} \right.'


def get_latex(fn, math_symbol=True):
def get_latex(fn, *args, **kwargs):
try:
source = inspect.getsource(fn)
# pylint: disable=broad-except
except Exception:
# Maybe running on console.
source = dill.source.getsource(fn)

return LatexifyVisitor(math_symbol=math_symbol).visit(ast.parse(source))
return LatexifyVisitor(*args, **kwargs).visit(ast.parse(source))


def with_latex(*args, math_symbol=True):
def with_latex(*args, **kwargs):
"""Translate a function with latex representation."""

class _LatexifiedFunction:
"""Function with latex representation."""

def __init__(self, fn):
self._fn = fn
self._str = get_latex(fn, math_symbol=math_symbol)
self._str = get_latex(fn, *args,**kwargs)

@property
def __doc__(self):
Expand Down