我正在写一小段代码,它解析latex文件,并给我定义的newcommands。一个测试用例就是这个简单的latex文件:% +--------------------------------------------------------------------+
% | |
% | New particle stuff |
% | |
% +--------------------------------------------------------------------+
\newcommand*{\Hmp}{\ensuremath{H^{\mp}}\xspace}
\newcommand*{\susy}[1]{\ensuremath{\tilde{#1}}\xspace}
\newcommand*{\susy2}[1,2]{\ensuremath{\tilde{#1}\tilde{#2}}\xspace}
可能有一个更复杂的情况,命令扩展了几行,所以我需要跟踪不同的步骤,比如命令是否需要增加更多的行,或者命令已经完成并准备完成。在
问题是,在两个嵌套的if/else语句中,变量的作用域似乎丢失了,变量不再更新。我要做的是:
^{pr2}$
问题是,当我给newcommand变量赋值时,我从get_cmg_from_line函数(我已经测试过了)中得到的值,它不会更新newcommand变量,但是如果我把它移到前面的if上,它就会识别并更新它。keep和added变量也会发生同样的情况。在
既然我不知道为什么我不应该去定义这个范围。。。我错过了什么蠢事吗?我应该如何更新newcommand变量的值?因为它可能会随着新行的到来而更新。我看到的唯一解决方案是将代码展平,但我想这样维护它。在
编辑:我修改了一点原始代码,以适应文本的额外功能,但如果不展开代码,它也不起作用。所以上面的代码不是我提到的原因。以下代码工作正常,并通过所有测试:macros = []
warg_keep = re.compile("newcommand\*\{(.*)\}\[(.*)\]\{(.*)")
woarg_keep = re.compile("newcommand\*\{(.*)\}\{(.*)")
warg_one = re.compile("newcommand\*\{(.*)\}\[(.*)\]\{(.*)\}")
woarg_one = woarg = re.compile("newcommand\*\{(.*)\}\{(.*)\}")
keep = False
for line in open(file).readlines():
line = line.strip()
if len(line) == 0 or line[0] == "%":
continue
if not keep:
newcommand = {"key":"","command":"","args":[]}
added = False
if "newcommand" in line and line [-1] == "%":
clean_line = line[0:-1]
keep = True
newcommand = get_cmd_from_line(warg_keep,woarg_keep,clean_line)
if "newcommand" in line and line[-1] != "%":
newcommand = get_cmd_from_line(warg_one, woarg_one, line)
added = True
if not "newcommand" in line and keep:
# Now it dos not matter how it ends, the command will always be added the line without the
# last character, it can be either % or } but it shouldn't be added
newcommand["command"] += line[0:-1]
if not "newcommand" in line and keep and line[-1] != "%":
# End the keep
keep = False
added = True
if added:
macros.append(newcommand)