Difference between revisions of "Vim"

From ArchWiki
Jump to: navigation, search
m (Configuration: defaults.vim is already mentioned below, let's mention it here as well)
 
(224 intermediate revisions by 60 users not shown)
Line 1: Line 1:
 
[[Category:Development]]
 
[[Category:Development]]
 
[[Category:Text editors]]
 
[[Category:Text editors]]
{{i18n|Vim}}
+
[[de:Vim]]
{{Article summary start}}
+
[[es:Vim]]
{{Article summary text|A basic tutorial, and tips to setup the console/terminal text editor.}}
+
[[it:Vim]]
{{Article summary end}}
+
[[ja:Vim]]
 +
[[lt:Vim]]
 +
[[ru:Vim]]
 +
[[zh-CN:Vim]]
 +
[[zh-TW:Vim]]
 +
{{Related articles start}}
 +
{{Related|List of applications/Documents#Vi text editors}}
 +
{{Related articles end}}
  
''"[http://www.vim.org/about.php Vim] is an advanced text editor that seeks to provide the power of the de-facto UNIX editor ‘vi’, with a more complete feature set."'' Vim is not a simple text editor like nano or pico. It does require some time to learn, and a great amount of time to master.
+
[[Wikipedia:Vim (text editor)|Vim]] is a terminal text editor. It is an extended version of [[Wikipedia:vi|vi]] with additional features, including syntax highlighting, a comprehensive help system, native scripting (vimscript), a visual mode for text selection, and comparison of files (vimdiff).
 
+
Vim is designed to make your fingers work as little as possible, and you should never have to use the mouse. This may seem odd, but once you master Vim, you will begin to understand the reasoning.
+
 
+
== Features ==
+
 
+
* Vim is very powerful for advanced editing tasks
+
* Extensible configuration options
+
* Simple, robust keybindings
+
* Syntax highlighting
+
  
 
== Installation ==
 
== Installation ==
  
[[pacman|Install]] the command line version with the {{Pkg|vim}} package, or you can install the GUI version (which also provides {{ic|vim}}) by installing the {{Pkg|gvim}} package.
+
[[Install]] one of the following packages:
  
{{Note|{{Pkg|vim}} is no longer compiled with X server options.  For many users, this will mean that standard copy and paste functionality from the X server clipboard will fail to work. If this is a common task for you, consider installing {{Pkg|gvim}} which includes a version of Vim with this support. See {{Bug|14609}} for more information.}}
+
* {{Pkg|vim}} with Python 2/3, Lua, Ruby and Perl interpreters support but without GTK/X support.
 +
* {{Pkg|gvim}} which also provides the same as the above {{ic|vim}} package with GTK/X support.
  
{{Note|The vim package is meant to be as lightweight as possible, hence it does not support Python, Lua, and Ruby interpreters. If you require their support, choose the gvim package, which includes the vim binary. The {{ic|herecura-stable}} unofficial repository provides a couple different vim / gvim variants:
+
{{Note|
{{hc|$ pacman -Slq herecura-stable | grep vim|
+
* The {{Pkg|vim}} package is built without [[Xorg]] support; specifically the {{ic|+clipboard}} feature is missing, so Vim will not be able to operate with the ''primary'' and ''clipboard'' [[Clipboard|selection buffers]]. The {{Pkg|gvim}} package provides also the CLI version of Vim with the {{ic|+clipboard}} feature.
vim-cli
+
* The unofficial repository [[Unofficial user repositories#herecura|herecura]] also provides a number of Vim/gVim variants: {{ic|vim-cli}}, {{ic|vim-gvim-common}}, {{ic|vim-gvim-gtk}}, {{ic|vim-gvim-qt}}, {{ic|vim-rt}} and {{ic|vim-tiny}}.
vim-gvim-gtk
+
vim-gvim-motif
+
vim-gvim-qt
+
vim-gvim-x11
+
vim-rt
+
vim-tiny
+
}}
+
 
}}
 
}}
  
==Usage==
+
== Usage ==
  
This is a basic overview on how to use vim.  Alternately, you could use {{Ic|vimtutor}} to further familiarize yourself. Vim has four different modes:
+
For a basic overview on how to use Vim, follow the vim tutorial by running either ''vimtutor'' (for the terminal version) or ''gvimtutor'' (for the graphical version).
  
* Command mode: keystrokes are interpreted as commands.
+
Vim includes a broad help system that can be accessed with the {{ic|:h ''subject''}} command. Subjects include commands, configuration options, key bindings, plugins etc. Use the {{ic|:h}} command (without any subject) for information about the help system and jumping between subjects.
* Insert mode: keystrokes are entered into the file.
+
* Visual mode: keystrokes select, cut, or copy text
+
* Ex mode: input mode for additional commands (e.g. saving a file, replacing text...)
+
  
===Basic Editing===
+
== Configuration ==
  
If you start vim with:
+
Vim's user-specific configuration file is located in the home directory: {{ic|~/.vimrc}}, and Vim files of current user are located inside {{ic|~/.vim/}}. The global configuration file is located at {{ic|/etc/vimrc}}. Global Vim files are located inside {{ic|/usr/share/vim/}}.
  
$ vim somefile.txt
+
{{Note|Commonly expected behavior such as syntax highlighting is enabled in {{ic|defaults.vim}}, which is loaded when no {{ic|~/.vimrc}} is present. Add {{ic|1=let skip_defaults_vim=1}} to {{ic|/etc/vimrc}} to disable loading of {{ic|defaults.vim}} completely. [https://github.com/vim/vim/issues/1033]}}
  
you will see a blank document (providing that somefile.txt does not exist. If it does, you will see what is in there). You will not be able to edit right away – you are in Command Mode. In this mode you are able to issue commands to vim with the keyboard.
+
=== Syntax highlighting ===
  
{{Note|Vim is an example of classic Unix-style ware. This means that it is not flashy, and it will not hold your hand. It does not come with built-in paperclips and games. It will allow you to get the job done however, and quickly too. Also, all commands are case sensitive. Sometimes the uppercase versions are “blunter” versions ({{keypress|s}} will replace a character, {{keypress|S}} will replace a line), other times they are completely different commands ({{keypress|j}} will move down, {{keypress|J}} will join two lines).}}
+
To enable syntax highlighting (Vim supports a huge list of programming languages):
  
You insert text (stick it before the cursor) with the {{keypress|i}} command. {{keypress|I}} (uppercase '''i''') inserts text at the beginning of the line. You append text (place text after the cursor, what most people expect) with {{keypress|a}}. Typing {{keypress|A}} will place the cursor at the end of the line.
+
:filetype plugin on
 +
:syntax on
  
Return to command mode at any time by pressing {{keypress|Esc}}.
+
=== Visual wrapping ===
  
===Moving Around===
+
The {{ic|wrap}} option is on by default, which instructs Vim to wrap lines longer than the width of the window, so that the rest of the line is displayed on the next line. The {{ic|wrap}} option only affects how text is displayed, the text itself is not modified.
  
In vim, you can move the cursor with the arrow keys, but this isn't the '''vim way'''. You’d have to move your right hand all the way from the standard typing position all the way to the arrow keys, and then back. Not fun.
+
The wrapping normally occurs after the last character that fits the window, even when it is in the middle of a word. More intelligent wrapping can be controlled with the {{ic|linebreak}} option. When it is enabled with {{ic|set linebreak}}, the wrapping occurs after characters listed in the {{ic|breakat}} string option, which by default contains a space and some punctuation marks (see {{ic|:help breakat}}).
  
In vim you can move down by pressing {{keypress|j}}. You can remember this because the “j” hangs down. You move the cursor back up by pressing {{keypress|k}}. Left is {{keypress|h}} (it's left of the “j”), and right is {{keypress|l}} (lowercase '''L''').
+
Wrapped lines are normally displayed at the beginning of the next line, regardless of any indentation. The [https://retracile.net/wiki/VimBreakIndent breakindent] option instructs Vim to take indentation into account when wrapping long lines, so that the wrapped lines keep the same indentation of the previously displayed line. The behaviour of {{ic|breakindent}} can be fine-tuned with the {{ic|breakindentopt}} option, for example to shift the wrapped line another four spaces to the right for Python files (see {{ic|:help breakindentopt}} for details):
  
{{keypress|^}} will put the cursor at the beginning of the line, and {{keypress|$}} will place it at the end.
+
autocmd FileType python set breakindentopt=shift:4
  
{{Note|{{keypress|^}} and {{keypress|$}} are commonly used in regular expressions to match the beginning and ending of the line. Regular expressions are very powerful and are commonly used in *nix environment, so maybe it is a little bit tricky now, but later you will notice “the idea” behind the use of most of these key mappings.}}
+
=== Using the mouse ===
  
To advance a word, press the {{keypress|w}} key. {{keypress|W}} will include more characters in what it thinks is a word (e.g. underscores and dashes as a part of a word). To go back a word, {{keypress|b}} is used. Once again, {{keypress|B}} will include more characters in what vim considers a word. To advance to the end of a word, use {{keypress|e}}, {{keypress|E}} includes more characters.
+
Vim has the ability to make use of the mouse, but it only works for certain terminals: on Linux it is [[xterm]]-based terminals and Linux console with {{Pkg|gpm}} (see [[Console mouse support]] for details), and also PuTTY.
  
To advance to the beginning of a sentence, {{keypress|(}} will get the job done. {{keypress|)}} will do the opposite, moving to the end of a sentence. For an even bigger jump, {{keypress|{}} will move the the beginning a whole paragraph. {{keypress|<nowiki>}</nowiki>}} will advance to the end of a whole paragraph.
+
To enable this feature, add this line into {{ic|~/.vimrc}}:
  
To advance to the header (top) of the screen, {{keypress|H}} will get the job done. {{keypress|M}} will advance to the middle of the screen, and {{keypress|L}} will advance to the last (bottom). {{keypress|gg}} will go to the beginning of the file, {{keypress|G}} will go to the end of the file. {{keypress|Ctrl+D}} will let you scroll page by page.
+
  set mouse=a
  
===Repeating commands===
+
The {{ic|1=mouse=a}} option is set in {{ic|defaults.vim}}, which is sourced if there is no {{ic|~/.vimrc}}.
  
If a command is prefixed by a number, then that command will be executed that number of times over (there are exceptions, but they still make sense, like the {{keypress|s}} command). For example, pressing {{keypress|3i}} then “Help! ” then {{keypress|Esc}} will print “Help! Help! Help!“. Pressing {{keypress|<nowiki>2}</nowiki>}} will advance you two paragraphs. This comes in handy with the next few commands…
+
{{Note|When enabling the mouse in a terminal, copy/paste will use the {{ic|"*}} register if there is access to an X server. The xterm handling of the mouse buttons can still be used by keeping the shift key pressed. Also see the {{ic|clipboard}} option.}}
  
===Deleting===
+
=== Traverse line breaks with arrow keys ===
  
The {{keypress|x}} command will delete the character under the cursor. {{keypress|X}} will delete the character before the cursor. This is where those number functions get fun. {{keypress|6x}} will delete 6 characters. Pressing {{keypress|.}} (dot) will repeat the previous command. So, lets say you have the word "foobar" in a few places, but after thinking about it, you’d like to see just “foo”. Move the cursor under the "b", hit {{keypress|3x}}, move to the next "foobar" and hit {{keypress|.}} (dot).
+
By default, pressing {{ic|}} at the beginning of a line, or pressing {{ic|}} at the end of a line, will not let the cursor traverse to the previous, or following, line.
  
The {{keypress|d}} will tell vim that you want to delete something. After pressing {{keypress|d}}, you need to tell vim what to delete. Here you can use the movement commands. {{keypress|dW}} will delete up to the next word. {{keypress|d^}} will delete up unto the beginning of the line. Prefacing the delete command with a number works well too: {{keypress|3dW}} will delete the next three words. {{keypress|D}} (uppercase) is a shortcut to delete until the end of the line (basically {{keypress|d$}}). Pressing {{keypress|dd}} will delete the whole line.
+
The default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file.
  
To delete then replace the current word, place the cursor on the word and execute the command {{keypress|cw}}. This will delete the word and change to insert mode. To replace only a single letter use {{keypress|r}}.
+
== Merging files ==
  
===Undo and Redo===
+
Vim includes a diff editor (a program that shows differences between two or more files and aids to conveniently merge them). Use ''vimdiff'' to run the diff editor — just specify some couple of files to it: {{ic|vimdiff ''file1'' ''file2''}}. Here is the list of ''vimdiff''-specific commands.
  
vim has a built-in clipboard (also known as a buffer). Actions can be undone with {{keypress|u}} and redone with {{keypress|Ctrl+r}}.
+
{| class="wikitable"
 +
! Action          !! Shortcut
 +
|-
 +
| next change    || {{ic|]c}}
 +
|-
 +
| previous change || {{ic|[c}}
 +
|-
 +
| diff obtain    || {{ic|do}}
 +
|-
 +
| diff put        || {{ic|dp}}
 +
|-
 +
| fold open      || {{ic|zo}}
 +
|-
 +
| fold close      || {{ic|zc}}
 +
|-
 +
| rescan files    || {{ic|:diffupdate}}
 +
|-
 +
| switch windows  || {{ic|Ctrl+w+w}}
 +
|}
  
===Visual Mode===
+
== Tips and tricks ==
  
Pressing {{keypress|v}} will put you in visual mode . Here you can move around to select text, when you’re done, you press {{keypress|y}} to yank the text into the buffer (copy), or you may use {{keypress|c}} to cut.  {{keypress|p}} pastes after the cursor, {{keypress|P}} pastes before.  {{keypress|V}}, Visual Line mode, is the same for entire lines. {{keypress|Ctrl+v}} is for blocks of text.
+
=== Line numbers ===
  
{{Note|Whenever you delete something, that something is placed inside a buffer and is available for pasting.}}
+
To show the line number column, use {{ic|:set number}}. By default absolute line numbers are shown, relative numbers can be enabled with {{ic|:set relativenumber}}.
  
===Search and Replace===
+
Jumping to a specific line is possible with {{ic|:''line number''}} or {{ic|''line number''gg}}. Jumps are remembered in a jump list, see {{ic|:h jump-motions}} for details.
  
To search for a word or character in the file, simply use {{keypress|/}} and then the characters your are searching for and press enter.  To view the next match in the search press {{keypress|n}}.
+
=== Spell checking ===
  
To search and replace use the substitute {{keypress|:s/}} command. The syntax is: {{Ic|[range]s///[arguments]}}. For example:
+
Vim has the ability to do spell checking, enable by entering:
  
{{bc|
+
  set spell
Command        Outcome
+
:s/xxx/yyy/    Replace xxx with yyy at the first occurence
+
:s/xxx/yyy/g  Replace xxx with yyy first occurrence, global (whole sentence)
+
:s/xxx/yyy/gc Replace xxx with yyy global with confirm
+
:%s/xxx/yyy/g  Replace xxx with yyy global in the whole file
+
}}
+
  
You can use the global {{keypress|:g/}} command to search for patterns and then execute a command for each match. The syntax is: {{Ic|[range]:g//[cmd]}}.
+
By default, only English language dictionaries are installed. More dictionaries can be found in the [[official repositories]] by searching for {{ic|vim-spell}}. Additional dictionaries can be found in the [http://ftp.vim.org/vim/runtime/spell/ Vim's FTP archive]. Additional dictionaries can be put in the folder {{ic|~/.vim/spell/}} and enabled with the command: {{ic|1=:setlocal spell spelllang=''en_us''}} (replacing the {{ic|''en_us''}} with the name of the needed dictionary).
  
{{bc|
+
{| class="wikitable"
Command  Outcome
+
! Action                      !! Shortcut
:g/^#/d  Delete all lines that begins with #
+
|-
:g/^$/d  Delete all lines that are empty
+
| next spelling              || {{ic|]s}}
}}
+
|-
 +
| previous spelling          || {{ic|[s}}
 +
|-
 +
| spelling suggestions        || {{ic|1=z=}}
 +
|-
 +
| spelling good, add          || {{ic|zg}}
 +
|-
 +
| spelling good, session      || {{ic|zG}}
 +
|-
 +
| spelling wrong, add        || {{ic|zw}}
 +
|-
 +
| spelling wrong, session    || {{ic|zW}}
 +
|-
 +
| spelling repeat all in file || {{ic|:spellr}}
 +
|}
  
===Saving and Quitting===
+
{{Tip|
 +
* To enable spelling in two languages (for instance English and German), add {{ic|1=set spelllang=''en,de''}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim.
 +
* You can enable spell checking for arbitrary file types (e.g. ''.txt'') by using the FileType plugin and a custom rule for file type detection. To enable spell checking for any file ending with ''.txt'', create the file {{ic|/usr/share/vim/vimfiles/ftdetect/plaintext.vim}}, and insert the line {{ic|autocmd BufRead,BufNewFile *.txt setfiletype plaintext}} into that file. Next, insert the line {{ic|1=autocmd FileType plaintext setlocal spell spelllang=''en_us''}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim.
 +
* To enable spell checking for LaTeX (or TeX) documents only, add {{ic|1=autocmd FileType '''tex''' setlocal spell spelllang=''en_us''}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim.}}
  
To save and/or quit, you will need to use Ex mode.  Ex mode commands are preceded by a {{keypress|:}}.  To write a file use {{keypress|:w}} or if the file doesn’t have a name {{ic|''':w''' filename}}. Quitting is done with {{keypress|:q}}. If you choose not to save your changes, use {{keypress|:q!}}. To save and quit {{keypress|:x}}.
+
=== Save cursor position ===
  
=== Additional Commands ===
+
If you want the cursor to [http://vim.wikia.com/wiki/Restore_cursor_to_file_position_in_previous_editing_session appear in its previous position] after you open a file, add the following to your {{ic|~/.vimrc}}:
  
# Pressing {{keypress|s}} will erase the current letter under the cursor, and place you in insert mode. {{keypress|S}} will erase the whole line, and place you in insert mode.
+
augroup resCur
# {{keypress|o}} will create a newline below the line and put you insert mode, {{keypress|O}} will create a newline above the line and put you in insert mode.
+
  autocmd!
# {{keypress|yy}} will yank an entire line
+
  autocmd BufReadPost * call setpos(".", getpos("'\""))
# {{keypress|cc}} will delete the current line and place you in insert mode.
+
augroup END
# {{keypress|*}} will highlight the current word and {{keypress|n}} will search it
+
  
==Configuration==
+
=== Replace vi command with Vim ===
  
Vim's personal configuration file is located in the home directory: {{ic|~/.vimrc}}. Advanced users tend to keep a well-tailored {{ic|~/.vimrc}}.  The global configuration file is located at {{ic|/etc/vimrc}}. The fall-back {{Ic|$VIM}} variable is defined as {{ic|/usr/share/vim/}}. For example, to create a global colorscheme the {{ic|*.vim}} colorscheme file should be stored in {{ic|/usr/share/vim/vimfiles/}}.
+
Create an [[alias]] for {{ic|vi}} to {{ic|vim}}.
  
Currently, the vim global configuration in Arch Linux is very basic and differs from many other distributions' default vim configuration file.  To get some commonly expected behaviors (like syntax highlighting, return to the line of the last edit...), consider using vim's example configuration file:
+
Alternatively, if you want to be able to type {{ic|sudo vi}} and get {{ic|vim}}, install {{AUR|vi-vim-symlink}} which will remove {{ic|vi}} and replace it with a symlink to {{ic|vim}}.
  
cp /etc/vimrc /etc/vimrc.bak
+
=== DOS/Windows carriage returns ===
cp /usr/share/vim/vim73/vimrc_example.vim /etc/vimrc
+
  
===Backup Files===
+
If there is a {{ic|^M}} at the end of each line then this means you are editing a text file which was created in MS-DOS or Windows. This is because in Linux only a single line feed character (LF) used for line break, but in Windows/MS DOS systems they are using a sequence of a carriage return (CR) and a line feed (LF) for the same. And this carriage returns are displayed as {{ic|^M}}.
  
Vim by default creates a backup of an edited file in the same directory as the file called {{ic|filename~}}. To prevent clutter, many users tell vim to use a backup directory:
+
To remove all carriage returns from a file do:
  
  set backupdir=~/.vim/backup,/tmp
+
  :%s/^M//g
  
Or, it's possible to even disable this behavior:
+
Note that there {{ic|^}} is a control letter. To enter the control sequence {{ic|^M}} press {{ic|Ctrl+v,Ctrl+m}}.
  
set nobackup
+
Alternatively install the package {{pkg|dos2unix}} and run {{ic|dos2unix ''file''}} to fix the file.
set nowritebackup
+
set noswapfile    ! (additionally disable swap files)
+
  
===Wrap Searches===
+
{{Note| Another simple way is by changing {{ic|fileformat}} setting. {{ic|<nowiki>set ff=unix</nowiki>}} to convert files with DOS/Windows line ending to Unix line ending. To do the reverse, just issue {{ic|<nowiki>set ff=dos</nowiki>}} to convert files with Unix line ending to DOS/Windows line ending. }}
  
With this option the ''search next'' behaviour allows to jump to the beginning of the file, when the end of file is reached. Similarly, ''search previous'' jumps to the end of the file when the start is reached.
+
=== Empty space at the bottom of gVim windows ===
  
set wrapscan
+
When using a [[window manager]] configured to ignore window size hints, gVim will fill the non-functional area with the GTK theme background color.
  
=== Spell Checking ===
+
The solution is to adjust how much space gVim reserves at the bottom of the window. Put the following line in {{ic|~/.vimrc}}:
  
  set spell
+
  set guiheadroom=0
  
With this setting, Vim will highlight incorrectly spelled words. Place the cursor on a misspelled word and enter {{keypress|1=z=}} to view spelling suggestions.
+
{{Note|If you set it to zero, you will not be able to see the bottom horizontal scrollbar.}}
  
Only English language dictionaries are installed by default, more can be found in the [[Official Repositories|official repositories]]. To get the list of available languages type:
+
== Plugins ==
  
# pacman -Ss vim-spell
+
Adding plugins to Vim can increase your productivity. Plugins can alter Vim's UI, add new commands, code completion support, integrate other programs and utilities with Vim, add support for additional languages and more.
  
Language dictionaries can also be found at the [http://ftp.vim.org/vim/runtime/spell/ Vim FTP archive]. Put the downloaded dictionar(y/ies) into the {{ic|~/.vim/spell}} folder and set the dictionary by typing: {{ic|:setlocal spell spelllang<nowiki>=</nowiki>LL}}
+
{{Tip|For a list of popular plugins, see [http://vimawesome.com/ Vim Awesome]}}
  
{{Tip|
+
=== Installation ===
* To enable spell checking for LaTeX (or TeX) documents only, add {{ic|autocmd FileType tex setlocal spell spelllang<nowiki>=</nowiki>en_us}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart vim. For spell checking of languages other than English, simply replace {{ic|en_us}} with the value appropriate for your language.
+
* You can enable spell checking for arbitrary file types (e.g. *.txt) by using the FileType plugin and a custom rule for file type detection. To enable spell checking for any file ending in {{ic|*.txt}}, create the file {{ic|/usr/share/vim/vimfiles/ftdetect/plaintext.vim}}, and insert the line {{ic|autocmd BufRead,BufNewFile *.txt    setfiletype plaintext}} into that file. Next, insert the line {{ic|autocmd FileType plaintext setlocal spell spelllang<nowiki>=</nowiki>en_us}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart vim.}}
+
  
===Syntax Highlighting===
+
==== Using a plugin manager ====
  
To enable syntax highlighting (vim supports a huge list of programming languages):
+
A plugin manager allows to install and manage Vim plugins in a similar way independently on which platform you are running Vim. It is a plugin that acts as a package manager for other Vim plugins.
  
filetype plugin on
+
* [https://github.com/gmarik/Vundle.vim Vundle] is currently the most popular plugin manager for Vim.
syntax on
+
* [https://github.com/junegunn/vim-plug Vim-plug] is a minimalist Vim plugin manager with many features like on-demand plugin loading and parallel updating.
 +
* [https://github.com/tpope/vim-pathogen pathogen.vim] is a simple plugin for managing Vim's runtimepath.
 +
* [https://github.com/Shougo/dein.vim Dein.vim] is a plugin manager replacing [https://github.com/Shougo/neobundle.vim NeoBundle], available as {{AUR|vim-dein-git}}.
  
=== Example ~/.vimrc ===
+
==== From Arch repositories ====
  
An example [[Vim/.vimrc|Vim configuration]].
+
The {{Grp|vim-plugins}} group provides many various plugins. Use {{ic|pacman -Sg vim-plugins}} command to list available packages which you can then [[install]] with pacman.
  
==Merging Files (Vimdiff)==
+
=== cscope ===
  
Vim includes a diff editor (a program that can merge differences between two files). Begin with {{Ic|vimdiff file1 file2}}; to use:
+
[http://cscope.sourceforge.net/ Cscope] is a tool for browsing a project. By navigating to a word/symbol/function and calling cscope (usually with shortcut keys) it can find: functions calling the function, the function definition, and more.
  
]c :        - next difference
+
[[Install]] the {{Pkg|cscope}} package.
[c :        - previous difference
+
Ctrl+w +w  - switch windows
+
do          - diff obtain
+
dp          - diff put
+
zo          - open folded text
+
zc          - close folded text
+
:diffupdate - re-scan the files for differences
+
  
==Vim Tips==
+
Copy the cscope default file where it will be automatically read by Vim:
  
Specific user tricks to accomplish tasks.
+
mkdir -p ~/.vim/plugin
 +
wget -P ~/.vim/plugin http://cscope.sourceforge.net/cscope_maps.vim
  
===Line Numbers===
+
{{Note|You will probably need to uncomment these lines in {{ic|~/.vim/plugin/cscope_maps.vim}} in order to enable cscope shortcuts in Vim 7.x:
 +
{{bc|1=
 +
set timeoutlen=4000
 +
set ttimeout
 +
}}}}
  
# Show line numbers by {{Ic|:set number}}.
+
Create a file which contains the list of files you wish cscope to index (cscope can handle many languages but this example finds ''.c'', ''.cpp'' and ''.h'' files, specific for C/C++ project):
# Jump to line number {{Ic|:<line number>}}.
+
  
===Substitute on Lines===
+
cd ''/path/to/project/dir''
 +
find . -type f -print | grep -E '\.(c(pp)?|h)$' > cscope.files
  
To only substitute between certain lines:
+
Create database files that cscope will read:
  
  :''n'',''n''s/one/two/g
+
  cscope -bq
  
For example, to replace instances of 'one' with 'two' between lines 3 and 4, one would execute:
+
{{Note|You must browse your project files from this location or set and export the {{ic|$CSCOPE_DB}} variable, pointing it to the {{ic|cscope.out}} file.}}
  
:3,4s/one/two/g
+
Default keyboard shortcuts:
  
===Make Vim restore cursor position in files===
+
  Ctrl-\ and
 +
      c: Find functions calling this function
 +
      d: Find functions called by this function
 +
      e: Find this egrep pattern
 +
      f: Find this file
 +
      g: Find this definition
 +
      i: Find files #including this file
 +
      s: Find this C symbol
 +
      t: Find assignments to
  
If you want the cursor to appear in its previous position after you open a file, add the following to your {{ic|~/.vimrc}}:
+
Feel free to change the shortcuts.
  
{{bc|<nowiki>
+
#Maps ctrl-c to find functions calling the function
if has("autocmd")
+
nnoremap <C-c> :cs find c <C-R>=expand("<cword>")<CR><CR>
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif
+
endif
+
</nowiki>}}
+
  
See also [http://vim.wikia.com/wiki/Restore_cursor_to_file_position_in_previous_editing_session this] tip in Vim Wiki.
+
=== Taglist ===
  
===Empty space at the bottom of gvim windows===
+
[http://vim-taglist.sourceforge.net/ Taglist] provides an overview of the structure of source code files and allows you to efficiently browse through source code files in different programming languages.
When using a [[window manager]] configured to ignore window size hints, gvim will fill the non-functional area with the GTK theme background color.  
+
  
A solution is to disable the menubar in {{ic|.vimrc}}, this will make the gvim window behave as it should, filling up the entire area:
+
[[Install]] the {{Pkg|vim-taglist}} package.
  
set go-=m "remove menubar
+
Useful options to be put in {{ic|~/.vimrc}}:
  
Another solution is to make a more pleasing background color: just put the following lines in {{ic|~/.gtkrc-2.0}}:
+
let Tlist_Compact_Format = 1
 +
let Tlist_GainFocus_On_ToggleOpen = 1
 +
let Tlist_Close_On_Select = 1
 +
nnoremap <C-l> :TlistToggle<CR>
  
style "vimfix" {
+
== See also ==
  bg[NORMAL] = "#242424" # this matches my gvim theme 'Normal' bg color.
+
}
+
widget "vim-main-window.*GtkForm" style "vimfix"
+
  
===Replace vi command with vim===
+
=== Official ===
  
Run the following commands:
 
 
# ln -s $(which vim) /usr/local/bin/vi
 
# ln -s $(which vim) /usr/local/bin/view
 
 
Also see http://superuser.com/questions/27091/vim-to-replace-vi
 
 
==See also==
 
 
===Official===
 
 
* [http://www.vim.org/ Homepage]
 
* [http://www.vim.org/ Homepage]
 
* [http://vimdoc.sourceforge.net/ Documentation]
 
* [http://vimdoc.sourceforge.net/ Documentation]
* [http://vim.wikia.com Tips Wiki]
+
* [http://vim.wikia.com Vim Wiki]
 +
* [http://www.vim.org/scripts/ Vim Scripts]
  
===Tutorials===
+
=== Tutorials ===
 +
 
 +
* [http://www.danielmiessler.com/study/vim/ vim Tutorial and Primer]
 
* [http://usalug.org/vi.html vi Tutorial and Reference Guide]
 
* [http://usalug.org/vi.html vi Tutorial and Reference Guide]
* [http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html Graphical vi-vim Cheat Sheet and Tutorial]
+
* [http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html Graphical vi-Vim Cheat Sheet and Tutorial]
 
* [http://blog.interlinked.org/tutorials/vim_tutorial.html Vim Introduction and Tutorial]
 
* [http://blog.interlinked.org/tutorials/vim_tutorial.html Vim Introduction and Tutorial]
* [http://vim.runpaint.org/ Vim Recipes] - A free cookbook.
+
* [http://www.openvim.com/ Open Vim] — collection of Vim learning tools
 +
* [http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/ Learn Vim Progressively]
 +
* [http://benmccormick.org/learning-vim-in-2014/ Learning Vim in 2014]
 +
* [http://www.moolenaar.net/habits.html Seven habits of effective text editing]
 +
* [http://bencrowder.net/files/vim-fu/ Basic Vim Tips]
 +
* [http://www.gentoo-wiki.info/HOWTO_VIM HOWTO Vim]
  
====Videos====
+
==== Videos ====
* [http://vimcasts.org/ Vimcasts] - Screencasts in .ogg format.
+
* [http://www.derekwyatt.org/vim/vim-tutorial-videos/vim-novice-tutorial-videos/ Tutorial Videos] - Covering the basics up to advanced topics.
+
  
===Example configurations===
+
* [http://vimcasts.org/ Vimcasts] — screencasts in ''.ogg'' format.
* [http://nion.modprobe.de/setup/vimrc nion's]
+
* [http://derekwyatt.org/vim/tutorials/ Vim Tutorial Videos] — covering the basics up to advanced topics.
 +
 
 +
==== Games ====
 +
 
 +
* [http://vim-adventures.com/ Vim Adventures]
 +
* [http://vimgolf.com/ VimGolf]
 +
 
 +
=== Configuration ===
 +
 
 +
* [https://web.archive.org/web/20131020125020/http://nion.modprobe.de/setup/vimrc nion's]
 
* [http://amix.dk/vim/vimrc.html A detailed configuration from Amir Salihefendic]
 
* [http://amix.dk/vim/vimrc.html A detailed configuration from Amir Salihefendic]
* [http://www.jukie.net/~bart/conf/vimrc Bart Trojanowski]
+
* [https://web.archive.org/web/20131004071740/http://www.jukie.net/~bart/conf/vimrc Bart Trojanowski]
 +
* [https://github.com/spf13/spf13-vim Steve Francia'http://vimawesome.com/s Vim Distribution]
 +
* [https://github.com/W4RH4WK/dotVim W4RH4WK's Vim configuration]
 +
* [http://www.askapache.com/linux/fast-vimrc.html Fast vimrc/colorscheme from askapache]
 +
* [https://gist.github.com/anonymous/c966c0757f62b451bffa Basic vimrc]
 +
* [http://www.usevim.com/ Usevim]
 +
 
 +
==== Colors ====
  
===Other===
+
* [http://bytefluent.com/vivify/ Vivify]
* [http://www.gentoo-wiki.info/HOWTO_VIM HOWTO Vim] - Gentoo wiki article which this article was based on (author unknown).
+
* [https://linuxtidbits.wordpress.com/2014/10/14/vim-customize-installed-colorschemes/ Vim colorscheme customization]
* [http://bytefluent.com/vivify/ Vivify] - A ColorScheme Editor for Vim
+

Latest revision as of 15:37, 11 September 2016

Vim is a terminal text editor. It is an extended version of vi with additional features, including syntax highlighting, a comprehensive help system, native scripting (vimscript), a visual mode for text selection, and comparison of files (vimdiff).

Installation

Install one of the following packages:

  • vim — with Python 2/3, Lua, Ruby and Perl interpreters support but without GTK/X support.
  • gvim — which also provides the same as the above vim package with GTK/X support.
Note:
  • The vim package is built without Xorg support; specifically the +clipboard feature is missing, so Vim will not be able to operate with the primary and clipboard selection buffers. The gvim package provides also the CLI version of Vim with the +clipboard feature.
  • The unofficial repository herecura also provides a number of Vim/gVim variants: vim-cli, vim-gvim-common, vim-gvim-gtk, vim-gvim-qt, vim-rt and vim-tiny.

Usage

For a basic overview on how to use Vim, follow the vim tutorial by running either vimtutor (for the terminal version) or gvimtutor (for the graphical version).

Vim includes a broad help system that can be accessed with the :h subject command. Subjects include commands, configuration options, key bindings, plugins etc. Use the :h command (without any subject) for information about the help system and jumping between subjects.

Configuration

Vim's user-specific configuration file is located in the home directory: ~/.vimrc, and Vim files of current user are located inside ~/.vim/. The global configuration file is located at /etc/vimrc. Global Vim files are located inside /usr/share/vim/.

Note: Commonly expected behavior such as syntax highlighting is enabled in defaults.vim, which is loaded when no ~/.vimrc is present. Add let skip_defaults_vim=1 to /etc/vimrc to disable loading of defaults.vim completely. [1]

Syntax highlighting

To enable syntax highlighting (Vim supports a huge list of programming languages):

:filetype plugin on
:syntax on

Visual wrapping

The wrap option is on by default, which instructs Vim to wrap lines longer than the width of the window, so that the rest of the line is displayed on the next line. The wrap option only affects how text is displayed, the text itself is not modified.

The wrapping normally occurs after the last character that fits the window, even when it is in the middle of a word. More intelligent wrapping can be controlled with the linebreak option. When it is enabled with set linebreak, the wrapping occurs after characters listed in the breakat string option, which by default contains a space and some punctuation marks (see :help breakat).

Wrapped lines are normally displayed at the beginning of the next line, regardless of any indentation. The breakindent option instructs Vim to take indentation into account when wrapping long lines, so that the wrapped lines keep the same indentation of the previously displayed line. The behaviour of breakindent can be fine-tuned with the breakindentopt option, for example to shift the wrapped line another four spaces to the right for Python files (see :help breakindentopt for details):

autocmd FileType python set breakindentopt=shift:4

Using the mouse

Vim has the ability to make use of the mouse, but it only works for certain terminals: on Linux it is xterm-based terminals and Linux console with gpm (see Console mouse support for details), and also PuTTY.

To enable this feature, add this line into ~/.vimrc:

set mouse=a

The mouse=a option is set in defaults.vim, which is sourced if there is no ~/.vimrc.

Note: When enabling the mouse in a terminal, copy/paste will use the "* register if there is access to an X server. The xterm handling of the mouse buttons can still be used by keeping the shift key pressed. Also see the clipboard option.

Traverse line breaks with arrow keys

By default, pressing at the beginning of a line, or pressing at the end of a line, will not let the cursor traverse to the previous, or following, line.

The default behavior can be changed by adding set whichwrap=b,s,<,>,[,] to your ~/.vimrc file.

Merging files

Vim includes a diff editor (a program that shows differences between two or more files and aids to conveniently merge them). Use vimdiff to run the diff editor — just specify some couple of files to it: vimdiff file1 file2. Here is the list of vimdiff-specific commands.

Action Shortcut
next change ]c
previous change [c
diff obtain do
diff put dp
fold open zo
fold close zc
rescan files :diffupdate
switch windows Ctrl+w+w

Tips and tricks

Line numbers

To show the line number column, use :set number. By default absolute line numbers are shown, relative numbers can be enabled with :set relativenumber.

Jumping to a specific line is possible with :line number or line numbergg. Jumps are remembered in a jump list, see :h jump-motions for details.

Spell checking

Vim has the ability to do spell checking, enable by entering:

set spell

By default, only English language dictionaries are installed. More dictionaries can be found in the official repositories by searching for vim-spell. Additional dictionaries can be found in the Vim's FTP archive. Additional dictionaries can be put in the folder ~/.vim/spell/ and enabled with the command: :setlocal spell spelllang=en_us (replacing the en_us with the name of the needed dictionary).

Action Shortcut
next spelling ]s
previous spelling [s
spelling suggestions z=
spelling good, add zg
spelling good, session zG
spelling wrong, add zw
spelling wrong, session zW
spelling repeat all in file :spellr
Tip:
  • To enable spelling in two languages (for instance English and German), add set spelllang=en,de into your ~/.vimrc or /etc/vimrc, and then restart Vim.
  • You can enable spell checking for arbitrary file types (e.g. .txt) by using the FileType plugin and a custom rule for file type detection. To enable spell checking for any file ending with .txt, create the file /usr/share/vim/vimfiles/ftdetect/plaintext.vim, and insert the line autocmd BufRead,BufNewFile *.txt setfiletype plaintext into that file. Next, insert the line autocmd FileType plaintext setlocal spell spelllang=en_us into your ~/.vimrc or /etc/vimrc, and then restart Vim.
  • To enable spell checking for LaTeX (or TeX) documents only, add autocmd FileType tex setlocal spell spelllang=en_us into your ~/.vimrc or /etc/vimrc, and then restart Vim.

Save cursor position

If you want the cursor to appear in its previous position after you open a file, add the following to your ~/.vimrc:

augroup resCur
  autocmd!
  autocmd BufReadPost * call setpos(".", getpos("'\""))
augroup END

Replace vi command with Vim

Create an alias for vi to vim.

Alternatively, if you want to be able to type sudo vi and get vim, install vi-vim-symlinkAUR which will remove vi and replace it with a symlink to vim.

DOS/Windows carriage returns

If there is a ^M at the end of each line then this means you are editing a text file which was created in MS-DOS or Windows. This is because in Linux only a single line feed character (LF) used for line break, but in Windows/MS DOS systems they are using a sequence of a carriage return (CR) and a line feed (LF) for the same. And this carriage returns are displayed as ^M.

To remove all carriage returns from a file do:

:%s/^M//g

Note that there ^ is a control letter. To enter the control sequence ^M press Ctrl+v,Ctrl+m.

Alternatively install the package dos2unix and run dos2unix file to fix the file.

Note: Another simple way is by changing fileformat setting. set ff=unix to convert files with DOS/Windows line ending to Unix line ending. To do the reverse, just issue set ff=dos to convert files with Unix line ending to DOS/Windows line ending.

Empty space at the bottom of gVim windows

When using a window manager configured to ignore window size hints, gVim will fill the non-functional area with the GTK theme background color.

The solution is to adjust how much space gVim reserves at the bottom of the window. Put the following line in ~/.vimrc:

set guiheadroom=0
Note: If you set it to zero, you will not be able to see the bottom horizontal scrollbar.

Plugins

Adding plugins to Vim can increase your productivity. Plugins can alter Vim's UI, add new commands, code completion support, integrate other programs and utilities with Vim, add support for additional languages and more.

Tip: For a list of popular plugins, see Vim Awesome

Installation

Using a plugin manager

A plugin manager allows to install and manage Vim plugins in a similar way independently on which platform you are running Vim. It is a plugin that acts as a package manager for other Vim plugins.

  • Vundle is currently the most popular plugin manager for Vim.
  • Vim-plug is a minimalist Vim plugin manager with many features like on-demand plugin loading and parallel updating.
  • pathogen.vim is a simple plugin for managing Vim's runtimepath.
  • Dein.vim is a plugin manager replacing NeoBundle, available as vim-dein-gitAUR.

From Arch repositories

The vim-plugins group provides many various plugins. Use pacman -Sg vim-plugins command to list available packages which you can then install with pacman.

cscope

Cscope is a tool for browsing a project. By navigating to a word/symbol/function and calling cscope (usually with shortcut keys) it can find: functions calling the function, the function definition, and more.

Install the cscope package.

Copy the cscope default file where it will be automatically read by Vim:

mkdir -p ~/.vim/plugin
wget -P ~/.vim/plugin http://cscope.sourceforge.net/cscope_maps.vim
Note: You will probably need to uncomment these lines in ~/.vim/plugin/cscope_maps.vim in order to enable cscope shortcuts in Vim 7.x:
set timeoutlen=4000
set ttimeout

Create a file which contains the list of files you wish cscope to index (cscope can handle many languages but this example finds .c, .cpp and .h files, specific for C/C++ project):

cd /path/to/project/dir
find . -type f -print | grep -E '\.(c(pp)?|h)$' > cscope.files

Create database files that cscope will read:

cscope -bq
Note: You must browse your project files from this location or set and export the $CSCOPE_DB variable, pointing it to the cscope.out file.

Default keyboard shortcuts:

 Ctrl-\ and
      c: Find functions calling this function
      d: Find functions called by this function
      e: Find this egrep pattern
      f: Find this file
      g: Find this definition
      i: Find files #including this file
      s: Find this C symbol
      t: Find assignments to

Feel free to change the shortcuts.

#Maps ctrl-c to find functions calling the function
nnoremap <C-c> :cs find c <C-R>=expand("<cword>")<CR><CR>

Taglist

Taglist provides an overview of the structure of source code files and allows you to efficiently browse through source code files in different programming languages.

Install the vim-taglist package.

Useful options to be put in ~/.vimrc:

let Tlist_Compact_Format = 1
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_Close_On_Select = 1
nnoremap <C-l> :TlistToggle<CR>

See also

Official

Tutorials

Videos

Games

Configuration

Colors