Giter VIP home page Giter VIP logo

Comments (1)

phfaist avatar phfaist commented on July 29, 2024 1

Hi, great question. This is slightly tricky because the default latex2text replacement texts aren't context-aware. I mean, the replacement text for "\item" is generated by default without knowing whether the macro is in an {enumerate} or {itemize} environment nor how many other "\item"'s were present before. You can track the context explicitly however, and here's a simple solution:

from pylatexenc import macrospec, latexwalker, latex2text

class EnumContext:
    def __init__(self, env=None, nest_level=0, item_no=0):
        self.env = env
        self.nest_level = nest_level
        self.item_no = item_no

def enum_environment_to_text(n, l2tobj):
    if n.environmentname not in ("enumerate", "itemize"):
        raise RuntimeError("environment was expected to be enumerate or itemize")
    try:
        old_context = getattr(l2tobj, 'context_enum_environment', EnumContext())
        l2tobj.context_enum_environment = EnumContext(n.environmentname, old_context.nest_level+1, 0)
        s = l2tobj.nodelist_to_text(n.nodelist)
    finally:
        l2tobj.context_enum_environment = old_context
    return s

def item_to_text(n, l2tobj):
    enumcontext = getattr(l2tobj, 'context_enum_environment', EnumContext())
    if n.nodeoptarg:
        itemstr = l2tobj.nodelist_to_text([n.nodeoptarg])
    if enumcontext.env == 'itemize':
        itemstr = '- '
    elif enumcontext.env == 'enumerate':
        enumcontext.item_no += 1
        itemstr = str(enumcontext.item_no) + '. '
    else:
        itemstr = '* ' # \item not in \begin{enumerate} or \begin{itemize} environment
    return '\n' + '  '*enumcontext.nest_level + itemstr


c = latex2text.get_default_latex_context_db()
c.add_context_category(
    'enum-context',
    macros=[
        latex2text.MacroTextSpec('item', simplify_repl=item_to_text)
    ],
    environments=[
        latex2text.EnvironmentTextSpec('enumerate', simplify_repl=enum_environment_to_text),
        latex2text.EnvironmentTextSpec('itemize', simplify_repl=enum_environment_to_text),
    ],
    prepend=True
)

l2t = latex2text.LatexNodes2Text(latex_context=c)

print(l2t.latex_to_text(r"""
Hello world.
\begin{enumerate}
\item first item
\item second item
\item group of itemized items
    \begin{itemize}
    \item subitem
    \item another subitem
    \end{itemize}
\item last item
\end{enumerate}
"""))

The result is:

Hello world.

  1.  first item

  2.  second item

  3.  group of itemized items

    -  subitem

    -  another subitem

  4.  last item

The idea is that we set an attribute context_enum_environment to the LatexNodes2Text object to track enumerate/itemize environments (including nesting level) and count how many \item macros are encountered at each level. This is all done in the replacement callbacks for the \item macro and for the \begin{enumerate} and \begin{itemize} environments.

Hope this helps.

from pylatexenc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.