On Linux at least (don't know about Windows), there is the latexdef script by Martin Scharrer, which looks up LaTeX definitions from the command line:
latexdef section
will print
\section
\long macro:->\@startsection {section}{1}{\z@ }{-3.5ex \@plus -1ex \@minus -.2ex}{2.3ex \@plus .2ex}{\normalfont \Large \bfseries }
whereas
latexdef sausage
will print
\sausage
undefined
We can invoke latexdef from Python like so:
import subprocess, re
def latexdef(command_list, *args):
'''
call latexdef on a list of commands to be looked up
*args can be used to pass options to latexdef
'''
p = subprocess.Popen(['latexdef'] + list(args) + command_list, \
stdout=subprocess.PIPE, \
stderr=subprocess.STDOUT)
return p.communicate()[0].strip()
def are_commands(command_list, *args):
'''
look up multiple commands and return results in a dict
'''
result = latexdef(command_list, *args)
frags = [ f.splitlines() for f in re.split(r'\n{2,}', result, re.MULTILINE) ]
return { command[1:] : defn != 'undefined' for command, defn in frags }
def is_command(command, *args):
'''
look up a single command
'''
return are_commands([command],*args).values()[0]
if __name__ == '__main__':
commands = "chapter section sausage".split()
for command in commands:
print command, is_command(command)
print "\nwith book class loaded"
for command in commands:
print command, is_command(command, '-c', 'book')
print "\nall at once, with class book"
print are_commands(commands, '-c', 'book')
This prints
chapter False
section True
sausage False
with book class loaded
chapter True
section True
sausage False
all at once, with class book
{'sausage:': False, 'section:': True, 'chapter:': True}
Each single invocation of latexdef is rather slow, but time can be saved by looking up multiple commands in a single call. This is the purpose of are_commands, which returns the lookup result for each command in a dict.
Also note that latexdef is a Perl script, so depending on how important this is to you, it might make sense to translate the entire thing to Python, thus cutting out the middleman. But it is a longish script, and Perl is kind of hard on the eyes ...
\which is usually followed by characters a-z or A-Z (there are exceptions). But to check if it's valid, you would have to compile. But maybe you want to read the TeXBook and source2e (you'll find the most basic hundreds of command sequences there). – TeXnician Jul 06 '17 at 13:13latexdefdoes.) – ShreevatsaR Jul 07 '17 at 00:30latexdefin answer below). There could be a second part about say how to parse the output in a particular language, and that would indeed be an offtopic general programming question but that's not how I read this question. – ShreevatsaR Jul 07 '17 at 03:31LatexCmds.mathit = bind(Style, '\\mathit', 'i', 'class="mq-font"');so it seems as if your question should be answered as checking if the string corresponds to an entry in theLatexCmdsarray, but I don't have mathquill installed to test. – David Carlisle Jul 08 '17 at 16:18