How To Vimrc
There is just one rule you must follow when crafting your own .vimrc.
Don't put any lines in your vimrc that you don't understand.
There are tons of tutorials such as this one on the internet that contain all kinds of awesome hacks to make your Vim better, but the absolute worst way to make your environment better is to just copy it wholesale from others.
Spending the time to actually learn what's going into the construction of your editor is invaluable. In the same way that copying notes off a projector by hand often leads to increased information retention, adding features one by one to your vimrc aids in overall Vim comprehension.
With that said, the rest of this article will be me explaining each and every line in my current vimrc in its entirety with the hope that you will find some tricks you haven't seen before. But! My vimrc is far from perfect. I'm always looking for additions that would make my environment better so if you think I missed something important please let me know: @dougblackio.
I will break it up into logical sections.
- Colors
- Spaces And Tabs
- UI Config
- Searching
- Folding
- Custom Movements
- Custom Leader
- CtrlP Settings
- Launch Config
- Tmux Config
- Autogroups
- Backups
- Custom Functions
- Organization
- Wrapping It Up
This article will almost certainly fall out of date with my vimrc in the very near future. You can find the most up to date version of it on github.
Colors
colorscheme badwolf " awesome colorscheme
Colors! Colorschemes are subjective, but I've currently settled on badwolf by Steve Losh. I found solarized incredibly complete, but a little too bland for my taste. I enjoy colors that pop. I also spend a good deal of time with molokai and still think it's a great scheme, but simply prefer badwolf at the moment.
Moving on:
syntax enable " enable syntax processing
The comment should be enough to describe this one. I'll take this moment to plug adding comments to most if not every line in your vimrc. If you're anything like me that file is going to get pretty long, and chances are you won't remember what every line does forever, so adding comments will help Future You know what the hell is going on in there.
Also, many settings in Vim have both a long name and a short name. For instance background
is the same as bg
. For future readability, I strongly recommend using the long name.
Spaces & Tabs
The incantations you must throw into your vimrc to get tabs/spaces working the way you want can be pretty confusing, so here's a quick refresher.
set tabstop=4 " number of visual spaces per TAB
tabstop
is the number of spaces a tab counts for. So, when Vim opens a file and reads a <TAB>
character, it uses that many spaces to visually show the <TAB>
.
set softtabstop=4 " number of spaces in tab when editing
softabstop
is the number of spaces a tab counts for when editing. So this value is the number of spaces that is inserted when you hit <TAB>
and also the number of spaces that are removed when you backspace.
set expandtab " tabs are spaces
expandtab
turns <TAB>s
into spaces. That's it. So <TAB>
just becomes a shortcut for "insert four spaces".
Taken together, these are great options for editing files in languages that prefer spaces over tabs, since this ensures no <TAB>s
are actually used. I spend most of my day in python and bash, where spaces are the norm. I like it, since it means my source code looks the same on every machine.
UI Config
These are options that change random visuals in Vim.
set number " show line numbers
Showing line numbers should need no justification.
set showcmd " show command in bottom bar
showcmd
shows the last command entered in the very bottom right of Vim. I have it set here but it's actually not shown in my Vim since I use powerline plugin (which we will get to later).
set cursorline " highlight current line
cursorline
draws a horizontal highlight (or underline, depending on your colorscheme) on the line your cursor is currently on. I've found that this makes it easier to follow exactly what line you left off on when you're switching back to a Vim session or switching between windows in Vim.
filetype indent on " load filetype-specific indent files
This both turns on filetype detection and allows loading of language specific indentation files based on that detection. For me, this means the python indentation file that lives at ~/.vim/indent/python.vim
gets loaded every time I open a *.py
file.
set wildmenu " visual autocomplete for command menu
This is a pretty cool feature I didn't know Vim had. You know how Vim automatically autocompletes things like filenames when you, for instance, run :e ~/.vim<TAB>
? Well it will provide a graphical menu of all the matches you can cycle through if you turn on wildmenu
.
set lazyredraw " redraw only when we need to.
Vim loves to redraw the screen during things it probably doesn't need to—like in the middle of macros. This tells Vim not to bother redrawing during these scenarios, leading to faster macros.
set showmatch " highlight matching [{()}]
With showmatch
, when your cursor moves over a parenthesis-like character, the matching one will be highlighted as well.
Searching
I love Vim's search. I love it even more with the following settings.
set incsearch " search as characters are entered set hlsearch " highlight matches
These should be pretty self explanatory. They make searching better.
" turn off search highlight nnoremap <leader><space> :nohlsearch<CR>
Vim will keep highlighted matches from searches until you either run a new one or manually stop highlighting the old search with :nohlsearch
. I find myself running this all the time so I've mapped it to ,<space>
.
Folding
Vim folding is a pretty sweet feature that I don't make heavy use of, but when I want it, I want it to have reasonable settings.
set foldenable " enable folding
Shows all folds.
set foldlevelstart=10 " open most folds by default
foldlevelstart
is the starting fold level for opening a new buffer. If it is set to 0, all folds will be closed. Setting it to 99 would guarantee folds are always open. So, setting it to 10 here ensures that only very nested blocks of code are folded when opening a buffer.
set foldnestmax=10 " 10 nested fold max
Folds can be nested. Setting a max on the number of folds guards against too many folds. If you need more than 10 fold levels you must be writing some Javascript burning in callback-hell and I feel very bad for you.
" space open/closes folds nnoremap <space> za
I change the mapping of <space>
pretty frequently, but this is its current command. za
opens/closes the fold around the current block. As an interesting aside, I've heard the z
character is used to represent folding in Vim because it looks like a folded piece of paper. Probably not, but it makes a nice story. :)
set foldmethod=indent " fold based on indent level
This tells Vim to fold based on indentation. This is especially useful for me since I spend my days in Python. Other acceptable values are marker
, manual
, expr
, syntax
, diff
. Run :help foldmethod
to find out what each of those do.
Movement
Here we start getting into custom bindings. This group of bindings all relate to movement commands.
" move vertically by visual line nnoremap j gj nnoremap k gk
These two allow us to move around lines visually. So if there's a very long line that gets visually wrapped to two lines, j
won't skip over the "fake" part of the visual line in favor of the next "real" line.
" move to beginning/end of line nnoremap B ^ nnoremap E $ " $/^ doesn't do anything nnoremap $ <nop> nnoremap ^ <nop>
These feel like my most controversial bindings, since they overwrite existing movement bindings. My thinking was that hitting ^
and $
to jump to the beginning and end of a line was a little too uncomfortable for such an oft-used movement. So I rebound E
and B
, which are typically used to move forwards and backwards over visual words to these purposes. Next I bound the old way to <nop>
to train myself to use the new ones.
" highlight last inserted text nnoremap gV `[v`]
This one is pretty cool. It visually selects the block of characters you added last time you were in INSERT
mode.
Leader Shortcuts
Here we've reached the meat of my custom keybindings. This section will introduce many different plugins and custom functions that I use pretty frequently. Let's get started.
let mapleader="," " leader is comma
\
is a little far away for a leader. I've found ,
to be a much better replacement.
" jk is escape inoremap jk <esc>
<ESC>
is very far away. jk
is a much better replacement as it's on the home row and I actually never type it when writing text. Except right now when I wrote this section of this post. Which I'm writing in Vim. The workaround if you ever need to enter this rare sequence of keys is to enter the j
, wait for the leader-check timeout to fade, and then enter the k
.
" toggle gundo nnoremap <leader>u :GundoToggle<CR>
In one of its cleverest innovations, Vim doesn't model undo as a simple stack. In Vim it's a tree. This makes sure you never lose an action in Vim, but also makes it much more difficult to traverse around that tree. gundo.vim fixes this by displaying that undo tree in graphical form. Get it and don't look back. Here I've mapped it to ,u
, which I like to think of as "super undo".
" edit vimrc/zshrc and load vimrc bindings nnoremap <leader>ev :vsp $MYVIMRC<CR> nnoremap <leader>ez :vsp ~/.zshrc<CR> nnoremap <leader>sv :source $MYVIMRC<CR>
These are shortcuts to edit and source my vimrc and my zshrc. That's it.
" save session nnoremap <leader>s :mksession<CR>
Ever wanted to save a given assortment of windows so that they're there next time you open up Vim? :mksession
does just that! After saving a Vim session, you can reopen it with vim -S
. Here I've mapped it to ,s
, which I remember by thinking of it as "super save".
" open ag.vim nnoremap <leader>a :Ag
The Silver Searcher is a fantastic command line tool to search source code in a project. It's wicked fast. The command line tool is named ag
(like the element silver). Thankfully there is a wonderful Vim plugin ag.vim which lets you use ag
without leaving Vim and pulls the results into a quickfix window for easily jumping to the matches. Here I've mapped it to ,a
.
CtrlP
ctrlp.vim is my life in Vim. If you've never used a fuzzy file searcher this will open your eyes. If you're currently using commandt.vim, you're on the right track, but CtrlP is the spiritual successor. It's can be (see below) significantly faster and more configurable than CommandT (Thanks Reddit!). Anyways here are my settings for CtrlP.
" CtrlP settings let g:ctrlp_match_window = 'bottom,order:ttb' let g:ctrlp_switch_buffer = 0 let g:ctrlp_working_path_mode = 0 let g:ctrlp_user_command = 'ag %s -l --nocolor --hidden -g ""'
There are a few things happening here. The first is I'm telling CtrlP to order matching files top to bottom with ttb
. Next, we tell CtrlP to always open files in new buffers with let ctrlp_switch_buffer=0
. Setting let g:ctrlp_working_path=0
lets us change the working directory during a Vim session and make CtrlP respect that change.
Now, let's talk about speed. CtrlP is entirely written in Vimscript, (which is pretty impressive) but CommandT has parts that are written in C. This means CommandT is, by default, faster than CtrlP. However, we can tell CtrlP to run an external command to find matching files. Now that we have ag
installed, we can use it with CtrlP to make CtrlP wicked fast.. We do that with the following.
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
If everything works out, you should see a noticeable improvement in the CtrlP speed. There are two caveats to this. Both g:ctrlp_show_hidden
and g:ctrlp_custom_ignore
do not work with custom user commands. I only care about the lack of support for custom ignores. Thankfully, ag
has it's own convention for ignore files: a .agignore
file that follows the same conventions as .gitignore
. This is actually great! We only need to define our directories to ignore when searching in one place.
Launch Config
These are options set at launch to configure external tools exactly once.
call pathogen#infect() " use pathogen call pathogen#runtime_append_all_bundles() " use pathogen
The pathogen
options extract all of the Vim plugins from their location in ~/.vim/bundles
to their respective places in the ~/.vim
folder.
Tmux
" allows cursor change in tmux mode if exists('$TMUX') let &t_SI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=1\x7\<Esc>\\" let &t_EI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=0\x7\<Esc>\\" else let &t_SI = "\<Esc>]50;CursorShape=1\x7" let &t_EI = "\<Esc>]50;CursorShape=0\x7" endif
These lines change the cursor from block cursor mode to vertical bar cursor mode when using tmux. Without these lines, tmux always uses block cursor mode.
Autogroups
augroup configgroup autocmd! autocmd VimEnter * highlight clear SignColumn autocmd BufWritePre *.php,*.py,*.js,*.txt,*.hs,*.java,*.md \:call <SID>StripTrailingWhitespaces() autocmd FileType java setlocal noexpandtab autocmd FileType java setlocal list autocmd FileType java setlocal listchars=tab:+\ ,eol:- autocmd FileType java setlocal formatprg=par\ -w80\ -T4 autocmd FileType php setlocal expandtab autocmd FileType php setlocal list autocmd FileType php setlocal listchars=tab:+\ ,eol:- autocmd FileType php setlocal formatprg=par\ -w80\ -T4 autocmd FileType ruby setlocal tabstop=2 autocmd FileType ruby setlocal shiftwidth=2 autocmd FileType ruby setlocal softtabstop=2 autocmd FileType ruby setlocal commentstring=#\ %s autocmd FileType python setlocal commentstring=#\ %s autocmd BufEnter *.cls setlocal filetype=java autocmd BufEnter *.zsh-theme setlocal filetype=zsh autocmd BufEnter Makefile setlocal noexpandtab autocmd BufEnter *.sh setlocal tabstop=2 autocmd BufEnter *.sh setlocal shiftwidth=2 autocmd BufEnter *.sh setlocal softtabstop=2 augroup END
This is a slew of commands that create language-specific settings for certain filetypes/file extensions. It is important to note they are wrapped in an augroup
as this ensures the autocmd
's are only applied once. In addition, the autocmd!
directive clears all the autocmd
's for the current group.
Backups
If you leave a Vim process open in which you've changed file, Vim creates a "backup" file. Then, when you open the file from a different Vim session, Vim knows to complain at you for trying to edit a file that is already being edited. The "backup" file is created by appending a ~
to the end of the file in the current directory. This can get quite annoying when browsing around a directory, so I applied the following settings to move backups to the /tmp
folder.
set backup set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp set backupskip=/tmp/*,/private/tmp/* set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp set writebackup
backup
and writebackup
enable backup support. As annoying as this can be, it is much better than losing tons of work in an edited-but-not-written file.
Custom Functions
I've written a small number of custom functions. Here they are with comments explaining their purpose.
" toggle between number and relativenumber function! ToggleNumber() if(&relativenumber == 1) set norelativenumber set number else set relativenumber endif endfunc " strips trailing whitespace at the end of files. this " is called on buffer write in the autogroup above. function! <SID>StripTrailingWhitespaces() " save last search & cursor position let _s=@/ let l = line(".") let c = col(".") %s/\s\+$//e let @/=_s call cursor(l, c) endfunction
Organization
Once your vimrc starts to fill up, organization becomes an issue. I've grouped this article by logical sections. Not surprisingly, it makes sense to group my actual vimrc by the exact same logical sections. Even cooler, Vim will let us fold all of those sections up by default. So when you open your Vimrc you have a high level view like this:
" Doug Black +-- 5 lines: " Colors ------------------------------------- +-- 5 lines: " Misc --------------------------------------- +-- 9 lines: " Spaces & Tabs ------------------------------ +-- 8 lines: " UI Layout ---------------------------------- +-- 5 lines: " Searching ---------------------------------- +-- 8 lines: " Folding ------------------------------------ +-- 9 lines: " Line Shortcuts ----------------------------- +-- 21 lines: " Leader Shortcuts --------------------------- +-- 7 lines: " Powerline ---------------------------------- +-- 6 lines: " CtrlP -------------------------------------- +-- 3 lines: " NERDTree ----------------------------------- +-- 4 lines: " Syntastic ---------------------------------- +-- 6 lines: " Launch Config ------------------------------ +-- 9 lines: " Tmux --------------------------------------- +-- 4 lines: " MacVim ------------------------------------- +-- 25 lines: " AutoGroups --------------------------------- +-- 7 lines: " Backups ------------------------------------ +-- 50 lines: " Custom Functions ---------------------------
Here's how we make that happen. First, we tell vim to fold sections by markers, rather than indentation. That looks like this
foldmethod=marker
Then we want it to close every fold by default so that we have this high level view when we open our vimrc.
foldlevel=0
Now, this is a file-specific setting, so we can use a modeline
to make Vim only use these settings for this file. Modelines are special comments somewhere in a file that can can declare certain Vim settings to be used only for that file. So we'll tell Vim to check just the final line of the file for a modeline.
set modelines=1
Next, we'll add our modeline to the bottom of the file.
" vim:foldmethod=marker:foldlevel=0
Finally, we need to visually wrap each section in the fold marker. The fold markers are {{{
and }}}
.That looks like this.
" Section Name {{{ set number "This will be folded " }}}
That's it. I find this a great way to keep your vimrc highly structured, easy to navigate, and incredibly readable.
Wrapping It Up
I hope this helped you. The reality is that this was a ton of stuff and I still stand by this platitude:
Don't put anything in your .vimrc you don't understand!
So, if you grab lines from this, make sure you add comments explaining exactly what is going on. If you can't, :help [setting]
is your best friend.
Thanks for reading! Don't forget to send me your .vimrc tips at @dougblackio.
原文:http://dougblack.io/words/a-good-vimrc.html
本文转自:Vimrc设置教程:A Good Vimrc (英文)
相关推荐
`.vimrc` 是一个启动时会被 Vim 加载的个人配置文件,它允许用户自定义各种设置,如缩进、颜色、自动对齐以及保存编辑历史等功能。下面将详细介绍这些配置命令的作用和用法。 首先,`.vimrc` 文件的位置因系统和...
Vim 是一款强大的文本编辑器,它允许用户通过自定义配置文件 `vimrc` 来个性化设置编辑器的行为。在 `vimrc-old: Vim 设置` 的主题中,我们将深入探讨如何利用 Vimscript 来定制你的 Vim 环境,使编辑体验更加高效和...
Vimrc文件是Vim编辑器的初始化脚本,它定义了Vim启动时的默认设置、快捷键映射以及插件配置。这个特定的vimrc配置是作者为了高效地进行Go语言开发而定制的。 首先,我们来看看Vimscript,它是Vim编辑器使用的内置...
从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的vimrc设置从网络上收集的...
.vimrc的设置 强大的vim配置文件, 在终端下使用vim进行编辑时,默认情况下, 编辑的界面上是没有显示行号、语法高亮度显示、智能缩进等功能的。 为了更好的在vim下进行工作,需要手动设置一个配置文件:.vimrc。 ...
现在,要永久保留某些Vim设置,请安装此插件,并将名为.obsidian.vimrc的文件.obsidian.vimrc保管库根目录。 如果您使用多个保管库,则每个保管库都需要此文件。 这是我正在使用的简单实用的.obsidian.vimrc : " ...
《我的vimrc常用设置》 vimrc文件是Vim编辑器的配置文件,它定义了用户自定义的快捷键、行为设置以及各种偏好。通过定制vimrc,我们可以使Vim更加符合个人的工作习惯,提高编程效率。下面将详细介绍标题和描述中...
【vimrc-survey】是一个项目,它通过分析GitHub上的.dotvimrc或.vimrc文件来探索最常用的Vim配置行。这个项目利用Python语言作为工具,进行数据抓取和分析,帮助用户了解社区中广泛使用的Vim编辑器个性化设置。 ...
【描述】中提到的"简单的vimrc配置"意味着这是一个简洁而有效的设置,专门针对C++编程竞赛的场景。Vimrc是Vim编辑器的配置文件,用户可以在此自定义各种快捷键、设置和行为。在这个配置中,作者追求的是在不增加复杂...
通过Web应用程序轻松构建vimrc为什么构建vimrc文件应该并不困难。 毕竟,您要配置的代码编辑器是1991年发明的。 没关系,您的经验水平是不变的,总有新的方法可以改变vim的经验,但是由于提示分散在Internet上,因此...
**vimrc配置:重塑你的vim体验** 在程序员和文本编辑器爱好者的世界里,vim是一款备受推崇的工具。它以其高效、可高度定制化的特性赢得了众多粉丝。`vimrc`文件是vim配置的核心,通过定制这个文件,用户可以根据...
要使用此存储库的设置,请执行以下步骤: 将此存储库克隆到最合适的位置 打开终端并导航到存储库文件夹 通过运行ln -s $PWD/.vimrc ~/创建从.vimrc文件到您的家的符号链接。 通过运行ln -s $PWD/.vimrc.bundles ~...
### vimrc(含各种插件设置) #### 描述: 这份 `.vimrc` 文件为 Vim 用户提供了丰富的配置选项,尤其侧重于 C/C++ 编程的支持。它包含了多种插件设置,用户可以根据自己的需求进行选择性地安装和配置。所有的插件都...
例如如果你使用 vim-plug,那么写: Plug 'sheerun/vimrc'我建议使用: 将您的领导者设置为太空作为轻量级插件管理器语法高亮一个简单的.vimrc文件示例: " Select your Leader keylet mapleader = " \< Space> ...
导入的方法通常是将文件内容复制到自己的`vimrc`文件中,或者在Vim中运行`:source vimyy`命令来加载新的设置。 通过理解和个性化`vimrc`,用户不仅可以提高编程效率,还能享受更加舒适和个性化的编程环境,这是Vim...
Vimrc文件是Vim编辑器的配置文件,用于存储用户个人的设置和快捷键映射,使得Vim能够按照用户的需求进行定制化。在本文中,我们将深入探讨`vimrc`设置,了解如何优化和个性化你的Vim体验。 首先,让我们了解一下`...
`vimrc`文件位于用户的主目录下,通常为`~/.vimrc`(在Unix/Linux系统中)或`$HOME/_vimrc`(在Windows系统中)。这个文件包含了启动Vim时会执行的命令,用于设置快捷键、颜色、行为等。例如,以下是一些常见的`...
1. **Vim 插件管理**:Amix 的配置可能包含了像 Vundle 或 Pathogen 这样的插件管理系统,它们允许用户方便地安装、更新和管理 Vim 插件。通过这些系统,你可以轻松地添加或删除对你工作有益的工具。 2. **常用插件...
4. **快捷键**:可以自定义按键映射,例如`map <F5> :w<CR>`将F5键设置为保存文件,`nnoremap <C-S-A> ggVGy`将Ctrl+Shift+A设置为全选并复制当前文件内容。 5. **插件管理**:若使用Vundle或Pathogen等插件管理...
### .vimrc配置文件解析与应用 在深入探讨`.vimrc`配置文件的各个部分之前,我们先简要介绍`.vimrc`的意义及其在Linux环境中的作用。`.vimrc`是Vim编辑器的配置文件,它允许用户自定义Vim的行为,包括编辑习惯、...