157

Vi 和 Vim 允许非常棒的自定义,通常存储在.vimrc文件中。程序员的典型功能是语法高亮、智能缩进等。

你还有什么其他的高效编程技巧,隐藏在你的 .vimrc 中?

我最感兴趣的是重构、自动类和类似的生产力宏,尤其是对于 C#。

4

72 回答 72

104

你自找的 :-)

"{{{Auto Commands

" Automatically cd into the directory that the file is in
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')

" Remove any trailing whitespace that is in the file
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif

" Restore cursor position to where it was before
augroup JumpCursorOnEdit
   au!
   autocmd BufReadPost *
            \ if expand("<afile>:p:h") !=? $TEMP |
            \   if line("'\"") > 1 && line("'\"") <= line("$") |
            \     let JumpCursorOnEdit_foo = line("'\"") |
            \     let b:doopenfold = 1 |
            \     if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
            \        let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
            \        let b:doopenfold = 2 |
            \     endif |
            \     exe JumpCursorOnEdit_foo |
            \   endif |
            \ endif
   " Need to postpone using "zv" until after reading the modelines.
   autocmd BufWinEnter *
            \ if exists("b:doopenfold") |
            \   exe "normal zv" |
            \   if(b:doopenfold > 1) |
            \       exe  "+".1 |
            \   endif |
            \   unlet b:doopenfold |
            \ endif
augroup END

"}}}

"{{{Misc Settings

" Necesary  for lots of cool vim things
set nocompatible

" This shows what you are typing as a command.  I love this!
set showcmd

" Folding Stuffs
set foldmethod=marker

" Needed for Syntax Highlighting and stuff
filetype on
filetype plugin on
syntax enable
set grepprg=grep\ -nH\ $*

" Who doesn't like autoindent?
set autoindent

" Spaces are better than a tab character
set expandtab
set smarttab

" Who wants an 8 character tab?  Not me!
set shiftwidth=3
set softtabstop=3

" Use english for spellchecking, but don't spellcheck by default
if version >= 700
   set spl=en spell
   set nospell
endif

" Real men use gcc
"compiler gcc

" Cool tab completion stuff
set wildmenu
set wildmode=list:longest,full

" Enable mouse support in console
set mouse=a

" Got backspace?
set backspace=2

" Line Numbers PWN!
set number

" Ignoring case is a fun trick
set ignorecase

" And so is Artificial Intellegence!
set smartcase

" This is totally awesome - remap jj to escape in insert mode.  You'll never type jj anyway, so it's great!
inoremap jj <Esc>

nnoremap JJJJ <Nop>

" Incremental searching is sexy
set incsearch

" Highlight things that we find with the search
set hlsearch

" Since I use linux, I want this
let g:clipbrdDefaultReg = '+'

" When I close a tab, remove the buffer
set nohidden

" Set off the other paren
highlight MatchParen ctermbg=4
" }}}

"{{{Look and Feel

" Favorite Color Scheme
if has("gui_running")
   colorscheme inkpot
   " Remove Toolbar
   set guioptions-=T
   "Terminus is AWESOME
   set guifont=Terminus\ 9
else
   colorscheme metacosm
endif

"Status line gnarliness
set laststatus=2
set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]

" }}}

"{{{ Functions

"{{{ Open URL in browser

function! Browser ()
   let line = getline (".")
   let line = matchstr (line, "http[^   ]*")
   exec "!konqueror ".line
endfunction

"}}}

"{{{Theme Rotating
let themeindex=0
function! RotateColorTheme()
   let y = -1
   while y == -1
      let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#"
      let x = match( colorstring, "#", g:themeindex )
      let y = match( colorstring, "#", x + 1 )
      let g:themeindex = x + 1
      if y == -1
         let g:themeindex = 0
      else
         let themestring = strpart(colorstring, x + 1, y - x - 1)
         return ":colorscheme ".themestring
      endif
   endwhile
endfunction
" }}}

"{{{ Paste Toggle
let paste_mode = 0 " 0 = normal, 1 = paste

func! Paste_on_off()
   if g:paste_mode == 0
      set paste
      let g:paste_mode = 1
   else
      set nopaste
      let g:paste_mode = 0
   endif
   return
endfunc
"}}}

"{{{ Todo List Mode

function! TodoListMode()
   e ~/.todo.otl
   Calendar
   wincmd l
   set foldlevel=1
   tabnew ~/.notes.txt
   tabfirst
   " or 'norm! zMzr'
endfunction

"}}}

"}}}

"{{{ Mappings

" Open Url on this line with the browser \w
map <Leader>w :call Browser ()<CR>

" Open the Project Plugin <F2>
nnoremap <silent> <F2> :Project<CR>

" Open the Project Plugin
nnoremap <silent> <Leader>pal  :Project .vimproject<CR>

" TODO Mode
nnoremap <silent> <Leader>todo :execute TodoListMode()<CR>

" Open the TagList Plugin <F3>
nnoremap <silent> <F3> :Tlist<CR>

" Next Tab
nnoremap <silent> <C-Right> :tabnext<CR>

" Previous Tab
nnoremap <silent> <C-Left> :tabprevious<CR>

" New Tab
nnoremap <silent> <C-t> :tabnew<CR>

" Rotate Color Scheme <F8>
nnoremap <silent> <F8> :execute RotateColorTheme()<CR>

" DOS is for fools.
nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR>

" Paste Mode!  Dang! <F10>
nnoremap <silent> <F10> :call Paste_on_off()<CR>
set pastetoggle=<F10>

" Edit vimrc \ev
nnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR>

" Edit gvimrc \gv
nnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR>

" Up and down are more logical with g..
nnoremap <silent> k gk
nnoremap <silent> j gj
inoremap <silent> <Up> <Esc>gka
inoremap <silent> <Down> <Esc>gja

" Good call Benjie (r for i)
nnoremap <silent> <Home> i <Esc>r
nnoremap <silent> <End> a <Esc>r

" Create Blank Newlines and stay in Normal mode
nnoremap <silent> zj o<Esc>
nnoremap <silent> zk O<Esc>

" Space will toggle folds!
nnoremap <space> za

" Search mappings: These will make it so that going to the next one in a
" search will center on the line it's found in.
map N Nzz
map n nzz

" Testing
set completeopt=longest,menuone,preview

inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"
inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"

" Swap ; and :  Convenient.
nnoremap ; :
nnoremap : ;

" Fix email paragraphs
nnoremap <leader>par :%s/^>$//<CR>

"ly$O#{{{ "lpjjj_%A#}}}jjzajj

"}}}

"{{{Taglist configuration
let Tlist_Use_Right_Window = 1
let Tlist_Enable_Fold_Column = 0
let Tlist_Exit_OnlyWindow = 1
let Tlist_Use_SingleClick = 1
let Tlist_Inc_Winwidth = 0
"}}}

let g:rct_completion_use_fri = 1
"let g:Tex_DefaultTargetFormat = "pdf"
let g:Tex_ViewRule_pdf = "kpdf"

filetype plugin indent on
syntax on
于 2008-10-05T05:57:56.637 回答
73

这不在我的 .vimrc 文件中,但昨天我了解了该]p命令。这就像粘贴缓冲区的内容一样p,但它会自动调整缩进以匹配光标所在的行!这非常适合移动代码。

于 2008-10-02T22:17:21.510 回答
52

我使用以下内容将所有临时文件和备份文件保存在一个地方:

set backup
set backupdir=~/.vim/backup
set directory=~/.vim/tmp

将杂乱无章的工作目录保存在各处。

您必须先创建这些目录,vim不会为您创建它们。

于 2008-10-02T22:17:22.803 回答
31

上面发布的某人(即弗鲁)有这行:

“自动 cd 进入文件所在的目录:”

autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')

我自己也在做类似的事情,直到我发现可以通过内置设置完成同样的事情:

set autochdir

我认为类似的事情发生在我身上好几次了。Vim 有很多不同的内置设置和选项,有时自己动手做比在文档中搜索内置方法更快、更容易。

于 2009-03-17T00:23:50.367 回答
28

我的最新添加是为了突出显示当前行

set cul                                           # highlight current line
hi CursorLine term=none cterm=none ctermbg=3      # adjust color
于 2009-01-24T11:40:48.033 回答
23

2012 年更新:我现在真的建议查看vim-powerline,它已经取代了我的旧状态行脚本,尽管目前缺少一些我错过的功能。


我想说我的 vimrc中的状态行内容可能是最有趣/最有用的(从这里的作者 vimrc和相应的博客文章中摘录)。

截屏:

状态行 http://img34.imageshack.us/img34/849/statusline.png

代码:

"recalculate the trailing whitespace warning when idle, and after saving
autocmd cursorhold,bufwritepost * unlet! b:statusline_trailing_space_warning

"return '[\s]' if trailing white space is detected
"return '' otherwise
function! StatuslineTrailingSpaceWarning()
    if !exists("b:statusline_trailing_space_warning")

        if !&modifiable
            let b:statusline_trailing_space_warning = ''
            return b:statusline_trailing_space_warning
        endif

        if search('\s\+$', 'nw') != 0
            let b:statusline_trailing_space_warning = '[\s]'
        else
            let b:statusline_trailing_space_warning = ''
        endif
    endif
    return b:statusline_trailing_space_warning
endfunction


"return the syntax highlight group under the cursor ''
function! StatuslineCurrentHighlight()
    let name = synIDattr(synID(line('.'),col('.'),1),'name')
    if name == ''
        return ''
    else
        return '[' . name . ']'
    endif
endfunction

"recalculate the tab warning flag when idle and after writing
autocmd cursorhold,bufwritepost * unlet! b:statusline_tab_warning

"return '[&et]' if &et is set wrong
"return '[mixed-indenting]' if spaces and tabs are used to indent
"return an empty string if everything is fine
function! StatuslineTabWarning()
    if !exists("b:statusline_tab_warning")
        let b:statusline_tab_warning = ''

        if !&modifiable
            return b:statusline_tab_warning
        endif

        let tabs = search('^\t', 'nw') != 0

        "find spaces that arent used as alignment in the first indent column
        let spaces = search('^ \{' . &ts . ',}[^\t]', 'nw') != 0

        if tabs && spaces
            let b:statusline_tab_warning = '[mixed-indenting]'
        elseif (spaces && !&et) || (tabs && &et)
            let b:statusline_tab_warning = '[&et]'
        endif
    endif
    return b:statusline_tab_warning
endfunction

"recalculate the long line warning when idle and after saving
autocmd cursorhold,bufwritepost * unlet! b:statusline_long_line_warning

"return a warning for "long lines" where "long" is either &textwidth or 80 (if
"no &textwidth is set)
"
"return '' if no long lines
"return '[#x,my,$z] if long lines are found, were x is the number of long
"lines, y is the median length of the long lines and z is the length of the
"longest line
function! StatuslineLongLineWarning()
    if !exists("b:statusline_long_line_warning")

        if !&modifiable
            let b:statusline_long_line_warning = ''
            return b:statusline_long_line_warning
        endif

        let long_line_lens = s:LongLines()

        if len(long_line_lens) > 0
            let b:statusline_long_line_warning = "[" .
                        \ '#' . len(long_line_lens) . "," .
                        \ 'm' . s:Median(long_line_lens) . "," .
                        \ '$' . max(long_line_lens) . "]"
        else
            let b:statusline_long_line_warning = ""
        endif
    endif
    return b:statusline_long_line_warning
endfunction

"return a list containing the lengths of the long lines in this buffer
function! s:LongLines()
    let threshold = (&tw ? &tw : 80)
    let spaces = repeat(" ", &ts)

    let long_line_lens = []

    let i = 1
    while i <= line("$")
        let len = strlen(substitute(getline(i), '\t', spaces, 'g'))
        if len > threshold
            call add(long_line_lens, len)
        endif
        let i += 1
    endwhile

    return long_line_lens
endfunction

"find the median of the given array of numbers
function! s:Median(nums)
    let nums = sort(a:nums)
    let l = len(nums)

    if l % 2 == 1
        let i = (l-1) / 2
        return nums[i]
    else
        return (nums[l/2] + nums[(l/2)-1]) / 2
    endif
endfunction


"statusline setup
set statusline=%f "tail of the filename

"display a warning if fileformat isnt unix
set statusline+=%#warningmsg#
set statusline+=%{&ff!='unix'?'['.&ff.']':''}
set statusline+=%*

"display a warning if file encoding isnt utf-8
set statusline+=%#warningmsg#
set statusline+=%{(&fenc!='utf-8'&&&fenc!='')?'['.&fenc.']':''}
set statusline+=%*

set statusline+=%h "help file flag
set statusline+=%y "filetype
set statusline+=%r "read only flag
set statusline+=%m "modified flag

"display a warning if &et is wrong, or we have mixed-indenting
set statusline+=%#error#
set statusline+=%{StatuslineTabWarning()}
set statusline+=%*

set statusline+=%{StatuslineTrailingSpaceWarning()}

set statusline+=%{StatuslineLongLineWarning()}

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

"display a warning if &paste is set
set statusline+=%#error#
set statusline+=%{&paste?'[paste]':''}
set statusline+=%*

set statusline+=%= "left/right separator

function! SlSpace()
    if exists("*GetSpaceMovement")
        return "[" . GetSpaceMovement() . "]"
    else
        return ""
    endif
endfunc
set statusline+=%{SlSpace()}

set statusline+=%{StatuslineCurrentHighlight()}\ \ "current highlight
set statusline+=%c, "cursor column
set statusline+=%l/%L "cursor line/total lines
set statusline+=\ %P "percent through file
set laststatus=2

除其他外,它会在状态行上通知通常的标准文件信息,但还包括其他内容,例如 :set paste、混合缩进、尾随空格等的警告。如果您对代码格式特别感兴趣,这将非常有用。

此外,如屏幕截图所示,将其与 syntastic结合使用可以突出显示任何语法错误(假设您选择的语言捆绑了相关的语法检查器。

于 2009-08-02T15:43:34.117 回答
19

我的迷你版:

syntax on
set background=dark
set shiftwidth=2
set tabstop=2

if has("autocmd")
  filetype plugin indent on
endif

set showcmd             " Show (partial) command in status line.
set showmatch           " Show matching brackets.
set ignorecase          " Do case insensitive matching
set smartcase           " Do smart case matching
set incsearch           " Incremental search
set hidden              " Hide buffers when they are abandoned

大版本,从各个地方收集:

syntax on
set background=dark
set ruler                     " show the line number on the bar
set more                      " use more prompt
set autoread                  " watch for file changes
set number                    " line numbers
set hidden
set noautowrite               " don't automagically write on :next
set lazyredraw                " don't redraw when don't have to
set showmode
set showcmd
set nocompatible              " vim, not vi
set autoindent smartindent    " auto/smart indent
set smarttab                  " tab and backspace are smart
set tabstop=2                 " 6 spaces
set shiftwidth=2
set scrolloff=5               " keep at least 5 lines above/below
set sidescrolloff=5           " keep at least 5 lines left/right
set history=200
set backspace=indent,eol,start
set linebreak
set cmdheight=2               " command line two lines high
set undolevels=1000           " 1000 undos
set updatecount=100           " switch every 100 chars
set complete=.,w,b,u,U,t,i,d  " do lots of scanning on tab completion
set ttyfast                   " we have a fast terminal
set noerrorbells              " No error bells please
set shell=bash
set fileformats=unix
set ff=unix
filetype on                   " Enable filetype detection
filetype indent on            " Enable filetype-specific indenting
filetype plugin on            " Enable filetype-specific plugins
set wildmode=longest:full
set wildmenu                  " menu has tab completion
let maplocalleader=','        " all my macros start with ,
set laststatus=2

"  searching
set incsearch                 " incremental search
set ignorecase                " search ignoring case
set hlsearch                  " highlight the search
set showmatch                 " show matching bracket
set diffopt=filler,iwhite     " ignore all whitespace and sync

"  backup
set backup
set backupdir=~/.vim_backup
set viminfo=%100,'100,/100,h,\"500,:100,n~/.viminfo
"set viminfo='100,f1

" spelling
if v:version >= 700
  " Enable spell check for text files
  autocmd BufNewFile,BufRead *.txt setlocal spell spelllang=en
endif

" mappings
" toggle list mode
nmap <LocalLeader>tl :set list!<cr>
" toggle paste mode
nmap <LocalLeader>pp :set paste!<cr>
于 2009-03-16T23:30:03.070 回答
13

有时最简单的东西是最有价值的。我的 .vimrc 中完全不可缺少的两行:

诺尔;:
诺尔, ;
于 2009-08-18T19:40:59.010 回答
12

杂项。设置:

  1. 关闭烦人的错误铃声:

    set noerrorbells
    set visualbell
    set t_vb=
    
  2. 使用换行使光标按预期移动:

    inoremap <Down> <C-o>gj
    inoremap <Up> <C-o>gk
    
  3. 在目录中查找ctags“标签”文件,直到找到一个:

    set tags=tags;/
    
  4. 使用 Python 语法显示 SCons 文件:

    autocmd BufReadPre,BufNewFile SConstruct set filetype=python
    autocmd BufReadPre,BufNewFile SConscript set filetype=python
    
于 2008-10-03T00:46:14.600 回答
8

我的大量评论 vimrc,带有 readline-esque (emacs) 键绑定:

if version >= 700

"------ Meta ------"

" clear all autocommands! (this comment must be on its own line)
autocmd!

set nocompatible                " break away from old vi compatibility
set fileformats=unix,dos,mac    " support all three newline formats
set viminfo=                    " don't use or save viminfo files

"------ Console UI & Text display ------"

set cmdheight=1                 " explicitly set the height of the command line
set showcmd                     " Show (partial) command in status line.
set number                      " yay line numbers
set ruler                       " show current position at bottom
set noerrorbells                " don't whine
set visualbell t_vb=            " and don't make faces
set lazyredraw                  " don't redraw while in macros
set scrolloff=5                 " keep at least 5 lines around the cursor
set wrap                        " soft wrap long lines
set list                        " show invisible characters
set listchars=tab:>·,trail:·    " but only show tabs and trailing whitespace
set report=0                    " report back on all changes
set shortmess=atI               " shorten messages and don't show intro
set wildmenu                    " turn on wild menu :e <Tab>
set wildmode=list:longest       " set wildmenu to list choice
if has('syntax')
    syntax on
    " Remember that rxvt-unicode has 88 colors by default; enable this only if
    " you are using the 256-color patch
    if &term == 'rxvt-unicode'
        set t_Co=256
    endif

    if &t_Co == 256
        colorscheme xoria256
    else
        colorscheme peachpuff
    endif
endif

"------ Text editing and searching behavior ------"

set nohlsearch                  " turn off highlighting for searched expressions
set incsearch                   " highlight as we search however
set matchtime=5                 " blink matching chars for .x seconds
set mouse=a                     " try to use a mouse in the console (wimp!)
set ignorecase                  " set case insensitivity
set smartcase                   " unless there's a capital letter
set completeopt=menu,longest,preview " more autocomplete <Ctrl>-P options
set nostartofline               " leave my cursor position alone!
set backspace=2                 " equiv to :set backspace=indent,eol,start
set textwidth=80                " we like 80 columns
set showmatch                   " show matching brackets
set formatoptions=tcrql         " t - autowrap to textwidth
                                " c - autowrap comments to textwidth
                                " r - autoinsert comment leader with <Enter>
                                " q - allow formatting of comments with :gq
                                " l - don't format already long lines

"------ Indents and tabs ------"

set autoindent                  " set the cursor at same indent as line above
set smartindent                 " try to be smart about indenting (C-style)
set expandtab                   " expand <Tab>s with spaces; death to tabs!
set shiftwidth=4                " spaces for each step of (auto)indent
set softtabstop=4               " set virtual tab stop (compat for 8-wide tabs)
set tabstop=8                   " for proper display of files with tabs
set shiftround                  " always round indents to multiple of shiftwidth
set copyindent                  " use existing indents for new indents
set preserveindent              " save as much indent structure as possible
filetype plugin indent on       " load filetype plugins and indent settings

"------ Key bindings ------"

" Remap broken meta-keys that send ^[
for n in range(97,122) " ASCII a-z
    let c = nr2char(n)
    exec "set <M-". c .">=\e". c
    exec "map  \e". c ." <M-". c .">"
    exec "map! \e". c ." <M-". c .">"
endfor

""" Emacs keybindings
" first move the window command because we'll be taking it over
noremap <C-x> <C-w>
" Movement left/right
noremap! <C-b> <Left>
noremap! <C-f> <Right>
" word left/right
noremap  <M-b> b
noremap! <M-b> <C-o>b
noremap  <M-f> w
noremap! <M-f> <C-o>w
" line start/end
noremap  <C-a> ^
noremap! <C-a> <Esc>I
noremap  <C-e> $
noremap! <C-e> <Esc>A
" Rubout word / line and enter insert mode
noremap  <C-w> i<C-w>
noremap  <C-u> i<C-u>
" Forward delete char / word / line and enter insert mode
noremap! <C-d> <C-o>x
noremap  <M-d> dw
noremap! <M-d> <C-o>dw
noremap  <C-k> Da
noremap! <C-k> <C-o>D
" Undo / Redo and enter normal mode
noremap  <C-_> u
noremap! <C-_> <C-o>u<Esc><Right>
noremap! <C-r> <C-o><C-r><Esc>

" Remap <C-space> to word completion
noremap! <Nul> <C-n>

" OS X paste (pretty poor implementation)
if has('mac')
    noremap  √ :r!pbpaste<CR>
    noremap! √ <Esc>√
endif

""" screen.vim REPL: http://github.com/ervandew/vimfiles
" send paragraph to parallel process
vmap <C-c><C-c> :ScreenSend<CR>
nmap <C-c><C-c> mCvip<C-c><C-c>`C
imap <C-c><C-c> <Esc><C-c><C-c><Right>
" set shell region height
let g:ScreenShellHeight = 12


"------ Filetypes ------"

" Vimscript
autocmd FileType vim setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4

" Shell
autocmd FileType sh setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4

" Lisp
autocmd Filetype lisp,scheme setlocal equalprg=~/.vim/bin/lispindent.lisp expandtab shiftwidth=2 tabstop=8 softtabstop=2

" Ruby
autocmd FileType ruby setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2

" PHP
autocmd FileType php setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4

" X?HTML & XML
autocmd FileType html,xhtml,xml setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2

" CSS
autocmd FileType css setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4

" JavaScript
" autocmd BufRead,BufNewFile *.json setfiletype javascript
autocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
let javascript_enable_domhtmlcss=1

"------ END VIM-500 ------"

endif " version >= 500
于 2009-10-28T19:04:04.577 回答
8

我不是世界上最先进的 vim'er,但这里有一些我捡到的

function! Mosh_Tab_Or_Complete()
    if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w'
        return "\<C-N>"
    else
        return "\<Tab>"
endfunction

inoremap <Tab> <C-R>=Mosh_Tab_Or_Complete()<CR>

使制表符自动完成功能确定您是要在此处放置一个单词还是一个实际的制表符(4 个空格)。

map cc :.,$s/^ *//<CR>

删除从此处到文件末尾的所有打开空格。出于某种原因,我发现这很有用。

set nu! 
set nobackup

显示行号,不要创建那些烦人的备份文件。无论如何,我从来没有从旧备份中恢复过任何东西。

imap ii <C-[>

在插入时,按两次 i 进入命令模式。我从来没有遇到过连续有 2 个 i 的单词或变量,这样我就不必让我的手指离开主行或按多个键来回切换。

于 2008-11-02T21:59:07.300 回答
7
syntax on
set cindent
set ts=4
set sw=4
set backspace=2
set laststatus=2
set nohlsearch
set modeline
set modelines=3
set ai
map Q gq

set vb t_vb=

set nowrap
set ss=5
set is
set scs
set ru

map <F2> <Esc>:w<CR>
map! <F2> <Esc>:w<CR>

map <F10> <Esc>:qa<CR>
map! <F10> <Esc>:qa<CR>

map <F9>  <Esc>:wqa<CR>
map! <F9>  <Esc>:wqa<CR>

inoremap <s-up> <Esc><c-w>W<Ins>
inoremap <s-down> <Esc><c-w>w<Ins>

nnoremap <s-up> <c-w>W
nnoremap <s-down> <c-w>w

" Fancy middle-line <CR>
inoremap <C-CR> <Esc>o
nnoremap <C-CR> o

" This is the way I like my quotation marks and various braces
inoremap '' ''<Left>
inoremap "" ""<Left>
inoremap () ()<Left>
inoremap <> <><Left>
inoremap {} {}<Left>
inoremap [] []<Left>
inoremap () ()<Left>

" Quickly set comma or semicolon at the end of the string
inoremap ,, <End>,
inoremap ;; <End>;
au FileType python inoremap :: <End>:


au FileType perl,python set foldlevel=0
au FileType perl,python set foldcolumn=4
au FileType perl,python set fen
au FileType perl        set fdm=syntax
au FileType python      set fdm=indent
au FileType perl,python set fdn=4
au FileType perl,python set fml=10
au FileType perl,python set fdo=block,hor,mark,percent,quickfix,search,tag,undo,search

au FileType perl,python abbr sefl self
au FileType perl abbr sjoft shift
au FileType perl abbr DUmper Dumper

function! ToggleNumberRow()
       if !exists("g:NumberRow") || 0 == g:NumberRow
               let g:NumberRow = 1
               call ReverseNumberRow()
       else
               let g:NumberRow = 0
               call NormalizeNumberRow()
       endif
endfunction


" Reverse the number row characters
function! ReverseNumberRow()
       " map each number to its shift-key character
       inoremap 1 !
       inoremap 2 @
       inoremap 3 #
       inoremap 4 $
       inoremap 5 %
       inoremap 6 ^
       inoremap 7 &
       inoremap 8 *
       inoremap 9 (
       inoremap 0 )
       inoremap - _
    inoremap 90 ()<Left>
       " and then the opposite
       inoremap ! 1
       inoremap @ 2
       inoremap # 3
       inoremap $ 4
       inoremap % 5
       inoremap ^ 6
       inoremap & 7
       inoremap * 8
       inoremap ( 9
       inoremap ) 0
       inoremap _ -
endfunction

" DO the opposite to ReverseNumberRow -- give everything back
function! NormalizeNumberRow()
       iunmap 1
       iunmap 2
       iunmap 3
       iunmap 4
       iunmap 5
       iunmap 6
       iunmap 7
       iunmap 8
       iunmap 9
       iunmap 0
       iunmap -
       "------
       iunmap !
       iunmap @
       iunmap #
       iunmap $
       iunmap %
       iunmap ^
       iunmap &
       iunmap *
       iunmap (
       iunmap )
       iunmap _
       inoremap () ()<Left>
endfunction

"call ToggleNumberRow()
nnoremap <M-n> :call ToggleNumberRow()<CR>

" Add use <CWORD> at the top of the file
function! UseWord(word)
       let spec_cases = {'Dumper': 'Data::Dumper'}
       let my_word = a:word
       if has_key(spec_cases, my_word)
               let my_word = spec_cases[my_word]
       endif

       let was_used = search("^use.*" . my_word, "bw")

       if was_used > 0
               echo "Used already"
               return 0
       endif

       let last_use = search("^use", "bW")
       if 0 == last_use
               last_use = search("^package", "bW")
               if 0 == last_use
                       last_use = 1
               endif
       endif

       let use_string = "use " . my_word . ";"
       let res = append(last_use, use_string)
       return 1
endfunction

function! UseCWord()
       let cline = line(".")
       let ccol = col(".")
       let ch = UseWord(expand("<cword>"))
       normal mu
       call cursor(cline + ch, ccol)

endfunction

function! GetWords(pattern)
       let cline = line(".")
       let ccol = col(".")
       call cursor(1,1)

       let temp_dict = {}
       let cpos = searchpos(a:pattern)
       while cpos[0] != 0
               let temp_dict[expand("<cword>")] = 1
               let cpos = searchpos(a:pattern, 'W')
       endwhile

       call cursor(cline, ccol)
       return keys(temp_dict)
endfunction

" Append the list of words, that match the pattern after cursor
function! AppendWordsLike(pattern)
       let word_list = sort(GetWords(a:pattern))
       call append(line("."), word_list)
endfunction


nnoremap <F7>  :call UseCWord()<CR>

" Useful to mark some code lines as debug statements
function! MarkDebug()
       let cline = line(".")
       let ctext = getline(cline)
       call setline(cline, ctext . "##_DEBUG_")
endfunction

" Easily remove debug statements
function! RemoveDebug()
       %g/#_DEBUG_/d
endfunction

au FileType perl,python inoremap <M-d> <Esc>:call MarkDebug()<CR><Ins>
au FileType perl,python inoremap <F6> <Esc>:call RemoveDebug()<CR><Ins>
au FileType perl,python nnoremap <F6> :call RemoveDebug()<CR>

" end Perl settings

nnoremap <silent> <F8> :TlistToggle<CR>
inoremap <silent> <F8> <Esc>:TlistToggle<CR><Esc>

function! AlwaysCD()
       if bufname("") !~ "^scp://" && bufname("") !~ "^sftp://" && bufname("") !~ "^ftp://"
               lcd %:p:h
       endif
endfunction
autocmd BufEnter * call AlwaysCD()

function! DeleteRedundantSpaces()
       let cline = line(".")
       let ccol = col(".")
       silent! %s/\s\+$//g
       call cursor(cline, ccol)
endfunction
au BufWrite * call DeleteRedundantSpaces()

set nobackup
set nowritebackup
set cul

colorscheme evening

autocmd FileType python set formatoptions=wcrq2l
autocmd FileType python set inc="^\s*from"
autocmd FileType python so /usr/share/vim/vim72/indent/python.vim

autocmd FileType c      set si
autocmd FileType mail   set noai
autocmd FileType mail   set ts=3
autocmd FileType mail   set tw=78
autocmd FileType mail   set shiftwidth=3
autocmd FileType mail   set expandtab
autocmd FileType xslt   set ts=4
autocmd FileType xslt   set shiftwidth=4
autocmd FileType txt    set ts=3
autocmd FileType txt    set tw=78
autocmd FileType txt    set expandtab

" Move cursor together with the screen
noremap <c-j> j<c-e>
noremap <c-k> k<c-y>

" Better Marks
nnoremap ' `
于 2009-10-28T12:31:20.333 回答
6

一些常见拼写错误的修复为我节省了惊人的时间:

:command WQ wq
:command Wq wq
:command W w
:command Q q

iab anf and
iab adn and
iab ans and
iab teh the
iab thre there
于 2008-10-03T12:44:37.817 回答
5

我的 242 行.vimrc并不是那么有趣,但由于没有人提到它,我觉得我必须分享两个最重要的映射,它们除了默认映射之外增强了我的工作流程:

map <C-j> :bprev<CR>
map <C-k> :bnext<CR>
set hidden " this will go along

说真的,切换缓冲区是经常要做的事情。Windows,当然,但一切都不太适合屏幕。

用于快速浏览错误(见 quickfix)和 grep 结果的类似地图集:

map <C-n> :cn<CR>
map <C-m> :cp<CR>

简单、轻松、高效。

于 2010-09-24T21:11:27.670 回答
5

我没有意识到我的 3200 条 .vimrc 行中有多少只是为了满足我的古怪需求,在这里列出来会很无聊。但也许这就是 Vim 如此有用的原因......

iab AlP ABCDEFGHIJKLMNOPQRSTUVWXYZ
iab MoN January February March April May June July August September October November December
iab MoO Jan Feb Mar Apr May Jun Jul Aug Sep Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
iab NuM 12345678901234567890123456789012345678901234567890123456789012345678901234567890 
iab RuL ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0

" Highlight every other line
map ,<Tab> :set hls<CR>/\\n.*\\n/<CR>

" This is for working across multiple xterms and/or gvims
" Transfer/read and write one block of text between vim sessions (capture whole line):
" Write
nmap ;w :. w! ~/.vimxfer<CR>
" Read
nmap ;r :r ~/.vimxfer<CR>
" Append 
nmap ;a :. w! >>~/.vimxfer<CR>
于 2008-10-20T20:03:55.380 回答
4

set nobackup 
set nocp
set tabstop=4
set shiftwidth=4
set et
set ignorecase

set ai
set ruler
set showcmd
set incsearch
set dir=$temp       " Make swap live in the %TEMP% directory
syn on

" Load the color scheme
colo inkpot
于 2008-10-02T22:24:02.570 回答
4

我在 vim 中使用 cscope(充分利用了多个缓冲区)。我使用 control-K 来启动大部分命令(我记得是从 ctags 偷来的)。另外,我已经生成了 .cscope.out 文件。

如果有(“cscope”)

set cscopeprg=/usr/local/bin/cscope
set cscopetagorder=0
set cscopetag
set cscopepathcomp=3
set nocscopeverbose
cs add .cscope.out
set csverb

"
" cscope find
"
" 0 or s: Find this C symbol
" 1 or d: Find this definition
" 2 or g: Find functions called by this function
" 3 or c: Find functions calling this function
" 4 or t: Find assignments to
" 6 or e: Find this egrep pattern
" 7 or f: Find this file
" 8 or i: Find files #including this file
" 
map ^Ks     :cs find 0 <C-R>=expand("<cword>")<CR><CR>
map ^Kd     :cs find 1 <C-R>=expand("<cword>")<CR><CR>
map ^Kg     :cs find 2 <C-R>=expand("<cword>")<CR><CR>
map ^Kc     :cs find 3 <C-R>=expand("<cword>")<CR><CR>
map ^Kt     :cs find 4 <C-R>=expand("<cword>")<CR><CR>
map ^Ke     :cs find 6 <C-R>=expand("<cword>")<CR><CR>
map ^Kf     :cs find 7 <C-R>=expand("<cfile>")<CR><CR>
map ^Ki     :cs find 8 <C-R>=expand("%")<CR><CR>

万一

于 2008-10-03T00:38:28.330 回答
4

我将 vimrc 文件保存在 github 上。你可以在这里找到它:

http://github.com/developernotes/vim-setup/tree/master

于 2008-10-03T00:56:24.187 回答
3
map = }{!}fmt^M}
map + }{!}fmt -p '> '^M}
set showmatch

= 用于重新格式化普通段落。+ 用于重新格式化引用电子邮件中的段落。showmatch 用于在我键入右括号或括号时闪烁匹配的括号/括号。

于 2008-10-02T22:56:10.917 回答
3

把它放在你的 vimrc 中:

imap <C-l> <Space>=><Space>

并且永远不要考虑再次输入 hashrocket。是的,我知道你不需要在 Ruby 1.9 中。但别介意。

我的完整 vimrc 在这里

于 2011-08-20T23:28:52.210 回答
3

我在 OS X 上,所以其中一些在其他平台上可能有更好的默认值,但无论如何:

syntax on
set tabstop=4
set expandtab
set shiftwidth=4
于 2008-10-02T22:22:18.330 回答
3

使用目录树中第一个可用的“标签”文件:

:set tags=tags;/

left 和 right 用于切换缓冲区,不移动光标:

map <right> <ESC>:bn<RETURN>
map <left> <ESC>:bp<RETURN>

使用单个按键禁用搜索突出显示:

map - :nohls<cr>
于 2008-10-03T00:43:52.373 回答
3
set tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent cindent 
set encoding=utf-8 fileencoding=utf-8
set nobackup nowritebackup noswapfile autoread
set number
set hlsearch incsearch ignorecase smartcase

if has("gui_running")
    set lines=35 columns=140
    colorscheme ir_black
else
    colorscheme darkblue
endif

" bash like auto-completion
set wildmenu
set wildmode=list:longest

inoremap <C-j> <Esc>

" for lusty explorer
noremap glr \lr
noremap glf \lf
noremap glb \lb

" use ctrl-h/j/k/l to switch between splits
map <c-j> <c-w>j
map <c-k> <c-w>k
map <c-l> <c-w>l
map <c-h> <c-w>h

" Nerd tree stuff
let NERDTreeIgnore = ['\.pyc$', '\.pyo$']
noremap gn :NERDTree<Cr>

" cd to the current file's directory
noremap gc :lcd %:h<Cr>
于 2009-10-28T12:37:19.670 回答
2

我试图让我的 .vimrc尽可能普遍有用。

一个方便的技巧是 .gpg 文件的处理程序可以安全地编辑它们:

au BufNewFile,BufReadPre *.gpg :set secure vimi= noswap noback nowriteback hist=0 binary
au BufReadPost *.gpg :%!gpg -d 2>/dev/null
au BufWritePre *.gpg :%!gpg -e -r 'name@email.com' 2>/dev/null
au BufWritePost *.gpg u
于 2008-10-02T23:16:44.237 回答
2

在我的 .vimrc中实际上并没有多少内容(即使它有 850 行)。主要是设置和一些我懒得提取到插件中的常见和简单的映射。

如果您的意思是“自动类”中的“模板文件”,我使用的是模板扩展插件——在同一个站点上,您会找到我为 C&C++ 编辑定义的 ftplugins,有些可能适用于C# 我猜。

关于重构方面,http: //vim.wikia.com上有专门针对此主题的提示;IIRC 示例代码适用于 C#。它启发了我一个仍然需要大量工作的重构插件(实际上需要重构)。

你应该看看 vim mailing-list 的档案,特别是关于使用 vim 作为有效 IDE 的主题。不要忘记查看 :make, tags, ...

高温下,

于 2008-10-02T22:41:10.267 回答
2

1) 我喜欢状态行(带有文件名、ascii 值(十进制)、十六进制值和标准行、cols 和 %):

set statusline=%t%h%m%r%=[%b\ 0x%02B]\ \ \ %l,%c%V\ %P
" Always show a status line
set laststatus=2
"make the command line 1 line high
set cmdheight=1

2)我也喜欢拆分窗口的映射。

" <space> switches to the next window (give it a second)
" <space>n switches to the next window
" <space><space> switches to the next window and maximizes it
" <space>= Equalizes the size of all windows
" + Increases the size of the current window
" - Decreases the size of the current window

 :map <space> <c-W>w
:map <space>n <c-W>w
:map <space><space> <c-W>w<c-W>_
:map <space>= <c-W>=
if bufwinnr(1)
  map + <c-W>+
  map - <c-W>-
endif
于 2008-10-03T12:25:55.263 回答
2

好吧,你必须自己清理我的配置。玩得开心。大多数情况下,这只是我想要的设置,包括映射和随机语法相关的东西,以及折叠设置和一些插件配置、tex 编译解析器等。

顺便说一句,我发现非常有用的是“突出显示光标下的单词”:

 highlight flicker cterm=bold ctermfg=white
 au CursorMoved <buffer> exe 'match flicker /\V\<'.escape(expand('<cword>'), '/').'\>/'

请注意,只有ctermandtermfg被使用,因为我不使用gvim. 如果您希望它起作用,gvim只需分别用gui和替换它们guifg

于 2008-10-02T22:43:48.543 回答
2

我的 .vimrc 包括(以及其他更有用的东西)以下行:

set statusline=%2*%n\|%<%*%-.40F%2*\|\ %2*%M\ %3*%=%1*\ %1*%2.6l%2*x%1*%1.9(%c%V%)%2*[%1*%P%2*]%1*%2B

我在为高中期末学习而感到无聊。

于 2009-08-02T15:49:35.287 回答
1

My .vimrc is available on Github. Lots of small tweaks and handy bindings in there :)

于 2011-08-20T23:10:34.253 回答
1

我的 .vimrc 和 .bashrc 以及我的整个 .vim 文件夹(包含所有插件)可在以下网址找到: http ://code.google.com/p/pal-nix/ 。

这是我的 .vimrc 供快速查看:


" .vimrc 
"
" $Author$
" $Date$
" $Revision$ 

" * Initial Configuration * {{{1 " " change directory on open file, buffer switch etc. {{{2 set autochdir

" turn on filetype detection and indentation {{{2 filetype indent plugin on

" set tags file to search in parent directories with tags; {{{2 set tags=tags;

" reload vimrc on update {{{2 autocmd BufWritePost .vimrc source %

" set folds to look for markers {{{2 :set foldmethod=marker

" automatically save view and reload folds {{{2 "au BufWinLeave * mkview "au BufWinEnter * silent loadview

" behave like windows {{{2 "source $VIMRUNTIME/mswin.vim " can't use if on (use with gvim only) "behave mswin

" load dictionary files for complete suggestion with Ctrl-n {{{2 set complete+=k autocmd FileType * exec('set dictionary+=~/.vim/dict/' . &filetype)

" * User Interface * {{{1 " " turn on coloring {{{2 if has('syntax') syntax on endif

" gvim color scheme of choice {{{2 if has('gui') so $VIMRUNTIME/colors/desert.vim endif

" turn off annoying bell {{{2 set vb

" set the directory for swp files {{{2 if(isdirectory(expand("$VIMRUNTIME/swp"))) set dir=$VIMRUNTIME/swp endif

" have fifty lines of cmdline (etc) history {{{2 set history=50

" have cmdline completion (for filenames, help topics, option names) {{{2 " first list the available options and complete the longest common part, then " have further s cycle through the possibilities: set wildmode=list:longest,full

" use "[RO]" for "[readonly]" to save space in the message line: {{{2 set shortmess+=r

" display current mode and partially typed commands in status line {{{2 set showmode set showcmd

" Text Formatting -- General {{{2 set nocompatible "prevents vim from emulating vi's original bugs set backspace=2 "make backspace work normal (indent, eol, start) set autoindent set smartindent "makes vim smartly guess indent level set tabstop=2 "sets up 2 space tabs set shiftwidth=2 "tells vim to use 2 spaces when text is indented set smarttab "uses shiftwidth for inserting s set expandtab "insert spaces instead of set softtabstop=2 "makes vim see multiple space characters as tabstops set showmatch "causes cursor to jump to bracket match set mat=5 "how many tenths of a second to blink matches set guioptions-=T "removes toolbar from gvim set ruler "ensures each window contains a status line set incsearch "vim will search for text as you type set hlsearch "highlight search terms set hl=l:Visual "use Visual mode's highlighting scheme --much better set ignorecase "ignore case in searches --faster this way set virtualedit=all "allows the cursor to stray beyond defined text set number "show line numbers in left margin set path=$PWD/** "recursively set the path of the project "get more information from the status line set statusline=[%n]\ %<%.99f\ %h%w%m%r%{exists('*CapsLockStatusline')?CapsLockStatusline():''}%y%=%-16(\ %l,%c-%v\ %)%P set laststatus=2 "keep status line showing set cursorline "highlight current line highlight CursorLine guibg=lightblue guifg=white ctermbg=blue ctermfg=white "set spell "spell check set spellsuggest=3 "suggest better spelling set spelllang=en "set language set encoding=utf-8 "set character encoding

" * Macros * {{{1 " " Function keys {{{2 " Don't you always find yourself hitting instead of ? {{{3 inoremap noremap

" turn off syntax highlighting {{{3 nnoremap :nohlsearch inoremap :nohlsearcha

" NERD Tree Explorer {{{3 nnoremap :NERDTreeToggle

" open tag list {{{3 nnoremap :TlistToggle

" Spell check {{{3 nnoremap :set spell

" No spell check {{{3 nnoremap :set nospell

" refactor curly braces on keyword line {{{3 map :%s/) \?\n^\s*{/) {/g

" useful mappings to paste and reformat/reindent {{{2 nnoremap P P'[v']= nnoremap p P'[v']=

" * Scripts * {{{1 " :au Filetype html,xml,xsl source ~/.vim/scripts/closetag.vim

" Modeline {{{1 " vim:set fdm=marker sw=4 ts=4:

于 2009-11-01T02:01:46.313 回答
1

行号和语法高亮。

set number
syntax on
于 2009-03-31T19:22:01.577 回答
1

What's in my .vimrc?

ngn@macavity:~$ cat .vimrc
" This file intentionally left blank

The real config files lie under ~/.vim/ :)

And most of the stuff there is parasiting on other people's efforts, blatantly adapted from vim.org to my editing advantage.

于 2008-11-02T20:57:59.327 回答
1

这是我的.vimrc。我使用 Gvim 7.2

set guioptions=em
set showtabline=2
set softtabstop=2
set shiftwidth=2
set tabstop=2

" Use spaces instead of tabs
set expandtab
set autoindent

" Colors and fonts
colorscheme inkpot
set guifont=Consolas:h11:cANSI

"TAB navigation like firefox
:nmap <C-S-tab> :tabprevious<cr>
:nmap <C-tab> :tabnext<cr>
:imap <C-S-tab> <ESC>:tabprevious<cr>i
:imap <C-tab> <ESC>:tabnext<cr>i
:nmap <C-t> :tabnew<cr>
:imap <C-t> <ESC>:tabnew<cr>i
:map <C-w> :tabclose<cr>

" No Backups and line numbers
set nobackup
set number
set nuw=6

" swp files are saved to %Temp% folder
set dir=$temp
" sets the default size of gvim on open
set lines=40 columns=90
于 2008-10-20T19:41:33.833 回答
1

我不能没有这条线,通常首先出现在我的.vimrc

" prevent switch to Replece mode if <Insert> pressed in insert mode
imap <Insert> <Nop>

我不能没有的另一点是在点击 PgDown/PgUp 时保留当前行:

map <silent> <PageUp> 1000<C-U>
map <silent> <PageDown> 1000<C-D>
imap <silent> <PageUp> <C-O>1000<C-U>
imap <silent> <PageDown> <C-O>1000<C-D>
set nostartofline

禁用烦人的匹配括号突出显示:

set noshowmatch
let loaded_matchparen = 1

编辑大 (>4MB) 文件时禁用语法突出显示:

au BufReadPost *        if getfsize(bufname("%")) > 4*1024*1024 |
\                               set syntax= |
\                       endif

最后是我的简单在线计算器

function CalcX(line_num)
        let l = getline(a:line_num)
        let expr = substitute( l, " *=.*$","","" )
        exec ":let g:tmp_calcx = ".expr
        call setline(a:line_num, expr." = ".g:tmp_calcx)
endfunction
:map <silent> <F11> :call CalcX(".")<CR>
于 2010-10-06T11:03:06.590 回答
1

这是我不起眼的.vimrc。这是一项正在进行的工作(应该一直如此),所以请原谅凌乱的布局和注释掉的行。

" =====Key mapping
" Insert empty line.
nmap <A-o> o<ESC>k
nmap <A-O> O<ESC>j
" Insert one character.
nmap <A-i> i <Esc>r
nmap <A-a> a <Esc>r
" Move on display lines in normal and visual mode.
nnoremap j gj
nnoremap k gk
vnoremap j gj
vnoremap k gk
" Do not lose * register when pasting on visual selection.
vmap p "zxP
" Clear highlight search results with <esc>
nnoremap <esc> :noh<return><esc>
" Center screen on next/previous selection.
map n nzz
map N Nzz
" <Esc> with jj.
inoremap jj <Esc>
" Switch jump to mark.
nnoremap ' `
nnoremap ` '
" Last and next jump should center too.
nnoremap <C-o> <C-o>zz
nnoremap <C-i> <C-i>zz
" Paste on new line.
nnoremap <A-p> :pu<CR>
nnoremap <A-S-p> :pu!<CR>
" Quick paste on insert mode.
inoremap <C-F> <C-R>"
" Indent cursor on empty line.
nnoremap <A-c> ddO
nnoremap <leader>c ddO
" Save and quit quickly.
nnoremap <leader>s :w<CR>
nnoremap <leader>q :q<CR>
nnoremap <leader>Q :q!<CR>
" The way it should have been.
noremap Y y$
" Moving in buffers.
nnoremap <C-S-tab> :bprev<CR>
nnoremap <C-tab> :bnext<CR>
" Using bufkill plugin.
nnoremap <leader>b :BD<CR>
nnoremap <leader>B :BD!<CR>
nnoremap <leader>ZZ :w<CR>:BD<CR>
" Moving and resizing in windows.
nnoremap + <C-W>+
nnoremap _ <C-W>-
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
nnoremap <leader>w <C-w>c
" Moving in tabs
noremap <c-right> gt
noremap <c-left> gT
nnoremap <leader>t :tabc<CR>
" Moving around in insert mode.
inoremap <A-j> <C-O>gj
inoremap <A-k> <C-O>gk
inoremap <A-h> <Left>
inoremap <A-l> <Right>

" =====General options
" I copy a lot from external apps.
set clipboard=unnamed
" Don't let swap and backup files fill my working directory.
set backupdir=c:\\temp,.    " Backup files
set directory=c:\\temp,.    " Swap files
set nocompatible
set showmatch
set hidden
set showcmd                     " This shows what you are typing as a command.
set scrolloff=3
" Allow backspacing over everything in insert mode
set backspace=indent,eol,start
" Syntax highlight
syntax on                           
filetype plugin on
filetype indent on

" =====Searching
set ignorecase
set hlsearch
set incsearch

" =====Indentation settings
" autoindent just copies the indentation from the line above.
"set autoindent
" smartindent automatically inserts one extra level of indentation in some cases.
set smartindent
" cindent is more customizable, but also more strict.
"set cindent
set tabstop=4
set shiftwidth=4

" =====GUI options.
" Just Vim without any gui.
set guioptions-=m
set guioptions-=T
set lines=40
set columns=150
" Consolas is better, but Courier new is everywhere.
"set guifont=Courier\ New:h9
set guifont=Consolas:h9
" Cool status line.
set statusline=%<%1*===\ %5*%f%1*%(\ ===\ %4*%h%1*%)%(\ ===\ %4*%m%1*%)%(\ ===\ %4*%r%1*%)\ ===%====\ %2*%b(0x%B)%1*\ ===\ %3*%l,%c%V%1*\ ===\ %5*%P%1*\ ===%0* laststatus=2
colorscheme mildblack
let g:sienna_style = 'dark'

" =====Plugins

" ===BufPos
nnoremap <leader>ob :call BufWipeout()<CR>
" ===SuperTab
" Map SuperTab to space key.
let g:SuperTabMappingForward = '<c-space>'
let g:SuperTabMappingBackward = '<s-c-space>'
let g:SuperTabDefaultCompletionType = 'context'
" ===miniBufExpl
" let g:miniBufExplMapWindowNavVim = 1
" let g:miniBufExplMapCTabSwitchBufs = 1
" let g:miniBufExplorerMoreThanOne = 0
" ===AutoClose
" let g:AutoClosePairs = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'"}
" ===NERDTree
nnoremap <leader>n :NERDTreeToggle<CR>
" ===delimitMate
let delimitMate = "(:),[:],{:}"
于 2009-10-28T18:52:23.930 回答
1

当我不带参数启动 gVim 时,我希望它在我的“项目”目录中打开,这样我就可以做:find等。但是,当我用文件启动它时,我不希望它切换目录,我希望它保留就在那里(部分是为了打开我想要打开的文件!)。

if argc() == 0
   cd $PROJECT_DIR
endif

为了可以:find从当前项目中的任何文件中使用,我设置了查找目录树的路径,直到它找到srcscripts下降到那些目录树,至少直到它找到c:\work我所有项目的根目录。这允许我在一个非当前项目中打开文件(即PROJECT_DIR上面指定了一个不同的目录)。

set path+=src/**;c:/work,scripts/**;c:/work

这样我就可以在 gVim 失去焦点时自动保存和重新加载,并退出插入模式,以及在编辑只读文件时从 Perforce 自动签出......

augroup AutoSaveGroup
    autocmd!
    autocmd FocusLost       *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel    wa
    autocmd FileChangedRO   *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel    silent !p4 edit %:p
    autocmd FileChangedRO   *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel    w!
augroup END

augroup OutOfInsert
    autocmd!
    autocmd FocusLost * call feedkeys("\<C-\>\<C-N>")
augroup END

最后,切换到当前缓冲区中文件的目录,以便于该目录中的:e其他文件。

augroup MiscellaneousTomStuff
    autocmd!
    " make up for the deficiencies in 'autochdir'
    autocmd BufEnter * silent! lcd %:p:h:gs/ /\\ /
augroup END
于 2010-09-10T21:55:50.897 回答
1
    " insert change log in files
    fun! InsertChangeLog()
    let l:flag=0
    for i in range(1,5)
        if getline(i) !~ '.*Last Change.*'
            let l:flag = l:flag + 1
        endif
    endfor
    if l:flag >= 5
        normal(1G)
        call append(0, "File: <+Description+>")
        call append(1, "Created: " . strftime("%a %d/%b/%Y hs %H:%M"))
        call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M"))
        call append(3, "author: <+your name+>")
        call append(4, "site: <+site+>")
        call append(5, "twitter: <+your twitter here+>")
        normal gg
    endif
endfun
map <special> <F4> <esc>:call InsertChangeLog()<cr>

" update changefile log
" http://tech.groups.yahoo.com/group/vim/message/51005
fun! LastChange()
    let _s=@/
    let l = line(".")
    let c = col(".")
    if line("$") >= 5
        1,5s/\s*Last Change:\s*\zs.*/\="" . strftime("%Y %b %d %X")/ge
    endif
    let @/=_s
    call cursor(l, c)
endfun
autocmd BufWritePre * keepjumps call LastChange()

    function! JumpToNextPlaceholder()
    let old_query = getreg('/')
    echo search("<+.\\++>")
    exec "norm! c/+>/e\<CR>"
    call setreg('/', old_query)
endfunction
autocmd BufNewFile * :call LoadFileTemplate()
nnoremap <special> <leader>j :call JumpToNextPlaceholder()<CR>a
inoremap <special> <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a

" Cientific calculator
command! -nargs=+ Calc :py print <args>
py from math import *
map ,c :Calc


set statusline=%F%m%r%h%w\
\ ft:%{&ft}\ \
\ff:%{&ff}\ \
\%{strftime(\"%a\ %d/%m/%Y\ \
\%H:%M:%S\",getftime(expand(\"%:p\")))}%=\ \
\buf:%n\ \
\L:%04l\ C:%04v\ \
\T:%04L\ HEX:%03.3B\ ASCII:%03.3b\ %P
set laststatus=2 " Always show statusline
于 2010-11-16T23:22:49.067 回答
1

return、backspace、spacebar 和 hyphen 键没有绑定到任何有用的东西,所以我映射它们以便更方便地浏览文档:

" Page down, page up, scroll down, scroll up
noremap <Space> <C-f>
noremap - <C-b>
noremap <Backspace> <C-y>
noremap <Return> <C-e>
于 2009-11-29T23:54:52.713 回答
1

几乎一切都在这里。它主要面向编程,尤其是 C++。

于 2009-10-29T07:35:19.523 回答
1

这不在我的 .vimrc 中,但与其相关。

在你的 .bashrc 添加这一行 alias :q=exit

令人惊讶的是我已经使用了多少,有时甚至没有意识到!

于 2011-03-20T11:10:29.570 回答
1

我用的比较多的两个函数是占位符跳转文件和InsertChangeLog(),共同“方便创建文件,描述更友好

" place holders snippets
" File Templates
" --------------
"  <leader>j jumps to the next marker
" iabbr <buffer> for for <+i+> in <+intervalo+>:<cr><tab><+i+>
function! LoadFileTemplate()
    "silent! 0r ~/.vim/templates/%:e.tmpl
    syn match vimTemplateMarker "<+.\++>" containedin=ALL
    hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold
endfunction
function! JumpToNextPlaceholder()
    let old_query = getreg('/')
    echo search("<+.\\++>")
    exec "norm! c/+>/e\<CR>"
    call setreg('/', old_query)
endfunction
autocmd BufNewFile * :call LoadFileTemplate()
nnoremap <leader>j :call JumpToNextPlaceholder()<CR>a
inoremap <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a


fun! InsertChangeLog()
    normal(1G)
    call append(0, "Arquivo: <+Description+>")
    call append(1, "Criado: " . strftime("%a %d/%b/%Y hs %H:%M"))
    call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M"))
    call append(3, "autor: <+digite seu nome+>")
    call append(4, "site: <+digite o endereço de seu site+>")
    call append(5, "twitter: <+your twitter here+>")
    normal gg
endfun
于 2010-10-20T12:49:51.587 回答
0

我的(非常定制的)vimrc 可能太长,无法在此处发布,所以我将仅链接到它:

https://github.com/majutsushi/etc/blob/master/vim/.vimrc

里面有一些有用的花絮,我要么自己写,要么在状态栏之类的地方捡到,里面有我觉得有用的各种信息。我写的这个插件的网站上有一个截图:

http://majutsushi.github.com/tagbar/

于 2011-03-14T01:14:25.433 回答
0

我的 .vimrc。我的单词交换功能通常很受欢迎。

于 2008-10-09T04:48:12.377 回答
0
set guifont=FreeMono\ 12

colorscheme default

set nocompatible
set backspace=indent,eol,start
set nobackup "do not keep a backup file, use versions instead
set history=10000 "keep 10000 lines of command line history
set ruler "show the cursor position all the time
set showcmd "display incomplete commands
set showmode
set showmatch
set nojoinspaces "do not insert a space, when joining lines
set whichwrap="" "do not jump to the next line when deleting
"set nowrap
filetype plugin indent on
syntax enable
set hlsearch
set incsearch "do incremental searching
set autoindent
set noexpandtab
set tabstop=4
set shiftwidth=4
set number
set laststatus=2
set visualbell "do not beep
set tabpagemax=100
set statusline=%F\ %h%m%r%=%l/%L\ \(%-03p%%\)\ %-03c\ 

"use listmode to make tabs visible and make them gray so they are not
"disctrating too much
set listchars=tab:»\ ,eol:¬,trail:.
highlight NonText ctermfg=gray guifg=gray
highlight SpecialKey ctermfg=gray guifg=gray
highlight clear MatchParen
highlight MatchParen cterm=bold
set list


match Todo /@todo/ "highlight doxygen todos


"different tabbing settings for different file types
if has("autocmd")
    autocmd FileType c setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab
    autocmd FileType cpp setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab
    autocmd FileType go setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab
    autocmd FileType make setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab
    autocmd FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab

    " doesnt work properly -- revise me
    autocmd CursorMoved * call RonnyHighlightWordUnderCursor()
    autocmd CursorMovedI * call RonnyHighlightWordUnderCursor()

    "jump to the end of the file if it is a logfile
    autocmd BufReadPost *.log normal G

    autocmd BufRead,BufNewFile *.go set filetype=go
endif


highlight Search ctermfg=white ctermbg=gray
highlight IncSearch ctermfg=white ctermbg=gray
highlight RonnyWordUnderCursorHighlight cterm=bold


function! RonnyHighlightWordUnderCursor()
python << endpython
import vim

# get the character under the cursor
row, col = vim.current.window.cursor
characterUnderCursor = ''
try:
    characterUnderCursor = vim.current.buffer[row-1][col]
except:
    pass

# remove last search
vim.command("match RonnyWordUnderCursorHighlight //")

# if the cursor is currently located on a real word, move on and highlight it
if characterUnderCursor.isalpha() or characterUnderCursor.isdigit() or characterUnderCursor is '_':

    # expand cword to get the word under the cursor
    wordUnderCursor = vim.eval("expand(\'<cword>\')")
    if wordUnderCursor is None :
        wordUnderCursor = ""

    # escape the word
    wordUnderCursor = vim.eval("RonnyEscapeString(\"" + wordUnderCursor + "\")")
    wordUnderCursor = "\<" + wordUnderCursor + "\>"

    currentSearch = vim.eval("@/")

    if currentSearch != wordUnderCursor :
        # highlight it, if it is not the currently searched word
        vim.command("match RonnyWordUnderCursorHighlight /" + wordUnderCursor + "/")

endpython
endfunction


function! RonnyEscapeString(s)
python << endpython
import vim

s = vim.eval("a:s")

escapeMap = {
    '"'     : '\\"',
    "'"     : '\\''',
    "*"     : '\\*',
    "/"     : '\\/',
    #'' : ''
}

s = s.replace('\\', '\\\\')

for before, after in escapeMap.items() :
    s = s.replace(before, after)

vim.command("return \'" + s + "\'")
endpython
endfunction
于 2008-12-15T18:38:49.523 回答
0

我在鼠标悬停时显示折叠内容和语法组:

function! SyntaxBallon()
    let synID   = synID(v:beval_lnum, v:beval_col, 0)
    let groupID = synIDtrans(synID)
    let name    = synIDattr(synID, "name")
    let group   = synIDattr(groupID, "name")
    return name . "\n" . group
endfunction

function! FoldBalloon()
    let foldStart = foldclosed(v:beval_lnum)
    let foldEnd   = foldclosedend(v:beval_lnum)
    let lines = []
    if foldStart >= 0
        " we are in a fold
        let numLines = foldEnd - foldStart + 1
        if (numLines > 17)
            " show only the first 8 and the last 8 lines
            let lines += getline(foldStart, foldStart + 8)
            let lines += [ '-- Snipped ' . (numLines - 16) . ' lines --']
            let lines += getline(foldEnd - 8, foldEnd)
        else
            " show all lines
            let lines += getline(foldStart, foldEnd)
        endif
    endif
    " return result
    return join(lines, has("balloon_multiline") ? "\n" : " ")
endfunction

function! Balloon()
    if foldclosed(v:beval_lnum) >= 0
        return FoldBalloon()
    else
        return SyntaxBallon()
endfunction

set balloonexpr=Balloon()
set ballooneval
于 2009-04-25T16:29:04.000 回答
0
set nocompatible
syntax on
set number
set autoindent
set smartindent
set background=dark
set tabstop=4 shiftwidth=4
set tw=80
set expandtab
set mousehide
set cindent
set list listchars=tab:»·,trail:·
set autoread
filetype on
filetype indent on
filetype plugin on

" abbreviations for c programming
func LoadCAbbrevs()
 "  iabbr do do {<CR>} while ();<C-O>3h<C-O>
 "  iabbr for for (;;) {<CR>}<C-O>k<C-O>3l<C-O>
 "  iabbr switch switch () {<CR>}<C-O>k<C-O>6l<C-O>
 "  iabbr while while () {<CR>}<C-O>k<C-O>5l<C-O>
 "  iabbr if if () {<CR>}<C-O>k<C-O>2l<C-O>
    iabbr #d #define
    iabbr #i #include
endfunc
au FileType c,cpp call LoadCAbbrevs()

au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") |
                         \ exe "normal g'\"" | endif

autocmd FileType python set nocindent shiftwidth=4 ts=4 foldmethod=indent

那里不多。

于 2009-04-25T16:38:54.817 回答
0

我的 .vimrc 中最重要的部分是它如何在每个有选项卡的地方显示一个“»”字符,以及它如何以红色突出显示“坏”空白。坏空格是行中间的制表符或末尾的不可见空格之类的东西。

syntax enable

" Incremental search without highlighting.
set incsearch
set nohlsearch

" Show ruler.
set ruler

" Try to keep 2 lines above/below the current line in view for context.
set scrolloff=2

" Other file types.
autocmd BufReadPre,BufNew *.xml set filetype=xml

" Flag problematic whitespace (trailing spaces, spaces before tabs).
highlight BadWhitespace term=standout ctermbg=red guibg=red
match BadWhitespace /[^* \t]\zs\s\+$\| \+\ze\t/

" If using ':set list' show things nicer.
execute 'set listchars=tab:' . nr2char(187) . '\ '
set list
highlight Tab ctermfg=lightgray guifg=lightgray
2match Tab /\t/

" Indent settings for code: 4 spaces, do not use tab character.
"set tabstop=4 shiftwidth=4 autoindent smartindent shiftround
"autocmd FileType c,cpp,java,xml,python,cs setlocal expandtab softtabstop=4
"autocmd FileType c,cpp,java,xml,python,cs 2match BadWhitespace /[^\t]\zs\t/
set tabstop=8 shiftwidth=4 autoindent smartindent shiftround
set expandtab softtabstop=4
2match BadWhitespace /[^\t]\zs\t\+/

" Automatically show matching brackets.
set showmatch

" Auto-complete file names after <TAB> like bash does.
set wildmode=longest,list
set wildignore=.svn,CVS,*.swp

" Show current mode and currently-typed command.
set showmode
set showcmd

" Use mouse if possible.
" set mouse=a

" Use Ctrl-N and Ctrl-P to move between files.
nnoremap <C-N> :confirm next<Enter>
nnoremap <C-P> :confirm prev<Enter>

" Confirm saving and quitting.
set confirm

" So yank behaves like delete, i.e. Y = D.
map Y y$

" Toggle paste mode with F5.
set pastetoggle=<F5>

" Don't exit visual mode when shifting.
vnoremap < <gv
vnoremap > >gv

" Move up and down by visual lines not buffer lines.
nnoremap <Up>   gk
vnoremap <Up>   gk
nnoremap <Down> gj
vnoremap <Down> gj
于 2009-11-01T02:02:40.710 回答
0

I have this in my ~/.vim/after/syntax/vim.vim file:

What it does is:

  • highlights the word blue in the color blue
  • highlights the wrod red in the color red
  • etc

Ie: so if you go:

highlight JakeRedKeywords cterm=bold term=bold ctermbg=black ctermfg=Red

The word red will be red and the word black will be black.

Here is the code:

syn cluster vimHiCtermColors contains=vimHiCtermColorBlack,vimHiCtermColorBlue,vimHiCtermColorBrown,vimHiCtermColorCyan,vimHiCtermColorDarkBlue,vimHiCtermColorDarkcyan,vimHiCtermColorDarkgray,vimHiCtermColorDarkgreen,vimHiCtermColorDarkgrey,vimHiCtermColorDarkmagenta,vimHiCtermColorDarkred,vimHiCtermColorDarkyellow,vimHiCtermColorGray,vimHiCtermColorGreen,vimHiCtermColorGrey,vimHiCtermColorLightblue,vimHiCtermColorLightcyan,vimHiCtermColorLightgray,vimHiCtermColorLightgreen,vimHiCtermColorLightgrey,vimHiCtermColorLightmagenta,vimHiCtermColorLightred,vimHiCtermColorMagenta,vimHiCtermColorRed,vimHiCtermColorWhite,vimHiCtermColorYellow

syn case ignore

syn keyword vimHiCtermColorYellow yellow contained 
syn keyword vimHiCtermColorBlack black contained
syn keyword vimHiCtermColorBlue blue contained
syn keyword vimHiCtermColorBrown brown contained
syn keyword vimHiCtermColorCyan cyan contained
syn keyword vimHiCtermColorDarkBlue darkBlue contained
syn keyword vimHiCtermColorDarkcyan darkcyan contained
syn keyword vimHiCtermColorDarkgray darkgray contained
syn keyword vimHiCtermColorDarkgreen darkgreen contained
syn keyword vimHiCtermColorDarkgrey darkgrey contained
syn keyword vimHiCtermColorDarkmagenta darkmagenta contained
syn keyword vimHiCtermColorDarkred darkred contained
syn keyword vimHiCtermColorDarkyellow darkyellow contained
syn keyword vimHiCtermColorGray gray contained
syn keyword vimHiCtermColorGreen green contained
syn keyword vimHiCtermColorGrey grey contained
syn keyword vimHiCtermColorLightblue lightblue contained
syn keyword vimHiCtermColorLightcyan lightcyan contained
syn keyword vimHiCtermColorLightgray lightgray contained
syn keyword vimHiCtermColorLightgreen lightgreen contained
syn keyword vimHiCtermColorLightgrey lightgrey contained
syn keyword vimHiCtermColorLightmagenta lightmagenta contained
syn keyword vimHiCtermColorLightred lightred contained
syn keyword vimHiCtermColorMagenta magenta contained
syn keyword vimHiCtermColorRed red contained
syn keyword vimHiCtermColorWhite white contained
syn keyword vimHiCtermColorYellow yellow contained

syn match  vimHiCtermFgBg   contained   "\ccterm[fb]g="he=e-1  nextgroup=vimNumber,@vimHiCtermColors,vimFgBgAttrib,vimHiCtermError

highlight vimHiCtermColorBlack ctermfg=black ctermbg=white
highlight vimHiCtermColorBlue ctermfg=blue
highlight vimHiCtermColorBrown ctermfg=brown
highlight vimHiCtermColorCyan ctermfg=cyan
highlight vimHiCtermColorDarkBlue ctermfg=darkBlue
highlight vimHiCtermColorDarkcyan ctermfg=darkcyan
highlight vimHiCtermColorDarkgray ctermfg=darkgray
highlight vimHiCtermColorDarkgreen ctermfg=darkgreen
highlight vimHiCtermColorDarkgrey ctermfg=darkgrey
highlight vimHiCtermColorDarkmagenta ctermfg=darkmagenta
highlight vimHiCtermColorDarkred ctermfg=darkred
highlight vimHiCtermColorDarkyellow ctermfg=darkyellow
highlight vimHiCtermColorGray ctermfg=gray
highlight vimHiCtermColorGreen ctermfg=green
highlight vimHiCtermColorGrey ctermfg=grey
highlight vimHiCtermColorLightblue ctermfg=lightblue
highlight vimHiCtermColorLightcyan ctermfg=lightcyan
highlight vimHiCtermColorLightgray ctermfg=lightgray
highlight vimHiCtermColorLightgreen ctermfg=lightgreen
highlight vimHiCtermColorLightgrey ctermfg=lightgrey
highlight vimHiCtermColorLightmagenta ctermfg=lightmagenta
highlight vimHiCtermColorLightred ctermfg=lightred
highlight vimHiCtermColorMagenta ctermfg=magenta
highlight vimHiCtermColorRed ctermfg=red
highlight vimHiCtermColorWhite ctermfg=white
highlight vimHiCtermColorYellow ctermfg=yellow
于 2010-05-15T17:34:48.383 回答
0

这是我的。它们已经发展了很多年,并且在 Linux/Windows/OSX 中同样运行良好(我上次检查时):

vimrcgvimrc

于 2008-10-14T16:45:44.380 回答
0

以下是我的 vimrc 的一些部分和来自 vimrc 的文件:

用于F10切换常见的布尔设置:

" F10 inverts 'wrap'
xnoremap <F10>          :<C-U>set wrap! <Bar> set wrap? <CR>gv
nnoremap <F10>          :set wrap! <Bar> set wrap? <CR>
inoremap <F10>          <C-O>:set wrap! <Bar> set wrap? <CR>
" Shift-F10 inverts 'virtualedit'
xnoremap <S-F10>        :<C-U>set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>gv
nnoremap <S-F10>        :set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>
inoremap <S-F10>        <C-O>:set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>
" Ctrl-F10 inverts 'hidden'
xnoremap <C-F10>        :<C-U>set hidden! <Bar> set hidden? <CR>gv
nnoremap <C-F10>        :set hidden! <Bar> set hidden? <CR>
inoremap <C-F10>        <C-O>:set hidden! <Bar> set hidden? <CR>

使用F11F12移动快速修复条目

" F11 and F12 to go to resp. previous and next item in quickfix entries
nnoremap <F11>          :silent! cc<CR>:silent! cp <CR>:call ErrBlink()<CR>
nnoremap <F12>          :silent! cc<CR>:silent! cn <CR>:call ErrBlink()<CR>
" Shift-F11 and Shift-F12 to go to resp prev. and next file in quickfix list
nnoremap <S-F11>        :silent! cc<CR>:silent! cpf<CR>:call ErrBlink()<CR>
nnoremap <S-F12>        :silent! cc<CR>:silent! cnf<CR>:call ErrBlink()<CR>
" Ctrl-F11 and Ctrl-F1 to recall older and newer quickfix lists
nnoremap <C-F11>        :silent! col <CR>:call ErrBlink()<CR>
nnoremap <C-F12>        :silent! cnew<CR>:call ErrBlink()<CR>

*使用and搜索视觉选择的文本#(前缀 with_也可以保留旧搜索)

xnoremap <silent> _* :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy/<C-R><C-R>/\|<C-R><C-R>=substitute(
  \substitute(escape(@", '/\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>

xnoremap <silent> _# :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy?<C-R><C-R>/\|<C-R><C-R>=substitute(
  \substitute(escape(@", '?\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>

xnoremap <silent> * :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy/<C-R><C-R>=substitute(
  \substitute(escape(@", '/\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>

xnoremap <silent> # :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy?<C-R><C-R>=substitute(
  \substitute(escape(@", '?\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>

使用F1F3搜索(将结果添加到当前结果)

set grepprg=ack
" F2 uses ack to search a Perl pattern
nnoremap <F2>         :grep<space>
nnoremap <S-F2>       :grepadd<space>
" F3 uses vim to search current pattern
nnoremap <F3>         :noautocmd vim // **/*<C-F>Bhhi
nnoremap <F3><F3>     :noautocmd vim /<C-R><C-O>// **/*<Return>
" F3 to search the current highlighted pattern
xnoremap <F3>         "zy:noautocmd vim /\M<C-R>=escape(@z,'\/')<CR>/ **/*<CR>
nnoremap <S-F3>       :noautocmd vimgrepadd // **/*<C-F>Bhhi
nnoremap <S-F3><S-F3> :noautocmd vimgrepadd /<C-R><C-O>// **/*<Return>
xnoremap <S-F3>       "zy:noautocmd vimgrepadd /\M<C-R>=escape(@z,'\/')<CR>/ **/*<CR>

在可视模式下粘贴时不要存储替换的文本

xnoremap p              pgvy

帮助功能

" Have cursor line and column blink a bit
function! BlinkHere()
    for i in range(1,6)
        set cursorline! cursorcolumn!
        redraw
        sleep 30m
    endfor
endfunction

" Blink on mappings to quickfix commands
function! ErrBlink()
    silent! cw
    silent! normal! z17
    silent! cc
    silent! normal! zz
    silent! call BlinkHere()
endfunction

自动排序 quickfix 列表

function! s:CompareQuickfixEntries(i1, i2)
  if bufname(a:i1.bufnr) == bufname(a:i2.bufnr)
    return a:i1.lnum == a:i2.lnum ? 0 : (a:i1.lnum < a:i2.lnum ? -1 : 1)
  else
    return bufname(a:i1.bufnr) < bufname(a:i2.bufnr) ? -1 : 1
  endif
endfunction

function! s:SortUniqQFList()
  let sortedList = sort(getqflist(), 's:CompareQuickfixEntries')
  let uniqedList = []
  let last = ''
  for item in sortedList
    let this = bufname(item.bufnr) . "\t" . item.lnum
    if this !=# last
      call add(uniqedList, item)
      let last = this
    endif
  endfor
  call setqflist(uniqedList)
endfunction
autocmd! QuickfixCmdPost * call s:SortUniqQFList()
于 2010-11-14T12:45:18.837 回答
0

一些我最喜欢的定制,我还没有发现太常见:

" Windows *********************************************************************"
set equalalways           " Multiple windows, when created, are equal in size"
set splitbelow splitright " Put the new windows to the right/bottom"

" Insert new line in command mode *********************************************"
map <S-Enter> O<ESC> " Insert above current line"
map <Enter> o<ESC>   " Insert below current line"

" After selecting something in visual mode and shifting, I still want that"
" selection intact ************************************************************"
vmap > >gv
vmap < <gv
于 2010-04-30T16:40:30.400 回答
0

现在才看到这个:

:nnoremap <esc> :noh<return><esc>

我在ViEmu 博客中找到了它,我真的很喜欢这个。一个简短的解释 - 它使 Esc 在正常模式下关闭搜索突出显示。

于 2009-08-25T19:55:13.060 回答
0
set tabstop=4
set shiftwidth=4
set cindent
set noautoindent
set noexpandtab
set nocompatible
set cino=:0(4u0
set backspace=indent,start
set term=ansi
let lpc_syntax_for_c=1
syntax enable

autocmd FileType c set cin noai nosi
autocmd FileType lpc set cin noai nosi
autocmd FileType css set nocin ai noet
autocmd FileType js set nocin ai noet
autocmd FileType php set nocin ai noet

function! DeleteFile(...)
  if(exists('a:1'))
    let theFile=a:1
  elseif ( &ft == 'help' )
    echohl Error
    echo "Cannot delete a help buffer!"
    echohl None
    return -1
  else
    let theFile=expand('%:p')
  endif
  let delStatus=delete(theFile)
  if(delStatus == 0)
    echo "Deleted " . theFile
  else
    echohl WarningMsg
    echo "Failed to delete " . theFile
    echohl None
  endif
  return delStatus
endfunction
"delete the current file
com! Rm call DeleteFile()
"delete the file and quit the buffer (quits vim if this was the last file)
com! RM call DeleteFile() <Bar> q!
于 2009-08-25T19:56:58.673 回答
0

http://github.com/elventails/vim/blob/master/vimrc

有 CakePHP/PHP/Git 的附加功能

请享用!

将添加你们正在使用的不错的选项并更新存储库;

干杯,

于 2009-10-29T20:00:40.327 回答
0

我的.vimrc、我使用的插件和其他调整都是定制的,以帮助我完成最常执行的任务:

  • 使用 Mutt/Vim 读/写电子邮件
  • 在 GNU/Linux 下编写 C 代码,通常使用 glib、gobject、gstreamer
  • 浏览/阅读 C 源代码
  • 使用 Python、Ruby on Rails 或 Bash 脚本
  • 使用 HTML、Javascript、CSS 开发 Web 应用程序

我在这里有一些关于我的Vim 配置的更多信息

于 2010-04-30T16:29:16.807 回答
0
" **************************
" * vim general options ****
" **************************
set nocompatible
set history=1000
set mouse=a

" don't have files trying to override this .vimrc:
set nomodeline

" have <F1> prompt for a help topic, rather than displaying the introduction
" page, and have it do this from any mode:
nnoremap <F1> :help<Space>
vmap <F1> <C-C><F1>
omap <F1> <C-C><F1>
map! <F1> <C-C><F1>

set title

" **************************
" * set visual options *****
" **************************
set nu
set ruler
syntax on

" colorscheme oceandeep
set background=dark

set wildmenu
set wildmode=list:longest,full

" use "[RO]" for "[readonly]"
set shortmess+=r

set scrolloff=3

" display the current mode and partially-typed commands in the status line:
set showmode
set showcmd

" don't make it look like there are line breaks where there aren't:
set nowrap

" **************************
" * set editing options ****
" **************************
set autoindent
filetype plugin indent on
set backspace=eol,indent,start
autocmd FileType text setlocal textwidth=80
autocmd FileType make set noexpandtab shiftwidth=8

" * Search & Replace
" make searches case-insensitive, unless they contain upper-case letters:
set ignorecase
set smartcase
" show the `best match so far' as search strings are typed:
set incsearch
" assume the /g flag on :s substitutions to replace all matches in a line:
set gdefault

" ***************************
" * tab completion **********
" ***************************
setlocal omnifunc=syntaxcomplete#Complete
imap <Tab> <C-x><C-o>
inoremap <tab> <c-r>=InsertTabWrapper()<cr>

" ***************************
" * keyboard mapping ********
" ***************************
imap <A-1> <Esc>:tabn 1<CR>i
imap <A-2> <Esc>:tabn 2<CR>i
imap <A-3> <Esc>:tabn 3<CR>i
imap <A-4> <Esc>:tabn 4<CR>i
imap <A-5> <Esc>:tabn 5<CR>i
imap <A-6> <Esc>:tabn 6<CR>i
imap <A-7> <Esc>:tabn 7<CR>i
imap <A-8> <Esc>:tabn 8<CR>i
imap <A-9> <Esc>:tabn 9<CR>i

map <A-1> :tabn 1<CR>
map <A-2> :tabn 2<CR>
map <A-3> :tabn 3<CR>
map <A-4> :tabn 4<CR>
map <A-5> :tabn 5<CR>
map <A-6> :tabn 6<CR>
map <A-7> :tabn 7<CR>
map <A-8> :tabn 8<CR>
map <A-9> :tabn 9<CR>

" ***************************
" * Utilities Needed ********
" ***************************
function InsertTabWrapper()
      let col = col('.') - 1
      if !col || getline('.')[col - 1] !~ '\k'
          return "\<tab>"
      else
          return "\<c-p>"
      endif
endfunction

" end of .vimrc
于 2008-11-02T21:59:14.867 回答
0

我将我的 .vimrc 放在http://dotfiles.org/~petdance/.vimrc上,我在 dotfiles.org 上也有一些其他文件

于 2008-10-03T00:47:12.227 回答
0

:map + v%zf # 点击“+”折叠函数/循环括号内的任何内容。

:set expandtab # tab 会根据 ts (tabspace) 的设置展开为空格

于 2009-10-28T12:33:28.473 回答
0

这是我的!感谢分享。您可以在此处找到有关 vim 插件的其他内容:http: //github.com/ametaireau/dotfiles/

希望能帮助到你。

" My .vimrc configuration file.
" =============================
"
" Plugins
" -------
" Comes with a set of utilities to enhance the user experience.
" Django and python snippets are possible thanks to the snipmate
" plugin.
"
" A also uses taglist and NERDTree vim plugins.
"
" Shortcuts
" ----------
" Here are some shortcuts I like to use when editing text using VIM:
"
" <alt-left/right> to navigate trough tabs
" <ctrl-e> to display the explorator
" <ctrl-p> for the code explorator
" <ctrl-space> to autocomplete
" <ctrl-n> enter tabnew to open a new file
" <alt-h> highlight the lines of more than 80 columns
" <ctrl-h> set textwith to 80 cols
" <maj-k> when on a python file, open the related pydoc documentation
" ,v and ,V to show/edit and reload the vimrc configuration file

colorscheme evening 
syntax on                       " syntax highlighting
filetype on                     " to consider filetypes ...
filetype plugin on              " ... and in plugins
set directory=~/.vim/swp        " store the .swp files in a specific path
set expandtab                   " enter spaces when tab is pressed
set tabstop=4                   " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4                " number of spaces to use for auto indent
set autoindent                  " copy indent from current line on new line
set number                      " show line numbers
set backspace=indent,eol,start  " make backspaces more powerful 
set ruler                       " show line and column number
set showcmd                     " show (partial) command in status line
set incsearch                   " highlight search
set noignorecase
set infercase
set nowrap

" shortcuts
map <c-n> :tabnew 
map <silent><c-e> :NERDTreeToggle <cr>
map <silent><c-p> :TlistToggle <cr>
nnoremap <a-right> gt
nnoremap <a-left>  gT
command W w !sudo tee % > /dev/null
map <buffer> K :execute "!pydoc " . expand("<cword>")<CR>
map <F2> :set textwidth=80 <cr>
" Replace trailing slashes
map <F3> :%s/\s\+$//<CR>:exe ":echo'trailing slashes removes'"<CR>
map <silent><F6> :QFix<CR>

" edit vim quickly
map ,v :sp ~/.vimrc<CR><C-W>_
map <silent> ,V :source ~/.vimrc<CR>:filetype detect<CR>:exe ":echo'vimrc reloaded'"<CR> 

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set noexpandtab
au BufRead,BufNewFile *.h set noexpandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" remap CTRL+N to CTRL + space
inoremap <Nul> <C-n>

" Omnifunc completers
autocmd FileType python set omnifunc=pythoncomplete#Complete

" Tlist configuration
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_Close_On_Select = 0
let Tlist_Auto_Update = 1
let Tlist_Process_File_Always = 1
let Tlist_Use_Right_Window = 1
let Tlist_WinWidth = 40
let Tlist_Show_One_File = 1
let Tlist_Show_Menu = 0
let Tlist_File_Fold_Auto_Close = 0
let Tlist_Ctags_Cmd = '/usr/bin/ctags'
let tlist_css_settings = 'css;e:SECTIONS'

" NerdTree configuration
let NERDTreeIgnore = ['\.pyc$', '\.pyo$']

" Highlight more than 80 columns lines on demand
nnoremap <silent><F1>
\    :if exists('w:long_line_match') <Bar>
\        silent! call matchdelete(w:long_line_match) <Bar>
\        unlet w:long_line_match <Bar>
\    elseif &textwidth > 0 <Bar>
\        let w:long_line_match = matchadd('ErrorMsg', '\%>'.&tw.'v.\+', -1) <Bar>
\    else <Bar>
\        let w:long_line_match = matchadd('ErrorMsg', '\%>80v.\+', -1) <Bar>
\    endif<CR>

command -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
  if exists("g:qfix_win") && a:forced == 0
    cclose
    unlet g:qfix_win
  else
    copen 10
    let g:qfix_win = bufnr("$")
  endif
endfunction
于 2010-06-07T12:37:23.007 回答
0

我的~/.vimrc非常标准(主要是.$VIMRUNTIME/vimrc_example.vim~/.vim~/.vim/ftplugin~/.vim/syntax

于 2008-10-03T14:52:48.213 回答
0

我最喜欢的 .vimrc 是一组用于处理宏的映射:

nnoremap <Leader>qa mqGo<Esc>"ap
nnoremap <Leader>qb mqGo<Esc>"bp
nnoremap <Leader>qc mqGo<Esc>"cp
<SNIP>
nnoremap <Leader>qz mqGo<Esc>"zp

nnoremap <Leader>Qa G0"ad$dd'q
nnoremap <Leader>Qb G0"bd$dd'q
nnoremap <Leader>Qc G0"cd$dd'q
<SNIP>
nnoremap <Leader>Qz G0"zd$dd'q

有了这个 \q[az] 将标记您的位置,并在当前文件的底部打印给定寄存器的内容, \Q[az] 将把最后一行的内容放入给定寄存器并返回到您的标记的位置。使编辑宏或将一个宏复制和调整到新寄存器中变得非常容易。

于 2010-04-15T20:16:52.050 回答
0

我制作了一个功能,可以自动将您的文本发送到私人粘贴箱。

let g:pfx='' " prefix for private pastebin.

function PBSubmit()
python << EOF
import vim
import urllib2 as url
import urllib

pfx = vim.eval( 'g:pfx' )

URL = 'http://'

if pfx == '':
    URL += 'pastebin.com/pastebin.php'
else:
    URL += pfx + '.pastebin.com/pastebin.php'

data = urllib.urlencode( {  'code2': '\n'.join( vim.current.buffer ).decode( 'utf-8' ).encode( 'latin-1' ),
                            'email': '',
                            'expiry': 'd',
                            'format': 'text',
                            'parent_pid': '',
                            'paste': 'Send',
                            'poster': '' } )

url.urlopen( URL, data )

print 'Submitted to ' + URL
EOF
endfunction

map <Leader>pb :call PBSubmit()<CR>
于 2010-01-16T23:29:02.783 回答
0

下面最重要的事情可能是字体选择和配色方案。是的,我花了太长时间愉快地摆弄这些东西。:)

"set tildeop
set nosmartindent
" set guifont=courier
" awesome programming font
" set guifont=peep:h09:cANSI
" another nice looking font for programming and general use
set guifont=Bitstream_Vera_Sans_MONO:h09:cANSI
set lines=68
set tabstop=2
set shiftwidth=2
set expandtab
set ignorecase
set nobackup
" set writebackup

" Some of my favourite colour schemes, lovingly crafted over the years :)
" very dark scarlet background, almost white text
" hi Normal   guifg=#FFFFF0 guibg=#3F0000 ctermfg=white ctermbg=Black
" C64 colours
"hi Normal   guifg=#8CA1EC guibg=#372DB4 ctermfg=white ctermbg=Black 
" nice forest green background with bisque fg
hi Normal   guifg=#9CfCb1 guibg=#279A1D ctermfg=white ctermbg=Black 
" dark green background with almost white text 
"hi Normal   guifg=#FFFFF0 guibg=#003F00 ctermfg=white ctermbg=Black

" french blue background, almost white text
"hi Normal   guifg=#FFFFF0 guibg=#00003F ctermfg=white ctermbg=Black

" slate blue bg, grey text
"hi Normal   guifg=#929Cb1 guibg=#20403F ctermfg=white ctermbg=Black 

" yellow/orange bg, black text
hi Normal   guifg=#000000 guibg=#f8db3a ctermfg=white ctermbg=Black 
于 2008-12-05T00:17:13.370 回答
0

我为我的待办事项或清单文档创建了自己的语法,其中突出显示了诸如

-> 这样做(粗体)

!-> 立即执行此操作(橙色)

++> 正在执行此操作(绿色)

=> 完成(灰色)

我在 ./syntax/ 中有文件作为 fc_comdoc.vim

在 vimrc 中为我的自定义扩展名 .txtcd 或 .txtap 的任何内容设置此语法

au BufNewFile,BufRead *.txtap,*.txtcd   setf fc_comdoc
于 2009-03-31T14:44:16.487 回答
0

其中很多来自维基顺便说一句。

set nocompatible
source $VIMRUNTIME/mswin.vim
behave mswin
set nobackup
set tabstop=4
set nowrap

set guifont=Droid_Sans_Mono:h9:cANSI
colorscheme torte
set shiftwidth=4
set ic
syn off
set nohls
set acd
set autowrite
noremap \c "+yy
noremap \x "+dd
noremap \t :tabnew<CR>
noremap \2 I"<Esc>A"<Esc>
noremap \3 bi'<Esc>ea'<Esc>
noremap \" i"<Esc>ea"<Esc>
noremap ?2 Bi"<Esc>Ea"<Esc>
set matchpairs+=<:>
nnoremap <C-N> :next<CR>
nnoremap <C-P> :prev<CR>
nnoremap <Tab> :bnext<CR>
nnoremap <S-Tab> :bprevious<CR>
nnoremap \w :let @/=expand("<cword>")<Bar>split<Bar>normal n<CR>
nnoremap \W :let @/='\<'.expand("<cword>").'\>'<Bar>split<Bar>normal n<CR>

autocmd FileType xml exe ":silent %!xmllint --format --recover - "
autocmd FileType cpp set tabstop=2 shiftwidth=2 expandtab autoindent smarttab
autocmd FileType sql set tabstop=2 shiftwidth=2 expandtab autoindent smarttab

" Map key to toggle opt
function MapToggle(key, opt)
  let cmd = ':set '.a:opt.'! \| set '.a:opt."?\<CR>"
  exec 'nnoremap '.a:key.' '.cmd
  exec 'inoremap '.a:key." \<C-O>".cmd
endfunction
command -nargs=+ MapToggle call MapToggle(<f-args>)

map <F6> :if exists("syntax_on") <Bar> syntax off <Bar> else <Bar> syntax enable <Bar> endif <CR>

" Display-altering option toggles
MapToggle <F7> hlsearch
MapToggle <F8> wrap
MapToggle <F9> list

" Behavior-altering option toggles
MapToggle <F10> scrollbind
MapToggle <F11> ignorecase
MapToggle <F12> paste
set pastetoggle=<F12>
于 2009-10-30T00:35:39.557 回答
0

对 C/C++ 和 svn 使用有用的东西(可以很容易地为 git/hg/whatever 修改)。我将它们设置为我的 F 键。

不是 C#,但仍然有用。

function! SwapFilesKeep()
    " Open a new window next to the current one with the matching .cpp/.h pair"
    let command = "echo " . bufname("%") . "|sed s,\h$,\H,|sed s,cpp,h,|sed s,H$,cpp,"
    let newfilename = system(command)
    silent execute("vs " . newfilename)
endfunction

function! SwapFiles()
    " swap between .cpp and .h "
    let command = "echo " . bufname("%") . "|sed s,\h$,\H,|sed s,cpp,h,|sed s,H$,cpp,"
    let newfilename = system(command)
    silent execute("e " . newfilename)
endfunction

function! SvnDiffAll()
    let tempfile = system("tempfile")
    silent execute ":!svn diff .>" . tempfile
    execute ":sf ".tempfile
    return
endfunction

function! SvnLog()
    let fn = expand('%')
    let tempfile = system("tempfile")
    silent execute ":!svn log -v " . fn . ">" . tempfile
    execute ":sf ".tempfile
    return
endfunction

function! SvnStatus()
    let tempfile = system("tempfile")
    silent execute ":!svn status .>" . tempfile
    execute ":sf ".tempfile
    return
endfunction

function! SvnDiff()
    " diff with BASE "
    let dir = expand('%:p:h')
    let fn = expand('%')
    let fn = substitute(fn,".*\\","","")
    let fn = substitute(fn,".*/","","")
    silent execute ":vert diffsplit " . dir . "/.svn/text-base/" . fn . ".svn-base"
    silent execute ":set ft=cpp"
    unlet fn dir
    return
endfunction
于 2009-10-22T10:01:12.977 回答
0

我倾向于将我的 .vimrc 拆分为不同的部分,以便我可以在我运行的所有不同机器上打开和关闭不同的部分,即 Windows 上的一些位,Linux 上的一些位等:


"*****************************************
"* SECTION 1 - THINGS JUST FOR GVIM      *
"*****************************************
if v:version >= 700

    "Note: Other plugin files
    source ~/.vim/ben_init/bens_pscripts.vim
    "source ~/.vim/ben_init/stim_projects.vim
    "source ~/.vim/ben_init/temp_commands.vim
    "source ~/.vim/ben_init/wwatch.vim

    "Extract sections of code as a function (works in C, C++, Perl, Java)
    source ~/.vim/ben_init/functify.vim

    "Settings that relate to the look/feel of vim in the GUI
    source ~/.vim/ben_init/gui_settings.vim

    "General VIM settings
    source ~/.vim/ben_init/general_settings.vim

    "Settings for programming
    source ~/.vim/ben_init/c_programming.vim

    "Settings for completion
    source ~/.vim/ben_init/completion.vim

    "My own templating system
    source ~/.vim/ben_init/templates.vim

    "Abbreviations and interesting key mappings
    source ~/.vim/ben_init/abbrev.vim

    "Plugin configuration
    source ~/.vim/ben_init/plugin_config.vim

    "Wiki configuration
    source ~/.vim/ben_init/wiki_config.vim

    "Key mappings
    source ~/.vim/ben_init/key_mappings.vim

    "Auto commands
    source ~/.vim/ben_init/autocmds.vim

    "Handy Functions written by other people
    source ~/.vim/ben_init/handy_functions.vim

    "My own omni_completions
    source ~/.vim/ben_init/bens_omni.vim

endif
于 2009-10-28T14:20:34.333 回答
0
set ai 
set si 
set sm 
set sta 
set ts=3 
set sw=3 
set co=130 
set lines=50 
set nowrap 
set ruler 
set showcmd 
set showmode 
set showmatch 
set incsearch 
set hlsearch 
set gfn=Consolas:h11
set guioptions-=T
set clipboard=unnamed
set expandtab
set nobackup

syntax on 
colors torte
于 2009-10-28T12:37:12.103 回答
0

我多年插手 vim 的结果都在这里

于 2009-10-22T09:28:47.253 回答
0
"{{{1 Защита от множественных загрузок 
if exists("b:dollarHOMEslashdotvimrcFileLoaded")
    finish
endif
let b:dollarHOMEslashdotvimrcFileLoaded=1
" set t_Co=8
" set t_Sf=[3%p1%dm
" set t_Sb=[4%p1%dm
"{{{1 Options 
"{{{2 set 
set nocompatible
set background=dark
set display+=lastline
"set iminsert=0
"set imsearch=0
set grepprg=grep\ -nH\ $*
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set backspace=indent,eol,start
set autoindent
set nosmartindent
set backup
set conskey
set bioskey
set browsedir=buffer
" bomb may work bad
set nobomb
exe "set backupdir=".$HOME."/.vimbackup,."
set backupext=~
set history=32
set ruler
set showcmd
set hlsearch
set incsearch
set nocindent
set textwidth=80
set complete=.,i,d,t,w,b,u,k
" set conskey
set noconfirm
set cscopetag
set cscopetagorder=1
" set copyindent
" !may be not safe
set exrc
set secure
" set foldclose
set noswapfile
" set swapsync=sync
set fsync
set guicursor="a:block-blinkoff0"
set autowriteall
set hidden
set nojoinspaces
set nostartofline
" set virtualedit+=onemore
set lazyredraw
set visualbell
set makeef=make.##.err.log
set modelines=16
set more
set virtualedit+=block
set winaltkeys=no
set fileencodings=utf-8,cp1251,koi8-r,default
set encoding=utf-8
set list
set listchars=tab:>-,trail:-,nbsp:_
set magic
set pastetoggle=<F1>
set foldmethod=marker
set wildmenu
set wildcharm=<Tab>
set formatoptions=arcoqn12w
"set formatoptions+=t
set scrolloff=2

"{{{3 define keys
"{{{4 get keys from zkbd
if isdirectory($HOME."/.zkbd") &&
  \filereadable($HOME."/.zkbd/".$TERM."-pc-linux-gnu")
    let s:keys=split(system("cat ".
                \shellescape($HOME."/.zkbd/".$TERM."-pc-linux-gnu").
                \" | grep \"^key\\\\[\" | ".
                \"sed -re \"s/^key\\\\[([[:alnum:]]*)\\\\]='(.*)'\\$".
                           \"/\\\\1=\\\\2/g\""), "\\n")
    for key in s:keys
        let tmp=split(key, "=")
        if tmp[0]=~"^F\\d\\+$"
            execute "set <".tmp[0].">=".
                        \substitute(tmp[1], "\\^\\[", "\<ESC>", "g")
        endif
    endfor
endif
" function g:DefineKeys()
    "{{{4 screen
    if 0 && $_SECONDLAUNCH
        set    <F1>=[11~
        set    <F2>=[12~
        set    <F3>=[13~
        set    <F4>=[14~
        set    <F5>=[15~
        set    <F6>=[17~
        set    <F7>=[18~
        set    <F8>=[19~
        set    <F9>=[20~
        set   <F10>=[21~
        set   <F11>=[23~
        set   <F12>=[24~
        set  <S-F1>=[23~
        set  <S-F2>=[24~
        set  <S-F3>=[25~
        set  <S-F4>=[26~
        set  <S-F5>=[28~
        set  <S-F6>=[29~
        set  <S-F7>=[31~
        set  <S-F8>=[32~
        set  <S-F9>=[33~
        set <S-F10>=[34~
        set <S-F11>=[23$
        set <S-F12>=[24$
        set  <HOME>=[7~
        set   <END>=[8~
    "{{{4 xterm 
    elseif $TERM=="xterm"
        set      <M-a>=a
        set      <M-b>=b
        set      <M-c>=c
        set      <M-d>=d
        set      <M-e>=e
        set      <M-f>=f
        set      <M-g>=g
        set      <M-h>=h
        set      <M-i>=i
        set      <M-j>=j
        set      <M-k>=k
        set      <M-l>=l
        set      <M-m>=m
        set      <M-n>=n
        set      <M-o>=o
        set      <M-p>=p
        set      <M-q>=q
        set      <M-r>=r
        set      <M-s>=s
        set      <M-t>=t
        set      <M-u>=u
        set      <M-v>=v
        set      <M-w>=w
        set      <M-x>=x
        set      <M-y>=y
        set      <M-z>=z
        "set <M-SPACE>= 
        "set    <Left>=OD
        "set  <S-Left>=O2D
        "set  <C-Left>=O5D
        "set   <Right>=OC
        "set <S-Right>=O2C
        "set <C-Right>=O5C
        "set      <Up>=OA
        "set    <S-Up>=O2A
        "set    <C-Up>=O5A
        "set    <Down>=OB
        "set  <S-Down>=O2B
        "set  <C-Down>=O5B
        set       <F1>=[11~
        set       <F2>=[12~
        set       <F3>=[13~
        set       <F4>=[14~
        set       <F5>=[15~
        set       <F6>=[17~
        set       <F7>=[18~
        set       <F8>=[19~
        set       <F9>=[20~
        set      <F10>=[21~
        set      <F11>=[23~
        set      <F12>=[24~
        "set    <C-F1>=
        "set    <C-F2>=
        "set    <C-F3>=
        "set    <C-F4>=
        "set    <C-F5>=[15;5~
        "set    <C-F6>=[17;5~
        "
        "set    <C-F7>=[18;5~
        "set    <C-F8>=[19;5~
        "set    <C-F9>=[20;5~
        "set   <C-F10>=[21;5~
        "set   <C-F11>=[23;5~
        "set   <C-F12>=[24;5~
        set     <S-F1>=[11;2~
        set     <S-F2>=[12;2~
        set     <S-F3>=[13;2~
        set     <S-F4>=[14;2~
        set     <S-F5>=[15;2~
        set     <S-F6>=[17;2~
        set     <S-F7>=[18;2~
        set     <S-F8>=[19;2~
        set     <S-F9>=[20;2~
        set    <S-F10>=[21;2~
        set    <S-F11>=[23;2~
        set    <S-F12>=[24;2~
        set      <END>=OF
        set    <S-END>=O2F
        set   <S-HOME>=O2H
        set     <HOME>=OH
        set      <DEL>=
        " set   <PageUp>=[5~
        " set <PageDown>=[6~
        "  noremap  <DEL>
        " inoremap  <DEL>
        " cnoremap  <DEL>
        set    <S-Del>=[3;2~
        " set   <C-Del>=[3;5~
        " set   <M-Del>=[3;3~
    "{{{4 rxvt --- aterm
    elseif $TERM=="rxvt"
        set      <M-a>=a
        set      <M-b>=b
        set      <M-c>=c
        set      <M-d>=d
        set      <M-e>=e
        set      <M-f>=f
        set      <M-g>=g
        set      <M-h>=h
        set      <M-i>=i
        set      <M-j>=j
        set      <M-k>=k
        set      <M-l>=l
        set      <M-m>=m
        set      <M-n>=n
        set      <M-o>=o
        set      <M-p>=p
        set      <M-q>=q
        set      <M-r>=r
        set      <M-s>=s
        set      <M-t>=t
        set      <M-u>=u
        set      <M-v>=v
        set      <M-w>=w
        set      <M-x>=x
        set      <M-y>=y
        set      <M-z>=z
        set       <F1>=OP
        set       <F2>=OQ
        set       <F3>=OR
        set       <F4>=OS
        set       <F5>=[15~
        set       <F6>=[17~
        set       <F7>=[18~
        set       <F8>=[19~
        set       <F9>=[20~
        set      <F10>=[21~
        set      <F11>=[23~
        set      <F12>=[24~
        set     <S-F1>=[23~
        set     <S-F2>=[24~
        set     <S-F3>=[25~
        set     <S-F4>=[26~
        set     <S-F5>=[28~
        set     <S-F6>=[29~
        set     <S-F7>=[31~
        set     <S-F8>=[32~
        set     <S-F9>=[33~
        set    <S-F10>=[34~
        set    <S-F11>=[23$
        set    <S-F12>=[24$
        " set  <C-S-F2>=[24^
        " set  <C-S-F3>=[25^
        " set  <C-S-F4>=[26^
        " set  <C-S-F5>=[28^
        " set  <C-S-F6>=[29^
        " set  <C-S-F7>=[31^
        " set  <C-S-F8>=[32^
        " set  <C-S-F9>=[33^
        " set <C-S-F10>=[34^
        " set <C-S-F11>=[23@
        " set <C-S-F12>=[24@
        " set    <M-F5>=<F5>
        " set    <M-F6>=<F6>
        " set    <M-F7>=<F7>
        " set    <M-F8>=<F8>
        " set    <M-F9>=<F9>
        " set   <M-F10>=<F10>
        " set   <M-F11>=<F11>
        " set   <M-F12>=<F12>
        " set  <M-S-F5>=<S-F5>
        " set  <M-S-F6>=<S-F6>
        " set  <M-S-F7>=<S-F7>
        " set  <M-S-F8>=<S-F8>
        " set  <M-S-F9>=<S-F9>
        " set <M-S-F10>=<S-F10>
        " set <M-S-F11>=<S-F11>
        " set <M-S-F12>=<S-F12>
    "{{{4 rxvt-unicode --- urxvt
    elseif $TERM=="rxvt-unicode"
        set      <M-a>=a
        set      <M-b>=b
        set      <M-c>=c
        set      <M-d>=d
        set      <M-e>=e
        set      <M-f>=f
        set      <M-g>=g
        set      <M-h>=h
        set      <M-i>=i
        set      <M-j>=j
        set      <M-k>=k
        set      <M-l>=l
        set      <M-m>=m
        set      <M-n>=n
        set      <M-o>=o
        set      <M-p>=p
        set      <M-q>=q
        set      <M-r>=r
        set      <M-s>=s
        set      <M-t>=t
        set      <M-u>=u
        set      <M-v>=v
        set      <M-w>=w
        set      <M-x>=x
        set      <M-y>=y
        set      <M-z>=z
        set       <F1>=[11~
        set       <F2>=[12~
        set       <F3>=[13~
        set       <F4>=[14~
        set       <F5>=[15~
        set       <F6>=[17~
        set       <F7>=[18~
        set       <F8>=[19~
        set       <F9>=[20~
        set      <F10>=[21~
        set      <F11>=[23~
        set      <F12>=[24~
        " fluxbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        set     <S-F1>=[23~
        set     <S-F2>=[24~
        set     <S-F3>=[25~
        set     <S-F4>=[26~
        set     <S-F5>=[28~
        set     <S-F6>=[29~
        set     <S-F7>=[31~
        set     <S-F8>=[32~
        set     <S-F9>=[33~
        set    <S-F10>=[34~
        set    <S-F11>=[23$
        set    <S-F12>=[24$
        " set    <C-F1>=[11^
        " set    <C-F2>=[12^
        " set    <C-F3>=[13^
        " set    <C-F4>=[14^
        " set    <C-F5>=[15^
        " set    <C-F6>=[17^
        " set    <C-F7>=[18^
        " set    <C-F8>=[19^
        " set    <C-F9>=[20^
        " set   <C-F10>=[21^
        " set   <C-F11>=[23^
        " set   <C-F12>=[24^
        " openbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        " set    <S-F1>=[23~
        " set    <S-F2>=[24~
        " set    <S-F3>=[25~
        " set    <S-F4>=[26~
        " set    <S-F5>=[28~
        " set    <S-F6>=[29~
        " set    <S-F7>=[31~
        " set    <S-F8>=[32~
        " set    <S-F9>=[33~
        " set   <S-F10>=[34~
        " set   <S-F11>=[23$
        " set   <S-F12>=[24$
        " set  <C-S-F2>=[24^
        " set  <C-S-F3>=[25^
        " set  <C-S-F4>=[26^
        " set  <C-S-F5>=[28^
        " set  <C-S-F6>=[29^
        " set  <C-S-F7>=[31^
        " set  <C-S-F8>=[32^
        " set  <C-S-F9>=[33^
        " set <C-S-F10>=[34^
        " set <C-S-F11>=[23@
        " set <C-S-F12>=[24@
        " set    <M-F5>=<F5>
        " set    <M-F6>=<F6>
        " set    <M-F7>=<F7>
        " set    <M-F8>=<F8>
        " set    <M-F9>=<F9>
        " set   <M-F10>=<F10>
        " set   <M-F11>=<F11>
        " set   <M-F12>=<F12>
        " set  <M-S-F5>=<S-F5>
        " set  <M-S-F6>=<S-F6>
        " set  <M-S-F7>=<S-F7>
        " set  <M-S-F8>=<S-F8>
        " set  <M-S-F9>=<S-F9>
        " set <M-S-F10>=<S-F10>
        " set <M-S-F11>=<S-F11>
        " set <M-S-F12>=<S-F12>
    endif
    " autocmd! DefineKeys
" endfunction
" "{{{4 autocmd 
" augroup DefineKeys
" autocmd BufEnter * call g:DefineKeys()
" augroup END

"{{{2 filetipe 
filetype plugin indent on
syntax on

"{{{2 let 
"{{{ NERDCommenter 
let           NERDShutUp=1
let      NERDSpaceDelims=1
"}}}
let g:c_syntax_for_h=1
let g:xml_syntax_folding=1
let           paste_mode=0 " 0 = normal, 1 = paste
"{{{3 keys if $TERM=="rxvt-unicode"
    " " fluxbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    " let    g:C_F1="\<ESC>[11^"
    " let    g:C_F2="\<ESC>[12^"
    " let    g:C_F3="\<ESC>[13^"
    " let    g:C_F4="\<ESC>[14^"
    " let    g:C_F5="\<ESC>[15^"
    " let    g:C_F6="\<ESC>[17^"
    " let    g:C_F7="\<ESC>[18^"
    " let    g:C_F8="\<ESC>[19^"
    " let    g:C_F9="\<ESC>[20^"
    " let   g:C_F10="\<ESC>[21^"
    " let   g:C_F11="\<ESC>[23^"
    " let   g:C_F12="\<ESC>[24^"
    " let  g:M_S_F1="\<ESC>\<ESC>[23$"
    " let  g:M_S_F2="\<ESC>\<ESC>[24$"
    " let  g:M_S_F3="\<ESC>\<ESC>[25$"
    " let  g:M_S_F4="\<ESC>\<ESC>[26$"
    " let  g:M_S_F5="\<ESC>\<ESC>[28$"
    " let  g:M_S_F6="\<ESC>\<ESC>[29$"
    " let  g:M_S_F7="\<ESC>\<ESC>[31$"
    " let  g:M_S_F8="\<ESC>\<ESC>[32$"
    " let  g:M_S_F9="\<ESC>\<ESC>[33$"
    " let g:M_S_F10="\<ESC>\<ESC>[34$"
    " let g:M_S_F11="\<ESC>\<ESC>[23$"
    " let g:M_S_F12="\<ESC>\<ESC>[24$"
    " let  g:M_C_F1="\<ESC>\<ESC>[11^"
    " let  g:M_C_F2="\<ESC>\<ESC>[12^"
    " let  g:M_C_F3="\<ESC>\<ESC>[13^"
    " let  g:M_C_F4="\<ESC>\<ESC>[14^"
    " let  g:M_C_F5="\<ESC>\<ESC>[15^"
    " let  g:M_C_F6="\<ESC>\<ESC>[17^"
    " let  g:M_C_F7="\<ESC>\<ESC>[18^"
    " let  g:M_C_F8="\<ESC>\<ESC>[19^"
    " let  g:M_C_F9="\<ESC>\<ESC>[20^"
    " let g:M_C_F10="\<ESC>\<ESC>[21^"
    " let g:M_C_F11="\<ESC>\<ESC>[23^"
    " let g:M_C_F12="\<ESC>\<ESC>[24^"
" endif
"{{{3 Настройки :TOhtml 
let    html_number_lines=1
" let  html_ignore_folding=1
let         html_use_css=1
let          html_no_pre=0
let            use_xhtml=1
"{{{3 Предотвратить загрузку 
let      loaded_cmdalias=0
"{{{3 Mine 
" let g:kmaps={"en": "", "ru": "russian-dvp"}

"{{{1 Syntax 
highlight TooLongLine term=reverse ctermfg=Yellow ctermbg=Red
2match TooLongLine /\S\%>81v/

"{{{1 Autocommands 
autocmd VimLeavePre * silent mksession! ~/.vim/lastSession.vim
au BufWritePost * if getline(1) =~ "^#!" | execute "silent! !chmod a+x %" | 
            \endif
autocmd BufRead,BufWinEnter * let &l:modifiable=(!(&ro && !&bt=="quickfix"))

"{{{1 Digraphs 
digraphs ca  94 "^
digraphs ga  96 "`
digraphs ti 126 "~

"{{{1 Menus 
" menu Encoding.koi8-r       :e ++enc=8bit-koi8-r<CR>
" menu Encoding.windows-1251 :e ++enc=8bit-cp1251<CR>
" menu Encoding.ibm-866      :e ++enc=8bit-ibm866<CR>
" menu Encoding.utf-8        :e ++enc=2byte-utf-8<CR>
" menu Encoding.ucs-2le      :e ++enc=ucs-2le<CR>

"{{{1 Команды 
function s:Substitute(sstring, line1, line2)
    execute a:line1.",".a:line2."!perl -pi -e 'use encoding \"utf8\"; s'".
                \escape(shellescape(a:sstring), '%!').
                \" 2>/dev/null"
endfunction
command -range=% -nargs=+ S call s:Substitute(<q-args>, <line1>, <line2>)

"{{{1 Mappings 
"{{{2 Menu mappings 

"{{{2 function mappings 
"
"{{{3 Function Eatchar 
function Eatchar(pat)
    let l:pat=((a:pat=="")?("*"):(a:pat))
    let c = nr2char(getchar(0))
    return (c =~ l:pat) ? '' : c
endfunction
"{{{3 CleverTab - tab to autocomplete and move indent 
function CleverTab()
    if strpart( getline('.'), col('.')-2, 1) =~ '^\k$'
        return "\<C-n>"
    else
        return "\<Tab>"
    endif
endfunction
inoremap <Tab> <C-R>=CleverTab()<CR>
"{{{3 Keymap switch 
function! SwitchKeymap(kmaps, knum)
    let s:kmapvals=values(a:kmaps)
    if a:knum=="+"
        let s:ki=index(s:kmapvals, &keymap)
        echo s:ki
        if s:ki==-1
            let &keymap=s:kmapvals[0]
            return
        elseif s:ki>=len(a:kmaps)-1
            let &keymap=s:kmapvals[0]
            return
        endif
        let &keymap=s:kmapvals[s:ki+1]
        return
    elseif has_key(a:kmaps, a:knum)
        let &keymap=a:kmaps[a:knum]
        return
    endif
    let s:ki=0
    for val in s:kmapvals
        if s:ki==a:knum
            let &keymap=val
            return
        endif
        let s:ki+=1
    endfor
    let &keymap=s:kmapvals[0]
endfunction
" inoremap <S-Tab> <C-\><C-o>:call<SPACE>SwitchKeymap(g:kmaps,<SPACE>"+")<C-m>


"{{{2 ToggleVerbose 
function! ToggleVerbose()
    let g:verboseflag = !g:verboseflag
    if g:verboseflag
        exe "set verbosefile=".$HOME."/.logs/vim/verbose.log
        set verbose=15
    else
        set verbose=0
        set verbosefile=
    endif
endfunction
noremap <F4>sv :call<SPACE>ToggleVerbose()
inoremap <F4>sv <C-o>:call<SPACE>ToggleVerbose()

"{{{2 Other mappings 
"{{{3 <.*F12> mappings - for some browsing 
 noremap <F12>        :TlistToggle<CR>
inoremap <F12>        <C-O>:TlistToggle<CR>
inoremap <S-F12>      <C-O>:BufExplorer<CR>
 noremap <S-F12>      :BufExplorer<CR>
inoremap <M-F12>      <C-O>:NERDTreeToggle<CR>
 noremap <M-F12>      :NERDTreeToggle<CR>
"{{{3 yank/paste 
vnoremap <C-Insert>   "+y
nnoremap <S-Insert>   "+p
inoremap <S-Insert>    <C-o><S-Insert>
vnoremap p            "_da<C-r><C-r>"<CR><ESC>
"{{{3 Motions 
"{{{4 Left/Right replace 
cnoremap <C-b>        <Left>
cnoremap <C-f>        <Right>
inoremap <C-b>        <C-\><C-o>h
inoremap <C-f>             <C-o>a

cnoremap <M-b>        <C-Right>
inoremap <M-b>        <C-o>w
inoremap <M-f>        <C-o>b
cnoremap <M-f>        <C-Left>
"{{{4 Page Up/Down 
nnoremap <C-b>             <C-U><C-U>
inoremap <PageUp>     <C-O><C-U><C-O><C-U>
nnoremap <C-f>             <C-D><C-D>
inoremap <PageDown>   <C-O><C-D><C-O><C-D>
"{{{4 Up/Down 
inoremap <C-G>        <C-\><C-o>gk
inoremap <Up>         <C-\><C-o>gk
inoremap <Down>       <C-\><C-o>gj
inoremap <C-l>        <C-\><C-o>gj
nnoremap <Down>       gj
vnoremap <Down>       gj
nnoremap  j           gj
vnoremap  j           gj
nnoremap gj            j
vnoremap gj            j
nnoremap gk            k
vnoremap gk            k
nnoremap  k           gk
vnoremap  k           gk
nnoremap <Up>         gk
vnoremap <Up>         gk
"{{{4 Smart <HOME> and <END> 

    " imap <HOME>        <C-o>g^
    " imap <C-O>g^<HOME> <C-o>^
" inoremap <C-o>^<HOME>  <C-o>0
    " imap <END>         <C-o>g$
" inoremap <C-o>g$<END>  <C-o>$
    " nmap <HOME>        <C-o>g^
    " nmap <C-O>g^<HOME>       ^
" nnoremap <C-o>^<HOME>        0
    " nmap <END>              g$
" nnoremap <C-o>g$<END>        $
"{{{3 <F3> and searching 
 noremap   <F3>            :nohl<CR>
inoremap <S-F3>       <C-o>:nohl<CR>
inoremap   <F3>       <C-o>n
"{{{3 <F2> for saving, <F10> for exiting 
 noremap <F2>              :up<CR>
inoremap <F2>         <C-o>:up<CR>
inoremap <F10>        <ESC>ZZ
 noremap <F10>        <ESC>ZZ
inoremap <S-F10>      <ESC>:q!<CR>
 noremap <S-F10>           :q!<CR>
inoremap <C-F10>      <ESC>:silent<SPACE>mksession<SPACE>session.vim<CR>:wq!
 noremap <C-F10>           :silent<SPACE>mksession<SPACE>session.vim<CR>:wq!
"{{{3 Something 
inoremap <C-z>        <C-o>u
 noremap <F1>         :set paste!<C-m>
inoremap <C-^>        <C-O><C-^>
inoremap <C-d>        <Del>
cnoremap <C-d>        <Del>
"{{{3 <C-j> 
inoremap <C-j>j       <C-o>:bn<CR>
inoremap <C-j>J       <C-o>:bN<CR>
 noremap <C-j>j            :bn<CR>
 noremap <C-j>J            :bN<CR>
"{{{3 for visual 
inoremap <S-Left>     <C-o>vge
inoremap <S-Up>       <C-o>vk
inoremap <S-Down>     <C-o>vj
inoremap <S-Right>    <C-o>ve
inoremap <S-End>      <C-o>v$
inoremap <S-Home>     <C-o>v$o^
vnoremap A            <C-c>i
"{{{3 <F4> 
"{{{4 <F4> folds 
 noremap <F4>{        a{{{<ESC>
inoremap <F4>{         {{{
 noremap <F4>}        a}}}<ESC>
inoremap <F4>}         }}}
inoremap <F4>[        <C-o>o{{{<C-o>:call NERDComment(0,"norm")<C-m>
 noremap <F4>[             o{{{<C-o>:call NERDComment(0,"norm")<C-m>
inoremap <F4>]        <C-o>o}}}<C-o>:call NERDComment(0,"norm")<C-m>
 noremap <F4>]             o}}}<C-o>:call NERDComment(0,"norm")<C-m>
"{{{4 <F4> folds 
inoremap <F4>f        <C-o>za<C-o>j<C-o>^
 noremap <F4>f             zaj
"{{{4 <F4> yank/paste/delete 
inoremap <F4>p        <C-o>p
inoremap <F4>gp       <C-o>"+p
inoremap <F4>y(       <C-o>ya)
inoremap <F4>yl       <C-o>yy
inoremap <F4>gy(      <C-o>"+ya)
inoremap <F4>gyl      <C-o>"+yy
inoremap <F4>P        <C-o>P
inoremap <F4>d(       <C-o>da)
inoremap <F4>dl       <C-o>dd
"{{{4 <F4> frequently used expressions 
inoremap <F4>c        \033[m<C-/><C-o>h
"{{{4 <F4> alternate 
    imap <F4>a        <C-o>:A<C-m>
     map <F4>a             :A<C-m>
"}}}
"}}}
"{{{3 «,» 
"
" &lower
" &upper
" &1st
" &2nd
" &both lower and upper (or both 1st and 2nd)
" prefixed with &e
" prefixed with &E
" is &Prefix for smth
" &prefixed with (([what]p(prefix)))
" -: nothing
" +: added
" /: replaced
" [invc]: for modes insert, normal, visual, command (for insert mode if
"         omitted)
"     |     vimrc       |        |        |       |       |
"     | i     n  v  c   |  tex   |   c    | html  | vim   | other
" ----+-----------------+--------+--------+-------+-------+---------------------
"   a | l     l         |        |        |       |       |
"   b | b     -  -  b   | +Pu    | +eb+Eb |       |       |
"   c | l     b         | +u     |        |       |       |
"   d | b     b  b      |        |        |       |       |
"   e | Pl          Pl  |        | +l+Pu  |       |       |
"   f | b(eb) - - b     |        |        |       | /u    | zsh:+el
"   g |                 |        |        |       |       |
"   h | b(el) - - b(el) | /u     |        |       |       | sh:/u+eu
"   i | l     l  -  l   |        |        |       |       |
"   j |                 |        |        |       |       |
"   k |                 |        |        |       |       |
"   l | l               | +Pu    |        |       |       | make:+u
"   m | l     l         | /[in]m | +u     |       |       |
"   n | l               | /l+u   |        | /l    | /l    |
"   o | l               |        |        |       |       |
"   p | -     -  -  b   | +el    |        |       |       |
"   q | b(eb)           | +Pl    |        |       |       |
"   r |                 | +u     |        |       |       |
"   s | l(el) - - b     | +u     | +u     |       | +u+eu | make,perl,zsh:+u
"   t | b(el) - - l     | +eu    |        |       |       |
"   u | l     -  -  b   |        |        | +u    | +u    |
"   v |                 |        |        |       |       |
"   w | b     -  -  b   |        |        |       |       |
"   x |                 |        |        |       |       |
"   y | l     l  l      |        |        |       |       |
"   z |                 |        |        |       |       |
" ' " | b               | /b     |        |       |       |
" ; : | 1               |        |        |       |       |
" , . | b     2  - 1    |        |        | +e2   |       |
" ? ! |                 |        |        |       |       |
" < > |                 | +b     |        | +b+eb | +1    |
" - _ |                 | +1     |        | +b    |       |
" @ / | b               |        |        |       |       |
"   = |                 |        |        |       |       |
"
"{{{4 insert 
inoremap ,<SPACE>     ,<SPACE>
inoremap ,<Esc>       ,
inoremap ,<BS>        <Nop>
inoremap ,ef           <C-o>I{<C-m><C-o>o}<C-o>O
inoremap ,eF            <C-m>{<C-m><C-o>o}<C-o>O
inoremap ,F              {<C-o>o}<C-o>O
inoremap ,f               {}<C-\><C-o>h
inoremap ,h               []<C-\><C-o>h
inoremap ,s               ()<C-\><C-o>h
inoremap ,u            <LT>><C-\><C-o>h
inoremap ,es               (<C-\><C-o>E<C-o>a)<C-\><C-o>h
inoremap ,H           [[::]]<C-o>F:
inoremap ,eh            [::]<C-o>F:
inoremap ,,                \
inoremap ,.           <C-o>==
inoremap ,w           <C-o>w
inoremap ,W           <C-o>W
inoremap ,b           <C-o>b
inoremap ,B           <C-o>B
inoremap ,a           <C-o>A
inoremap ,i           <C-o>I
inoremap ,l           <C-o>o
inoremap ,o           <C-o>O
inoremap ,dw          <C-o>"zdaw
inoremap ,p           <C-o>"zp
inoremap ,P           <C-o>"zP
inoremap ,yw          <C-o>"zyaw
inoremap ,y           <C-o>"zy
inoremap ,d           <C-o>"zd
inoremap ,D           <C-o>"_d
inoremap ,c           <C-o>:call<SPACE>NERDComment(0,"toggle")<C-m>
inoremap ,ec          <C-o>:call<SPACE>NERDComment(0,"toEOL")<C-m>
inoremap ,t                                <C-r>=Tr3transliterate(input("Translit: "))<C-m>
inoremap ,T           <C-o>b<C-o>"tdiw<C-r><C-r>=Tr3transliterate(@t)<C-m>
inoremap ,et          <C-o>B<C-o>"tdiW<C-r><C-r>=Tr3transliterate(@t)<C-m>
inoremap ,/            <C-x><C-f>
inoremap ,@                 <C-o>:w!<C-m>
inoremap ,;                 <C-o>%
inoremap ,m           <C-\><C-o>:call system("make &")<C-m>
inoremap ,n           \<C-m>
inoremap ,q           «»<C-\><C-o>h
inoremap ,Q           „“&lt;C-\><C-o>h
inoremap ,eq          “”&lt;C-\><C-o>h
inoremap ,eQ          ‘’&lt;C-\><C-o>h
inoremap ,"           ""<C-\><C-o>h
inoremap ,'           ''<C-\><C-o>h

"{{{4 visual 
vnoremap ,y                "zy
vnoremap ,d                "zd
vnoremap ,D                "_d
vnoremap ,p                "zp

"{{{4 command 
cnoremap ,s                ()<Left>
cnoremap ,S              \(\)<Left><Left>
cnoremap ,U           \<LT>\><Left><Left>
cnoremap ,u             <LT>><Left>
cnoremap ,F               \{}<Left>
cnoremap ,f                {}<Left>
cnoremap ,h                []<Left>
cnoremap ,H            [[::]]<Left><Left><Left>
cnoremap ,eh             [::]<Left><Left>
cnoremap ,i                  <Home>
cnoremap ,a                  <End>
cnoremap ,,                \
cnoremap ,.           <C-r>:
cnoremap ,p           <C-r>"
cnoremap ,P           <C-r>+
cnoremap ,z           <C-r>z
cnoremap ,t           <C-r>=Tr3transliterate(input("Translit: "))<C-m>
cnoremap ,b           <C-Left>
cnoremap ,w           <C-Right>
cnoremap ,B           <C-Left>
cnoremap ,W           <C-Right>

"{{{4 normal 
nnoremap ,C                     :!
nnoremap ,c           :call<SPACE>NERDComment(0,"toggle")<C-m>
nnoremap ,d           "_
nnoremap ,D           "_d
nnoremap ,m           :call system("make &")<C-m>
nnoremap ,a           $
nnoremap ,i           ^
nnoremap ,,           ==
nnoremap ,y           "zy
nnoremap ,p           "zp
nnoremap ,P           "zP

"{{{1 Functions 

"{{{1 
nohlsearch
" vim: ft=vim:fenc=utf-8:ts=4
于 2010-06-07T13:00:30.857 回答
0

没有 TAB 完成我活不下去

" Intelligent tab completion
inoremap <silent> <Tab> <C-r>=<SID>InsertTabWrapper(1)<CR>
inoremap <silent> <S-Tab> <C-r>=<SID>InsertTabWrapper(-1)<CR>

function! <SID>InsertTabWrapper(direction)
    let idx = col('.') - 1
    let str = getline('.')

    if a:direction > 0 && idx >= 2 && str[idx - 1] == ' '
                \&& str[idx - 2] =~? '[a-z]'
        if &softtabstop && idx % &softtabstop == 0
            return "\<BS>\<Tab>\<Tab>"
        else
            return "\<BS>\<Tab>"
        endif
    elseif idx == 0 || str[idx - 1] !~? '[a-z]'
        return "\<Tab>"
    elseif a:direction > 0
        return "\<C-p>"
    else
        return "\<C-n>"
    endif
endfunction
于 2009-11-20T21:16:38.927 回答
0

除了我的 vimrc,我还有更多的插件。一切都存储在http://github.com/jceb/vimrc的 git 存储库中。

" Author: Jan Christoph Ebersbach jceb AT e-jc DOT de

""""""""""""""""""""""""""""""""""""""""""""""""""
" ---------- Settings ----------
"
""""""""""""""""""""""""""""""""""""""""""""""""""

" Prevent modelines in files from being evaluated (avoids a potential
" security problem wherein a malicious user could write a hazardous
" modeline into a file) (override default value of 5)
set modeline
set modelines=5

" ########## miscellaneous options ##########
set nocompatible               " Use Vim defaults instead of 100% vi compatibility
set whichwrap=<,>              " Cursor key move the cursor to the next/previous line if pressed at the end/beginning of a line
set backspace=indent,eol,start " more powerful backspacing
set viminfo='20,\"50           " read/write a .viminfo file, don't store more than
set history=100                " keep 50 lines of command line history
set incsearch                  " Incremental search
set hidden                     " hidden allows to have modified buffers in background
set noswapfile                 " turn off backups and files
set nobackup                   " Don't keep a backup file
set magic                      " special characters that can be used in search patterns
set grepprg=grep\ --exclude='*.svn-base'\ -n\ $*\ /dev/null " don't grep through svn-base files
" Try do use the ack program when available
let tmp = ''
for i in ['ack', 'ack-grep']
 let tmp = substitute (system ('which '.i), '\n.*', '', '')
 if v:shell_error == 0
  exec "set grepprg=".tmp."\\ -a\\ -H\\ --nocolor\\ --nogroup"
  break
 endif
endfor
unlet tmp
"set autowrite                                               " Automatically save before commands like :next and :make
" Suffixes that get lower priority when doing tab completion for filenames.
" These are files we are not likely to want to edit or read.
set suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc,.pdf,.exe
"set autochdir                  " move to the directory of the edited file
set ssop-=options              " do not store global and local values in a session
set ssop-=folds                " do not store folds

" ########## visual options ##########
set wildmenu             " When 'wildmenu' is on, command-line completion operates in an enhanced mode.
set wildcharm=<C-Z>
set showmode             " If in Insert, Replace or Visual mode put a message on the last line.
set guifont=monospace\ 8 " guifont + fontsize
set guicursor=a:blinkon0 " cursor-blinking off!!
set ruler                " show the cursor position all the time
set nowrap               " kein Zeilenumbruch
set foldmethod=indent    " Standardfaltungsmethode
set foldlevel=99         " default fold level
set winminheight=0       " Minimal Windowheight
set showcmd              " Show (partial) command in status line.
set showmatch            " Show matching brackets.
set matchtime=2          " time to show the matching bracket
set hlsearch             " highlight search
set linebreak
set lazyredraw           " no readraw when running macros
set scrolloff=3          " set X lines to the curors - when moving vertical..
set laststatus=2         " statusline is always visible
set statusline=(%{bufnr('%')})\ %t\ \ %r%m\ #%{expand('#:t')}\ (%{bufnr('#')})%=[%{&fileformat}:%{&fileencoding}:%{&filetype}]\ %l,%c\ %P " statusline
"set mouse=n             " mouse only in normal mode support in vim
"set foldcolumn=1        " show folds
set number               " draw linenumbers
set nolist               " list nonprintable characters
set sidescroll=0         " scroll X columns to the side instead of centering the cursor on another screen
set completeopt=menuone  " show the complete menu even if there is just one entry
set listchars+=precedes:<,extends:> " display the following nonprintable characters
if $LANG =~ ".*\.UTF-8$" || $LANG =~ ".*utf8$" || $LANG =~ ".*utf-8$"
 set listchars+=tab:»·,trail:·" display the following nonprintable characters
endif
set guioptions=aegitcm   " disabled menu in gui mode
"set guioptions=aegimrLtT
set cpoptions=aABceFsq$  " q: When joining multiple lines leave the cursor at the position where it would be when joining two lines.
" $:  When making a change to one line, don't redisplay the line, but put a '$' at the end of the changed text.
" v: Backspaced characters remain visible on the screen in Insert mode.

colorscheme peaksea " default color scheme

" default color scheme
" if &term == '' || &term == 'builtin_gui' || &term == 'dumb'
if has('gui_running')
 set background=light " use colors that fit to a light background
else
 set background=light " use colors that fit to a light background
 "set background=dark " use colors that fit to a dark background
endif

syntax on " syntax highlighting

" ########## text options ##########
set smartindent              " always set smartindenting on
set autoindent               " always set autoindenting on
set backspace=2              " Influences the working of <BS>, <Del>, CTRL-W and CTRL-U in Insert mode.
set textwidth=0              " Don't wrap words by default
set shiftwidth=4             " number of spaces to use for each step of indent
set tabstop=4                " number of spaces a tab counts for
set noexpandtab              " insert spaces instead of tab
set smarttab                 " insert spaces only at the beginning of the line
set ignorecase               " Do case insensitive matching
set smartcase                " overwrite ignorecase if pattern contains uppercase characters
set formatoptions=lcrqn      " no automatic linebreak
set pastetoggle=<F11>        " put vim in pastemode - usefull for pasting in console-mode
set fileformats=unix,dos,mac " favorite fileformats
set encoding=utf-8           " set default-encoding to utf-8
set iskeyword+=_,-           " these characters also belong to a word
set matchpairs+=<:>

""""""""""""""""""""""""""""""""""""""""""""""""""
" ---------- Special Configuration ----------
"
""""""""""""""""""""""""""""""""""""""""""""""""""

" ########## determine terminal encoding ##########
"if has("multi_byte") && &term != 'builtin_gui'
"    set termencoding=utf-8
"
"    " unfortunately the normal xterm supports only latin1
"    if $TERM == "xterm" || $TERM == "xterm-color" || $TERM == "screen" || $TERM == "linux" || $TERM_PROGRAM == "GLterm"
"        let propv = system("xprop -id $WINDOWID -f WM_LOCALE_NAME 8s ' $0' -notype WM_LOCALE_NAME")
"        if propv !~ "WM_LOCALE_NAME .*UTF.*8"
"            set termencoding=latin1
"        endif
"    endif
"    " for the possibility of using a terminal to input and read chinese
"    " characters
"    if $LANG == "zh_CN.GB2312"
"        set termencoding=euc-cn
"    endif
"endif

" Set paper size from /etc/papersize if available (Debian-specific)
if filereadable('/etc/papersize')
 let s:papersize = matchstr(system('/bin/cat /etc/papersize'), '\p*')
 if strlen(s:papersize)
  let &printoptions = "paper:" . s:papersize
 endif
 unlet! s:papersize
endif

""""""""""""""""""""""""""""""""""""""""""""""""""
" ---------- Autocommands ----------
"
""""""""""""""""""""""""""""""""""""""""""""""""""

filetype plugin on " automatically load filetypeplugins
filetype indent on " indent according to the filetype

if !exists("autocommands_loaded")
 let autocommands_loaded = 1

 augroup templates
  " read templates
  " au BufNewFile ?akefile,*.mk TSkeletonSetup Makefile
  " au BufNewFile *.tex TSkeletonSetup latex.tex
  " au BufNewFile build*.xml TSkeletonSetup antbuild.xml
  " au BufNewFile test*.py,*Test.py TSkeletonSetup pyunit.py
  " au BufNewFile *.py TSkeletonSetup python.py
 augroup END

 augroup filetypesettings
  " Do word completion automatically
  au FileType debchangelog setl expandtab
  au FileType asciidoc,mkd,txt,mail call DoFastWordComplete()
  au FileType tex,plaintex setlocal makeprg=pdflatex\ \"%:p\"
  au FileType mkd setlocal autoindent
  au FileType java,c,cpp setlocal noexpandtab nosmarttab
  au FileType mail setlocal textwidth=70
  au FileType mail call FormatMail()
  au FileType mail setlocal formatoptions=tcrqan
  au FileType mail setlocal comments+=b:--
  au FileType txt setlocal formatoptions=tcrqn textwidth=72
  au FileType asciidoc,mkd,tex setlocal formatoptions=tcrq textwidth=72
  au FileType xml,docbk,xhtml,jsp setlocal formatoptions=tcrqn
  au FileType ruby setlocal shiftwidth=2

  au BufReadPost,BufNewFile *  set formatoptions-=o " o is really annoying
  au BufReadPost,BufNewFile *  call ReadIncludePath()

  " Special Makefilehandling
  au FileType automake,make setlocal list noexpandtab

  au FileType xsl,xslt,xml,html,xhtml runtime! scripts/closetag.vim

  " Omni completion settings
  "au FileType c  setlocal completefunc=ccomplete#Complete
  au FileType css setlocal omnifunc=csscomplete#CompleteCSS
  "au FileType html setlocal completefunc=htmlcomplete#CompleteTags
  "au FileType js setlocal completefunc=javascriptcomplete#CompleteJS
  "au FileType php setlocal completefunc=phpcomplete#CompletePHP
  "au FileType python setlocal completefunc=pythoncomplete#Complete
  "au FileType ruby setlocal completefunc=rubycomplete#Complete
  "au FileType sql setlocal completefunc=sqlcomplete#Complete
  "au FileType *  setlocal completefunc=syntaxcomplete#Complete
  "au FileType xml setlocal completefunc=xmlcomplete#CompleteTags

  au FileType help setlocal nolist

  " insert a prompt for every changed file in the commit message
  "au FileType svn :1![ -f "%" ] && awk '/^[MDA]/ { print $2 ":\n - " }' %
 augroup END

 augroup hooks
  " replace "Last Modified: with the current time"
  au BufWritePre,FileWritePre * call LastMod()

  " line highlighting in insert mode
  autocmd InsertLeave * set nocul
  autocmd InsertEnter * set cul

  " move to the directory of the edited file
  "au BufEnter *      if isdirectory (expand ('%:p:h')) | cd %:p:h | endif

  " jump to last position in the file
  au BufRead *  if line("'\"") > 0 && line("'\"") <= line("$") && &filetype != "mail" | exe "normal g`\"" | endif
  " jump to last position every time a buffer is entered
  "au BufEnter *  if line("'x") > 0 && line("'x") <= line("$") && line("'y") > 0 && line("'y") <= line("$") && &filetype != "mail" | exe "normal g'yztg`x" | endif
  "au BufLeave *  if &modifiable | exec "normal mxHmy"
 augroup END

 augroup highlight
  " make visual mode dark cyan
  au FileType * hi Visual ctermfg=Black ctermbg=DarkCyan gui=bold guibg=#a6caf0
  " make cursor red
  au BufEnter,BufRead,WinEnter * :call SetCursorColor()

  " hightlight trailing spaces and tabs and the defined print margin
  "au FileType * hi WhiteSpaceEOL_Printmargin ctermfg=black ctermbg=White guifg=Black guibg=White
  au FileType * hi WhiteSpaceEOL_Printmargin ctermbg=White guibg=White
  au FileType * let m='' | if &textwidth > 0 | let m='\|\%' . &textwidth . 'v.' | endif | exec 'match WhiteSpaceEOL_Printmargin /\s\+$' . m .'/'
 augroup END
endif

""""""""""""""""""""""""""""""""""""""""""""""""""
" ---------- Functions ----------
"
""""""""""""""""""""""""""""""""""""""""""""""""""

" set cursor color
function! SetCursorColor()
 hi Cursor ctermfg=black ctermbg=red guifg=Black guibg=Red
endfunction
call SetCursorColor()

" change dir the root of a debian package
function! GetPackageRoot()
 let sd = getcwd()
 let owd = sd
 let cwd = owd
 let dest = sd
 while !isdirectory('debian')
  lcd ..
  let owd = cwd
  let cwd = getcwd()
  if cwd == owd
   break
  endif
 endwhile
 if cwd != sd && isdirectory('debian')
  let dest = cwd
 endif
 return dest
endfunction

" vim tip: Opening multiple files from a single command-line
function! Sp(dir, ...)
 let split = 'sp'
 if a:dir == '1'
  let split = 'vsp'
 endif
 if(a:0 == 0)
  execute split
 else
  let i = a:0
  while(i > 0)
   execute 'let files = glob (a:' . i . ')'
   for f in split (files, "\n")
    execute split . ' ' . f
   endfor
   let i = i - 1
  endwhile
  windo if expand('%') == '' | q | endif
 endif
endfunction
com! -nargs=* -complete=file Sp call Sp(0, <f-args>)
com! -nargs=* -complete=file Vsp call Sp(1, <f-args>)

" reads the file .include_path - useful for C programming
function! ReadIncludePath()
 let include_path = expand("%:p:h") . '/.include_path'
 if filereadable(include_path)
  for line in readfile(include_path, '')
   exec "setl path +=," . line
  endfor
 endif
endfunction

" update last modified line in file
fun! LastMod()
 let line = line(".")
 let column = col(".")
 let search = @/

 " replace Last Modified in the first 20 lines
 if line("$") > 20
  let l = 20
 else
  let l = line("$")
 endif
 " replace only if the buffer was modified
 if &mod == 1
  silent exe "1," . l . "g/Last Modified:/s/Last Modified:.*/Last Modified: " .
     \ strftime("%a %d. %b %Y %T %z %Z") . "/"
 endif
 let @/ = search

 " set cursor to last position before substitution
 call cursor(line, column)
endfun

" toggles show marks plugin
"fun! ToggleShowMarks()
" if exists('b:sm') && b:sm == 1
"  let b:sm=0
"  NoShowMarks
"  setl updatetime=4000
" else
"  let b:sm=1
"  setl updatetime=200
"  DoShowMarks
" endif
"endfun

" reformats an email
fun! FormatMail()
 " workaround for the annoying mutt send-hook behavoir
 silent! 1,/^$/g/^X-To: .*/exec 'normal gg'|exec '/^To: /,/^Cc: /-1d'|1,/^$/s/^X-To: /To: /|exec 'normal dd'|exec '?Cc'|normal P
 silent! 1,/^$/g/^X-Cc: .*/exec 'normal gg'|exec '/^Cc: /,/^Bcc: /-1d'|1,/^$/s/^X-Cc: /Cc: /|exec 'normal dd'|exec '?Bcc'|normal P
 silent! 1,/^$/g/^X-Bcc: .*/exec 'normal gg'|exec '/^Bcc: /,/^Subject: /-1d'|1,/^$/s/^X-Bcc: /Bcc: /|exec 'normal dd'|exec '?Subject'|normal P

 " delete signature
 silent! /^> --[\t ]*$/,/^-- $/-2d
 " fix quotation
 silent! /^\(On\|In\) .*$/,/^-- $/-1:s/>>/> >/g
 silent! /^\(On\|In\) .*$/,/^-- $/-1:s/>\([^\ \t]\)/> \1/g
 " delete inner and trailing spaces
 normal :%s/[\xa0\x0d\t ]\+$//g
 normal :%s/\([^\xa0\x0d\t ]\)[\xa0\x0d\t ]\+\([^\xa0\x0d\t ]\)/\1 \2/g
 " format text
 normal gg
 " convert bad formated umlauts to real characters
 normal :%s/\\\([0-9]*\)/\=nr2char(submatch(1))/g
 normal :%s/&#\([0-9]*\);/\=nr2char(submatch(1))/g
 " break undo sequence
 normal iu
 exec 'silent! /\(^\(On\|In\) .*$\|\(schrieb\|wrote\):$\)/,/^-- $/-1!par '.&tw.'gqs0'
 " place the cursor before my signature
 silent! /^-- $/-1
 " clear search buffer
 let @/ = ""
endfun

" insert selection at mark a
fun! Insert() range
 exe "normal vgvmzomy\<Esc>"
 normal `y
 let lineA = line(".")
 let columnA = col(".")

 normal `z
 let lineB = line(".")
 let columnB = col(".")

 " exchange marks
 if lineA > lineB || lineA <= lineB && columnA > columnB
  " save z in c
  normal mc
  " store y in z
  normal `ymz
  " set y to old z
  normal `cmy
 endif

 exe "normal! gvd`ap`y"
endfun

" search with the selection of the visual mode
fun! VisualSearch(direction) range
 let l:saved_reg = @"
 execute "normal! vgvy"
 let l:pattern = escape(@", '\\/.*$^~[]')
 let l:pattern = substitute(l:pattern, "\n$", "", "")
 if a:direction == '#'
  execute "normal! ?" . l:pattern . "^M"
 elseif a:direction == '*'
  execute "normal! /" . l:pattern . "^M"
 elseif a:direction == '/'
  execute "normal! /" . l:pattern
 else
  execute "normal! ?" . l:pattern
 endif
 let @/ = l:pattern
 let @" = l:saved_reg
endfun

" 'Expandvar' expands the variable under the cursor
fun! <SID>Expandvar()
 let origreg = @"
 normal yiW
 if (@" == "@\"")
  let @" = origreg
 else
  let @" = eval(@")
 endif
 normal diW"0p
 let @" = origreg
endfun

" execute the bc calculator
fun! <SID>Bc(exp)
 setlocal paste
 normal mao
 exe ":.!echo 'scale=2; " . a:exp . "' | bc"
 normal 0i "bDdd`a"bp
 setlocal nopaste
endfun

fun! <SID>RFC(number)
 silent exe ":e http://www.ietf.org/rfc/rfc" . a:number . ".txt"
endfun

" The function Nr2Hex() returns the Hex string of a number.
func! Nr2Hex(nr)
 let n = a:nr
 let r = ""
 while n
  let r = '0123456789ABCDEF'[n % 16] . r
  let n = n / 16
 endwhile
 return r
endfunc

" The function String2Hex() converts each character in a string to a two
" character Hex string.
func! String2Hex(str)
 let out = ''
 let ix = 0
 while ix < strlen(a:str)
  let out = out . Nr2Hex(char2nr(a:str[ix]))
  let ix = ix + 1
 endwhile
 return out
endfunc

" translates hex value to the corresponding number
fun! Hex2Nr(hex)
 let r = 0
 let ix = strlen(a:hex) - 1
 while ix >= 0
  let val = 0
  if a:hex[ix] == '1'
   let val = 1
  elseif a:hex[ix] == '2'
   let val = 2
  elseif a:hex[ix] == '3'
   let val = 3
  elseif a:hex[ix] == '4'
   let val = 4
  elseif a:hex[ix] == '5'
   let val = 5
  elseif a:hex[ix] == '6'
   let val = 6
  elseif a:hex[ix] == '7'
   let val = 7
  elseif a:hex[ix] == '8'
   let val = 8
  elseif a:hex[ix] == '9'
   let val = 9
  elseif a:hex[ix] == 'a' || a:hex[ix] == 'A'
   let val = 10
  elseif a:hex[ix] == 'b' || a:hex[ix] == 'B'
   let val = 11
  elseif a:hex[ix] == 'c' || a:hex[ix] == 'C'
   let val = 12
  elseif a:hex[ix] == 'd' || a:hex[ix] == 'D'
   let val = 13
  elseif a:hex[ix] == 'e' || a:hex[ix] == 'E'
   let val = 14
  elseif a:hex[ix] == 'f' || a:hex[ix] == 'F'
   let val = 15
  endif
  let r = r + val * Power(16, strlen(a:hex) - ix - 1)
  let ix = ix - 1
 endwhile
 return r
endfun

" mathematical power function
fun! Power(base, exp)
 let r = 1
 let exp = a:exp
 while exp > 0
  let r = r * a:base
  let exp = exp - 1
 endwhile
 return r
endfun

" Captialize movent/selection
function! Capitalize(type, ...)
  let sel_save = &selection
  let &selection = "inclusive"
  let reg_save = @@

  if a:0  " Invoked from Visual mode, use '< and '> marks.
 silent exe "normal! `<" . a:type . "`>y"
  elseif a:type == 'line'
 silent exe "normal! '[V']y"
  elseif a:type == 'block'
 silent exe "normal! `[\<C-V>`]y"
  else
 silent exe "normal! `[v`]y"
  endif

  silent exe "normal! `[gu`]~`]"

  let &selection = sel_save
  let @@ = reg_save
endfunction

" Find file in current directory and edit it.
function! Find(...)
  let path="."
  if a:0==2
    let path=a:2
  endif
  let l:list=system("find ".path. " -name '".a:1."' | grep -v .svn ")
  let l:num=strlen(substitute(l:list, "[^\n]", "", "g"))
  if l:num < 1
    echo "'".a:1."' not found"
    return
  endif
  if l:num != 1
    let tmpfile = tempname()
    exe "redir! > " . tmpfile
    silent echon l:list
    redir END
    let old_efm = &efm
    set efm=%f

    if exists(":cgetfile")
        execute "silent! cgetfile " . tmpfile
    else
        execute "silent! cfile " . tmpfile
    endif

    let &efm = old_efm

    " Open the quickfix window below the current window
    botright copen

    call delete(tmpfile)
  endif
endfunction

""""""""""""""""""""""""""""""""""""""""""""""""""
" ---------- Plugin Settings ----------
"
""""""""""""""""""""""""""""""""""""""""""""""""""

" hide dotfiles by default - the gh mapping quickly changes this behavior
let g:netrw_list_hide = '\(^\|\s\s\)\zs\.\S\+'

" Do not go to active window.
"let g:bufExplorerFindActive = 0
" Don't show directories.
"let g:bufExplorerShowDirectories = 0
" Sort by full file path name.
"let g:bufExplorerSortBy = 'fullpath'
" Show relative paths.
"let g:bufExplorerShowRelativePath = 1

" don't allow autoinstalling of scripts
let g:GetLatestVimScripts_allowautoinstall = 0

" load manpage-plugin
runtime! ftplugin/man.vim

" load matchit-plugin
runtime! macros/matchit.vim

" minibuf explorer
"let g:miniBufExplModSelTarget = 1
"let g:miniBufExplorerMoreThanOne = 0
"let g:miniBufExplModSelTarget = 0
"let g:miniBufExplUseSingleClick = 1
"let g:miniBufExplMapWindowNavVim = 1
"let g:miniBufExplVSplit = 25
"let g:miniBufExplSplitBelow = 1
"let g:miniBufExplForceSyntaxEnable = 1
"let g:miniBufExplTabWrap = 1

" calendar plugin
" let g:calendar_weeknm = 4

" xml-ftplugin configuration
let xml_use_xhtml = 1

" :ToHTML
let html_number_lines = 1
let html_use_css = 1
let use_xhtml = 1

" LatexSuite
"let g:Tex_DefaultTargetFormat = 'pdf'
"let g:Tex_Diacritics = 1

" python-highlightings
let python_highlight_all = 1

" Eclim settings
"let org.eclim.user.name     = g:tskelUserName
"let org.eclim.user.email    = g:tskelUserEmail
"let g:EclimLogLevel         = 4 " info
"let g:EclimBrowser          = "x-www-browser"
"let g:EclimShowCurrentError = 1
" nnoremap <silent> <buffer> <tab> :call eclim#util#FillTemplate("${", "}")<CR>
" nnoremap <silent> <buffer> <leader>i :JavaImport<CR>
" nnoremap <silent> <buffer> <leader>d :JavaDocSearch -x declarations<CR>
" nnoremap <silent> <buffer> <CR> :JavaSearchContext<CR>
" nnoremap <silent> <buffer> <CR> :AntDoc<CR>

" quickfix notes plugin
map <Leader>n <Plug>QuickFixNote
nnoremap <F6> :QFNSave ~/.vimquickfix/
nnoremap <S-F6> :e ~/.vimquickfix/
nnoremap <F7> :cgetfile ~/.vimquickfix/
nnoremap <S-F7> :caddfile ~/.vimquickfix/
nnoremap <S-F8> :!rm ~/.vimquickfix/

" EnhancedCommentify updated keybindings
vmap <Leader><Space> <Plug>VisualTraditional
nmap <Leader><Space> <Plug>Traditional
let g:EnhCommentifyTraditionalMode = 'No'
let g:EnhCommentifyPretty = 'No'
let g:EnhCommentifyRespectIndent = 'Yes'

" FuzzyFinder keybinding
nnoremap <leader>fb :FufBuffer<CR>
nnoremap <leader>fd :FufDir<CR>
nnoremap <leader>fD :FufDir <C-r>=expand('%:~:.:h').'/'<CR><CR>
nmap <leader>Fd <leader>fD
nmap <leader>FD <leader>fD
nnoremap <leader>ff :FufFile<CR>
nnoremap <leader>fF :FufFile <C-r>=expand('%:~:.:h').'/'<CR><CR>
nmap <leader>FF <leader>fF
nnoremap <leader>ft :FufTextMate<CR>
nnoremap <leader>fr :FufRenewCache<CR>
"let g:FuzzyFinderOptions = {}
"let g:FuzzyFinderOptions = { 'Base':{}, 'Buffer':{}, 'File':{}, 'Dir':{},
   "\                      'MruFile':{}, 'MruCmd':{}, 'Bookmark':{},
   "\                      'Tag':{}, 'TaggedFile':{},
   "\                      'GivenFile':{}, 'GivenDir':{}, 'GivenCmd':{},
   "\                      'CallbackFile':{}, 'CallbackItem':{}, }
let g:fuf_onelinebuf_location  = 'botright'
let g:fuf_maxMenuWidth     = 300
let g:fuf_file_exclude     = '\v\~$|\.o$|\.exe$|\.bak$|\.swp$|((^|[/\\])\.[/\\]$)|\.pyo|\.pyc|autom4te\.cache|blib|_build|\.bzr|\.cdv|cover_db|CVS|_darcs|\~\.dep|\~\.dot|\.git|\.hg|\~\.nib|\.pc|\~\.plst|RCS|SCCS|_sgbak|\.svn'

" YankRing
nnoremap <silent> <F8> :YRShow<CR>
let g:yankring_history_file = '.yankring_history_file'
let g:yankring_replace_n_pkey = '<c-\>'
let g:yankring_replace_n_nkey = '<c-m>'

" supertab
let g:SuperTabDefaultCompletionType = "<c-n>"

" TagList
let Tlist_Show_One_File = 1

" UltiSnips
"let g:UltiSnipsJumpForwardTrigger = "<tab>"
"let g:UltiSnipsJumpBackwardTrigger = "<S-tab>"

" NERD Commenter
nmap <leader><space> <plug>NERDCommenterToggle
vmap <leader><space> <plug>NERDCommenterToggle
imap <C-c> <ESC>:call NERDComment(0, "insert")<CR>

" disable unused Mark mappings
nmap <leader>_r <plug>MarkRegex
vmap <leader>_r <plug>MarkRegex
nmap <leader>_n <plug>MarkClear
vmap <leader>_n <plug>MarkClear
nmap <leader>_* <plug>MarkSearchCurrentNext
nmap <leader>_# <plug>MarkSearchCurrentPrev
nmap <leader>_/ <plug>MarkSearchAnyNext
nmap <leader>_# <plug>MarkSearchAnyPrev
nmap <leader>__* <plug>MarkSearchNext
nmap <leader>__# <plug>MarkSearchPrev

" Nerd Tree explorer mapping
nmap <leader>e :NERDTree<CR>

" TaskList settings
let g:tlWindowPosition = 1

""""""""""""""""""""""""""""""""""""""""""""""""""
" ---------- Keymappings ----------
"
""""""""""""""""""""""""""""""""""""""""""""""""""

" edit/reload .vimrc-Configuration
nnoremap gce :e $HOME/.vimrc<CR>
nnoremap gcl :source $HOME/.vimrc<CR>:echo "Configuration reloaded"<CR>

" un/hightlight current line
nnoremap <silent> <Leader>H :match<CR>
nnoremap <silent> <Leader>h mk:exe 'match Search /<Bslash>%'.line(".").'l/'<CR>

" spellcheck off, german, englisch
nnoremap gsg :setlocal invspell spelllang=de<CR>
nnoremap gse :setlocal invspell spelllang=en<CR>

" switch to previous/next buffer
nnoremap <silent> <c-p> :bprevious<CR>
nnoremap <silent> <c-n> :bnext<CR>

" kill/delete trailing spaces and tabs
nnoremap <Leader>kt msHmt:silent! %s/[\t \x0d]\+$//g<CR>:let @/ = ""<CR>:echo "Deleted trailing spaces"<CR>'tzt`s
vnoremap <Leader>kt :s/[\t \x0d]\+$//g<CR>:let @/ = ""<CR>:echo "Deleted trailing, spaces"<CR>

" kill/reduce inner spaces and tabs to a single space/tab
nnoremap <Leader>ki msHmt:silent! %s/\([^\xa0\x0d\t ]\)[\xa0\x0d\t ]\+\([^\xa0\x0d\t ]\)/\1 \2/g<CR>:let @/ = ""<CR>:echo "Deleted inner spaces"<CR>'tzt`s
vnoremap <Leader>ki :s/\([^\xa0\x0d\t ]\)[\xa0\x0d\t ]\+\([^\xa0\x0d\t ]\)/\1 \2/g<CR>:let @/ = ""<CR>:echo "Deleted inner spaces"<CR>

" start new undo sequences when using certain commands in insert mode
inoremap <C-U> <C-G>u<C-U>
inoremap <C-W> <C-G>u<C-W>
inoremap <BS> <C-G>u<BS>
inoremap <C-H> <C-G>u<C-H>
inoremap <Del> <C-G>u<Del>

" swap two words
" http://www.vim.org/tips/tip.php?tip_id=329
nmap <silent> gw "_yiw:s/\(\%#[ÄÖÜäöüßa-zA-Z0-9]\+\)\(\_W\+\)\([ÄÖÜäöüßa-zA-Z0-9]\+\)/\3\2\1/<CR><C-o><C-l>:let @/ = ""<CR>
nmap <silent> gW "_yiW:s/\(\%#[ÄÖÜäöüßa-zA-Z0-9-+*_]\+\)\(\_W\+\)\([ÄÖÜäöüßa-zA-Z0-9-+*_]\+\)/\3\2\1/<CR><C-o><C-l>:let @/ = ""<CR>

" Capitalize movement
nnoremap <silent> gC :set opfunc=Capitalize<CR>g@
vnoremap <silent> gC :<C-U>call Capitalize(visualmode(), 1)<CR>

" delete search-register
nnoremap <silent> <leader>/ :let @/ = ""<CR>

" browse current buffer/selection in www-browser
nnoremap <Leader>b :!x-www-browser %:p<CR>:echo "WWW-Browser started"<CR>
vnoremap <Leader>b y:!x-www-browser <C-R>"<CR>:echo "WWW-Browser started"<CR>

" lookup/translate inner/selected word in dictionary
" recode is only needed for non-utf-8-text
" nnoremap <Leader>T mayiw`a:exe "!dict -P - -- $(echo " . @" . "\| recode latin1..utf-8)"<CR>
"nnoremap <Leader>t mayiw`a:exe "!dict -P - -- " . @"<CR>
" vnoremap <Leader>T may`a:exe "!dict -P - -- $(echo " . @" . "\| recode latin1..utf-8)"<CR>
"vnoremap <Leader>t may`a:exe "!dict -P - -- " . @"<CR>

" delete words in insert mode like expected - doesn't work properly at
" the end of the line
inoremap <C-BS> <C-w>

" Switch buffers
nnoremap <silent> [b :ls<Bar>let nr = input("Buffer: ")<Bar>if nr != ''<Bar>exe ":b " . nr<Bar>endif<CR>
" Search for the occurence of the word under the cursor
nnoremap <silent> [I [I:le
于 2009-10-28T20:04:17.540 回答