为什么我要从这个vimscript得到E127?

2024-10-03 17:19:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下vimscript.vim/ftplugin目录:

" change to header file from c file or vice versa
function! CppAlter()
python << endpy
import vim
import os
bufferNames = [os.path.basename(b.name) for b in vim.buffers]
currentBufName = vim.eval("expand('%:p:t')")
currentBufStem, currentBufExt = os.path.splitext(currentBufName)
if currentBufExt == ".cpp" or currentBufExt == ".c" or currentBufExt == ".cc":
    altBufName1 = currentBufStem + ".h"
    altBufName2 = currentBufStem + ".hpp"
    if altBufName1 in bufferNames:
        vim.command("b " + altBufName1)
    elif altBufName2 in bufferNames:
        vim.command("b " + altBufName2)
    else:
        raise ValueError("No header file corresponding to this c file")
elif currentBufExt == ".h" or currentBufExt == ".hpp":
    altBufName1 = currentBufStem + ".cpp"
    altBufName2 = currentBufStem + ".c"
    altBufName3 = currentBufStem + ".cc"
    if altBufName1 in bufferNames:
        vim.command("b " + altBufName1)
    elif altBufName2 in bufferNames:
        vim.command("b " + altBufName2)
    elif altBufName3 in bufferNames:
        vim.command("b " + altBufName3)
    else:
        raise ValueError("No c file corresponding to this header file")
else:
    raise ValueError("This is not a c type file")
endpy
endfunction

nnoremap <leader>vc :call CppAlter()<cr>
inoremap <leader>vc <esc>:call CppAlter()<cr>

当我打开vim时,我得到一个错误:

^{pr2}$

但是如果我把它保存在/tmp中并显式地:so/tmp/x.vim,就没有error msg。 想知道这里怎么了。在


Tags: ortoinosvimcommandfileheader
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:43

在函数内部,您正在加载另一个缓冲区(例如vim.command("b " + altBufName1))。当该缓冲区具有相同的文件类型时,当前的ftplugin脚本将再次作为filetype plugin处理的一部分源代码,但是原始函数还没有返回,因此得到E127。在

解决方案

我建议将函数本身放入一个自动加载脚本,例如在~/.vim/autoload/ft/cppalter.vim中:

function! ft#cppalter#CppAlter()
    ...

您的ftplugin脚本变得更小更高效,因为该函数只源于一次:

^{pr2}$

(您可能应该在这里使用:nnoremap <buffer>来限制映射的范围。)

备选方案

如果不想将其分解,请将函数定义移到底部并添加一个保护,如:

nnoremap <leader>vc :...

if exists('*CppAlter')
    finish
endif
function! CppAlter()
    ...

相关问题 更多 >