开发者

vim-latex: Automatically recognize custom commands

开发者 https://www.devze.com 2023-04-10 05:17 出处:网络
I switched to vim-latex and have the following issue: I frequently define new convenient commands for easier editing via \\newcommand. My own commands usually take 2 or more parameters.

I switched to vim-latex and have the following issue: I frequently define new convenient commands for easier editing via \newcommand. My own commands usually take 2 or more parameters.

So let's for now assume I creat开发者_StackOverflow社区ed a command mycommand that takes 3 parameters.

Is there a way to tell vim-latex to automatically recognize my custom commands, so that I can simply type mycommand and press <F7> (or anything equivalent) and vim automatically converts this to \mycommand{<++>}{<++>}{<++>}<++>?

Note: I know about Tex_Com_name, but since I create new commands that often, I don't want to do this all the time.


Since this seems to be a nonexistent feature in vim, I've created it myself. I didn't do in-depth tests, but it seems to work quite well so far.

" 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()
0

精彩评论

暂无评论...
验证码 换一张
取 消