MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
Мой ~/.vimrc
является довольно стандартным (главным образом $VIMRUNTIME/vimrc_example.vim
), но я использую мой ~/.vim
каталог экстенсивно с пользовательскими сценариями в ~/.vim/ftplugin
и ~/.vim/syntax
.
Я поместил свой .vimrc в http://dotfiles.org/~petdance/.vimrc , и я имею некоторые другие файлы по dotfiles.org, также .
Вероятно, старшими значащими вещами ниже является выбор шрифта и цветовые схемы. Да, я потратил слишком долго приятно игру с теми вещами.:)
"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
Я создал свой собственный синтаксис для моего, чтобы сделать или документы контрольного списка, который выделяет вещи как
-> делают это (полужирным)
!-> делают это теперь (в оранжевом)
++> выполнение этого в процессе (в зеленом)
=> это сделано (в сером)
У меня есть документ в./syntax/как fc_comdoc.vim
в vimrc для установки этого синтаксиса для чего-либо с моим пользовательским расширением .txtcd или .txtap
au BufNewFile,BufRead *.txtap,*.txtcd setf fc_comdoc
Номера строки и подсветка синтаксиса.
set number
syntax on
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
Не так много.
Я показываю содержимое сгиба и группы синтаксиса при наведении мыши:
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
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!
Только что увидел это:
:nnoremap <esc> :noh<return><esc>
Я нашел это в блоге ViEmu , и мне это очень интересно. Краткое объяснение - это заставляет Esc отключать выделение при поиске в обычном режиме.
Полезный материал для использования C / C ++ и svn (можно легко изменить для git / hg / что угодно). Я установил их на свои 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
Все результаты многих лет моего вмешательства в vim приведены здесь .
Я обычно разбиваю свой .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
Многое из этого взято из вики кстати.
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>
http://github.com/elventails/vim/blob/master/vimrc
Есть дополнения для CakePHP / PHP / Git
наслаждайтесь!
Добавлю приятные опции вы, ребята, используете его и обновляете репо;
Ура,
Almost everything is here. It is mainly programming oriented, in C++ in particular.
Это мой скромный .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 = "(:),[:],{:}"
In addition to my vimrc I have a bigger collection of plugins. Everything is stored in a git repository at http://github.com/jceb/vimrc.
" 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
: map + v% zf # hit " + ", чтобы свернуть функцию / зациклить что-либо в парантезисе.
: set expandtab # табуляция будет расширена как пробелы в соответствии с настройкой ts (tabspace)
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
Мои .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:
Часть супер денег из моего .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
Клавиши возврата, возврата, пробела и дефиса не привязаны к чему-либо полезному, поэтому я сопоставляю их для более удобной навигации по документу:
" Page down, page up, scroll down, scroll up
noremap <Space> <C-f>
noremap - <C-b>
noremap <Backspace> <C-y>
noremap <Return> <C-e>
Здесь являются моими. Они развивались в течение многих лет, и они работают одинаково хорошо в Linux/Windows/OSX (в прошлый раз, когда я проверил):
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
Я не могу жить без завершения 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
Я сделал функцию, которая автоматически отправляет ваш текст на личный пастбин.
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>
Моя любимая часть моего .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] поместит содержимое последней строки в указанный регистр и вернется в отмеченное вами место. Упрощает редактирование макроса или копирование и настройку одного макроса в новый регистр.
Мой .vimrc , плагины, которые я использую, и другие настройки настроены так, чтобы помочь мне с задачами, которые я выполняю чаще всего:
У меня есть дополнительная информация о моей конфигурации Vim здесь
Некоторые из моих любимых настроек, которые я не нашел слишком распространенными:
" 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
У меня есть это в моем ~ / .vim / after / syntax / vim.vim
файле:
Что он делает:
Т.е., если вы идете:
highlight JakeRedKeywords cterm=bold term=bold ctermbg=black ctermfg=Red
Слово красный будет красным, а слово черный будет черным.
Вот код:
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