vim-latex:自动识别自定义命令

时间:2011-10-04 08:27:16

标签: macros vim

我切换到vim-latex并遇到以下问题:我经常定义新的便捷命令,以便通过\newcommand进行更轻松的编辑。我自己的命令通常需要2个或更多参数。

现在让我们假设我创建了一个带有3个参数的命令mycommand

有没有办法告诉vim-latex自动识别我的自定义命令,这样我只需输入mycommand并按<F7>(或任何等效的),vim会自动将其转换为{{ 1}}?

注意:我知道Tex_Com_name,但由于我经常创建新命令,所以我不想一直这样做。

1 个答案:

答案 0 :(得分:0)

由于这似乎是vim中不存在的功能,我自己创建了它。我没有进行深入的测试,但到目前为止似乎工作得很好。

" latex_helper.vim
function! GetCustomLatexCommands()
python << EOP

import os
import os.path
import re

def readFile(p):
    """Reads a file and extracts custom commands"""
    f = open(p)
    commands = []
    for _line in f:
        line = _line.strip()
        # search for included files
        tmp = re.search(r"(input|include){(.*)}", line)
        if tmp != None:
            path = tmp.group(2)
            newpath = os.path.join(os.path.dirname(p), path)
            if os.path.exists(newpath) and os.path.isfile(newpath):
                commands.extend(readFile(newpath))
            elif os.path.exists(newpath+".tex") and os.path.isfile(newpath+".tex"):
                commands.extend(readFile(newpath+".tex"))
        tmp = re.search(r"newcommand{(.*?)}\[(.*?)\]", line)
        if tmp != None:
            cmd = tmp.group(1)
            argc = int(tmp.group(2))
            commands.append((cmd[1:], argc))
    return commands

def getMain(path, startingpoint = None):
    """Goes folders upwards until it finds a *.latexmain file"""
    if startingpoint==None:
        startingpoint = path
    files = []
    if os.path.isdir(path):
        files = os.listdir(path)
    files = [os.path.join(path, s) for s in files if s.split(".")[-1] == "latexmain"]
    if len(files) >= 1:
        return os.path.splitext(files[0])[0]
    if os.path.dirname(path) != path:
        return getMain(os.path.dirname(path), startingpoint)
    return startingpoint

def GetCustomLatexCommands():
    """Reads all custom commands and adds them to givm"""
    import vim
    cmds = readFile(getMain(vim.current.buffer.name))
    for (cmd, argc) in cmds:
        vim.command('let g:Tex_Com_%s="\\\\%s%s <++>"'%(cmd, cmd, "{<++>}"*argc))

GetCustomLatexCommands()
EOP
endfunction

autocmd BufRead *.tex :call GetCustomLatexCommands()