调用system()函数,Vim脚本

时间:2012-11-27 14:37:50

标签: svn vim

当我遇到问题时,我试图在Vim 7.3中自定义状态行。

我正在尝试将SVN信息放在状态行中,所以我做了类似这样的事情:

function! DrawStatusLine()
    let svn = system("svn info")
    let l:status = " "
    let l:status = l:status . svn
    let l:status = l:status . "%t"       "tail of the filename
    let l:status = l:status . "%*"
    let l:status = l:status . "[%{strlen(&fenc)?&fenc:'none'}," "file encoding
    let l:status = l:status . "%{&ff}]" "file format
    let l:status = l:status . "%h"      "help file flag
    let l:status = l:status . "%m"      "modified flag
    let l:status = l:status . "%r"      "read only flag
    let l:status = l:status . "%="      "left/right separator
    let l:status = l:status . "%c,"     "cursor column
    let l:status = l:status . "%l/%L"   "cursor line/total lines
    let l:status = l:status . "\ %P"    "percent through file
    return l:status
endfunction

set statusline=%!DrawStatusLine()

但是在调用sytem()之后,光标移动得非常慢。每次移动光标时似乎都会调用system(实际上,每当窗口中发生某些事情时,似乎都会调用它)。

你知道我为什么会这样做吗?

这是.vimrc的其余部分,我没有使用异国情调的插件,而且我在Cygwin(Windows XP)下。

" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim"
    finish
endif

" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible

" Management of console or GUI settings.
if has("gui_running")
    " We are in gVim
    " Linux
    if has("gui_gtk2")
        :set guifont=DejaVu\ Sans\ Mono\ 11
    " Windows
    elseif has("gui_win32")
        :set guifont=DejaVu_Sans_Mono:h11:cANSI:
    endif
else
    " We are in a console
    set background=dark
endif

" Manage colors.
if filereadable($VIMRUNTIME . "/colors/wombat256.vim") ||
            \ filereadable($VIM . "/vimfiles/colors/wombat256.vim") ||
            \ filereadable($HOME . "/.vim/colors/wombat256.vim")
    colorscheme wombat256
elseif filereadable($VIMRUNTIME . "/colors/wombat.vim") ||
            \ filereadable($VIM . "/vimfiles/colors/wombat.vim") ||
            \ filereadable($HOME . "/.vim/colors/wombat.vim")
    colorscheme wombat
else
    colorscheme desert
endif

" allow backspacing over everything in insert mode
set backspace=indent,eol,start
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching

" For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries
let &guioptions = substitute(&guioptions, "t", "", "g")

" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
    set mouse=a
endif

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
    syntax on
    set hlsearch
endif

" Only do this part when compiled with support for autocommands.
if has("autocmd")

    " Enable file type detection.
    " Use the default filetype settings, so that mail gets 'tw' set to 72,
    " 'cindent' is on in C files, etc.
    " Also load indent files, to automatically do language-dependent indenting.
    filetype plugin indent on

    " Put these in an autocmd group, so that we can delete them easily.
    augroup vimrcEx
        autocmd!

        " For all text files set 'textwidth' to 78 characters.
        autocmd FileType text setlocal textwidth=78

        " When editing a file, always jump to the last known cursor position.
        " Don't do it when the position is invalid or when inside an event handler
        " (happens when dropping a file on gvim).
        " Also don't do it when the mark is in the first line, that is the default
        " position when opening a file.
        autocmd BufReadPost *
                    \ if line("'\"") > 1 && line("'\"") <= line("$") |
                    \   exe "normal! g`\"" |
                    \ endif

    augroup END

else

    set autoindent " always set autoindenting on

endif " has("autocmd")

" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
    command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
                \ | wincmd p | diffthis
endif

" Update the path with the dir where we opened Vim
set path=.,$PWD/**
" Now that we set the path to be recursive, disable
" the option that looking for completion in included files.
" Indeed, it can slow the process hard. We use tags instead.
set complete-=i

" Allow editing everywhere
set virtualedit=all

" No bells
set errorbells
set novisualbell
set vb t_vb=

" Show status bar
set laststatus=2
let loaded_matchparen = 1

" Draw the status line.
" Status line that rocks.
function! DrawStatusLine()
    let svn = system("svn info")
    let l:status = " "
    let l:status = l:status . "%t"       "tail of the filename
    let l:status = l:status . "%*"
    let l:status = l:status . "[%{strlen(&fenc)?&fenc:'none'}," "file encoding
    let l:status = l:status . "%{&ff}]" "file format
    let l:status = l:status . "%h"      "help file flag
    let l:status = l:status . "%m"      "modified flag
    let l:status = l:status . "%r"      "read only flag
    let l:status = l:status . "%="      "left/right separator
    let l:status = l:status . "%c,"     "cursor column
    let l:status = l:status . "%l/%L"   "cursor line/total lines
    let l:status = l:status . "\ %P"    "percent through file
    return l:status
endfunction

set statusline=%!DrawStatusLine()

" Highlight current line
set cursorline

" Add visible lines when start or end of the screen (3 lines)
set scrolloff=3

" Backup
set nobackup

" No preview in ins-completion.
set completeopt=menu

" Commands completion on status line.
set wildmenu

" Don't redraw while executing macros
set lazyredraw

" K = :help
set keywordprg=

" Diff always vertical
set diffopt+=vertical

" Use utf-8
set encoding=utf-8
set fileencoding=utf-8

" Remember buffer changes when jumping around.
set hidden

"""""""""""""""""
" Developpement "
"""""""""""""""""

" Line numbers
set nu

" Tabulation of 4 spaces
set expandtab
set smarttab
set shiftwidth=4
set softtabstop=4
set tabstop=4

" Show when a line exceeds 80 chars
highlight Overlength ctermbg=red ctermfg=white guibg=#592929

" Highlight Tabs and Spaces
" highlight Tab ctermbg=darkgray guibg=darkgray
" au BufWinEnter * let w:m2=matchadd('Tab', '/[^\t]\zs\t\+/', -1)
highlight Space ctermbg=darkblue guibg=darkblue
augroup matches
    autocmd!
    autocmd BufWinEnter * match Overlength /\%81v.*/
    autocmd BufWinEnter * let w:m3=matchadd('Space', '\s\+$\| \+\ze\t', -1)
    " Matches are memory greedy, shut them when the window is left
    " Mybe it is redondant.
    autocmd BufWinLeave * call clearmatches()
augroup END

set list listchars=tab:\ \ ,trail:.


" Redraw status line when saving.
" autocmd BufWritePost * set statusline=%!DrawStatusLine()

" Special indentation for switch / case
" Indentation when in unclosed (.
set cino=l1,(0

" Load Doxygen syntax
let g:load_doxygen_syntax=1

"""""""""""""""""
" Taglist
"""""""""""""""""
let Tlist_Use_Right_Window=1

"""""""""""""""""
" cscope
"""""""""""""""""
if has("cscope") && executable("cscope") && !has("gui_win32")
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory
    if filereadable("cscope.out")
        cs add cscope.out
    endif
    " abbreviations
    cnoreabbrev csf cs find
    set csverb
endif

"""""""""""""
"  Mapping  "
"""""""""""""

" Don't use Ex mode, use Q for formatting
map Q gq

" CTRL-U in insert mode deletes a lot.  Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>

" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","
let g:mapleader = ","

" After repeating command, return where we were.
map . .`[

" Switch tab.
noremap <A-h> gT
noremap <A-l> gt
" For dummy terminals
noremap <Esc>h gT
noremap <Esc>l gt

" Remap the Esc command
inoremap kj <Esc>
inoremap lk <Esc>

" Better for wrapped lines
nnoremap j gj
nnoremap k gk

" omnicompletion : words
inoremap <leader>, <C-x><C-o>

" Turn off highlighting in search.
nmap <leader>/ :nohlsearch<CR>

" edit .vimrc
nmap <silent> <leader>ev :tabnew $HOME/.vimrc<CR>
" source .vimrc
nmap <silent> <leader>sv :so $HOME/.vimrc<CR>

nnoremap <silent><leader>dh :call SVNDiff()<CR>

" Build C symbols.
function! BuildSymbols()
    if has("cscope") && executable("cscope") && !has("gui_win32")
        " kill all connection.
        execute "cs kill -1"
        execute "!ctags -R && cscope -Rb"
        execute "cs add cscope.out"
    else
        execute "!ctags -R"
    endif
endfunction

" Run Vim diff on HEAD copy in SVN.
function! SVNDiff()
    let fn = expand("%:p")
    let newfn = fn .  ".HEAD"
    let catstat = system("svn cat " . fn . " > " . newfn)
    if catstat == 0
        execute 'diffsplit ' . newfn
        execute 'set filetype=c'
    else
        echo "*** ERROR: svn cat failed for ". fn . " (as " . newfn . ")"
    endif
endfunction

" Build symbols with F2.
nnoremap <F2> :call BuildSymbols()<CR>

" Taglist with F3
nnoremap <F3> :TlistToggle<CR>

" Open a explorer on a vertical split of 26.
nnoremap <F4> :26Vexplore<CR>

" When you forgot to open the file as sudo.
cmap w!! %!sudo tee > /dev/null %

3 个答案:

答案 0 :(得分:5)

'statusline'值一直在评估,它还能如何显示光标位置等信息?!不要在那里做耗时的事情;甚至很长的Vimscript片段都会大大减慢Vim的速度,system()是你可以做的最差的。

相反,在状态行中包含一个(缓冲区 - 本地)变量(例如%{exists('b:svn_info')?b:svn_info:''}),并使用适当的autocmds来设置和更新它:

:autocmd BufRead * let b:svn_info = system('svn info')

答案 1 :(得分:2)

现有答案的一个补充:有些插件已经自己保存缓存(如aurum)或者只在BufEnter上执行一次(如VCSCommand)。上述两个都能够替换您的SVNDiff功能。

VCSCommand将提供文件状态(仅限未知和新的)或(如果状态不是)修订,存储库以及存储库中新版本的存在。我必须在此重复一遍,在切换到另一个缓冲区然后再返回之前,它不会更新状态。

Aurum更灵活*,但除非你愿意每N秒经历输入滞后或切换到mercurial,否则你被迫使用文件状态和分支**(最后一个是当前的修订版信息)。 Subversion状态始终映射到八个mercurial状态之一。除非您使用+ python编译vim,否则它使用缓存方法(并且缓存失效将使您遭受延迟),但是+ python的事情是不同的:状态是在每个N秒的单独进程中获得的,并且不会因任何延迟而烦扰您除非你做了一些导致缓存失效的事情(目前使用+ python,你只会在失效发生时受到延迟,并且不会注意到它认为它是你的行为的一部分导致失效,但没有滞后被视为发生当状态行无效时。)

*从文档中我猜VCSCommand的作者打算让用户自己编写更好的状态行,但我没有看到任何可以帮助他们的东西。也许我只是在寻找错误的位置。

**此处的分支表示“存储库根URL中不存在的根目录URL的尾随部分”。根目录是嵌套最少的目录,其.svn子目录和存储库根URL等于当前目录(包含当前缓冲区的目录)。

即使您不愿意使用aurum,也可以随意借用重复执行的命令或缓存实现。

答案 2 :(得分:1)

这是预期的行为:每次移动光标时都会更新整个状态行,从而每次执行某些操作时都会执行svn info。可能每秒很多次。

这显然是浪费,因为当前文件的svn状态不会每秒改变10次。

您应该缓存此信息,并且只能在写入时或每{{}}}分钟或其他任何位置检索该信息。