Difference between revisions of "Vim"

From ArchWiki
Jump to: navigation, search
m (Syntax highlighting)
(the second sentence is equally useless, anything takes time to learn, including the CUA interfaces in Notepad & co)
 
(176 intermediate revisions by 45 users not shown)
Line 1: Line 1:
 
[[Category:Development]]
 
[[Category:Development]]
 
[[Category:Text editors]]
 
[[Category:Text editors]]
 +
[[de:Vim]]
 
[[es:Vim]]
 
[[es:Vim]]
[[de:Vim]]
 
 
[[it:Vim]]
 
[[it:Vim]]
 +
[[ja:Vim]]
 
[[lt:Vim]]
 
[[lt:Vim]]
 
[[ru:Vim]]
 
[[ru:Vim]]
 
[[zh-CN:Vim]]
 
[[zh-CN:Vim]]
 
[[zh-TW:Vim]]
 
[[zh-TW:Vim]]
''"[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."''
+
{{Related articles start}}
 +
{{Related|List of applications/Documents#Vi text editors}}
 +
{{Related articles end}}
  
Vim focuses on keyboard usage, and offers useful features such as syntax highlighting and scripting capabilities. 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).
  
 
== 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|The {{Pkg|vim}} package is meant to be as lightweight as possible; hence, it does not support Python, Lua, and Ruby interpreters, nor does it support X server options (this means that it will not support copy and paste from the X clipboard). If you require these options, install the {{Pkg|gvim}} package instead (it includes the {{ic|vim}} binary as well). The {{ic|herecura-stable}} unofficial repository also provides a couple different Vim / gVim variants:
+
* {{Pkg|vim}} — with Python 2/3, Lua, Ruby and Perl interpreters support but without GTK/X support.
{{hc|$ pacman -Slq herecura-stable | grep vim|
+
* {{Pkg|gvim}} — which also provides the same as the above {{ic|vim}} package with GTK/X support.
vim-cli
+
vim-gvim-gtk
+
vim-gvim-motif
+
vim-gvim-qt
+
vim-gvim-x11
+
vim-rt
+
vim-tiny
+
}}
+
}}
+
  
{{Note|There are some visualization problems in KDE using {{Pkg|gvim}} from official repositories. In that case you can install {{ic|vim-gvim-qt}} from {{ic|herecura-stable}} or {{AUR|vim-qt}}
+
{{Note|
 +
* 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.
 +
* 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}}.
 
}}
 
}}
==Usage==
 
  
This is a basic overview on how to use Vim.  Alternately, running {{Ic|vimtutor}} or {{Ic|gvimtutor}} will launch vim's tutorial, which takes about 25-30 minutes.
+
== Usage ==
  
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
+
To get some commonly expected behaviors (such as syntax highlighting), add the Vim example configuration to {{ic|/etc/vimrc}}:
  
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.
+
{{hc|/etc/vimrc/|
 +
...
  
{{Note|Vim is an example of classic Unix-style ware. It has a steep learning curve, but once you get started, you will find that it is extremely powerful. 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).}}
+
runtime! vimrc_example.vim
 +
}}
  
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.
+
=== Syntax highlighting ===
  
Return to command mode at any time by pressing {{keypress|Esc}}.
+
To enable syntax highlighting (Vim supports a huge list of programming languages):
  
===Moving around===
+
:filetype plugin on
 +
:syntax on
  
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.
+
=== Visual wrapping ===
  
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''').
+
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.
  
{{keypress|^}} will put the cursor at the beginning of the line, and {{keypress|$}} will place it at the end.
+
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}}).
  
{{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.}}
+
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):
  
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.
+
autocmd FileType python set breakindentopt=shift:4
  
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.
+
=== Using the mouse ===
  
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.
+
Vim has the ability to make use of the mouse, but it only works for certain terminals (on Linux it is [[xterm]] and Linux console with {{Pkg|gpm}}, see [[Console mouse support]] for details).
  
===Repeating commands===
+
To enable this feature, add this line into {{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…
+
set mouse=a
  
===Deleting===
+
{{Note|
 +
* This even works in PuTTY over SSH.
 +
* In PuTTY, the normal highlight/copy behavior is changed because Vim enters visual mode when the mouse is used. To select text with the mouse normally, hold down the {{ic|Shift}} key while selecting text.
 +
}}
  
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).
+
=== Traverse line breaks with arrow keys ===
  
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.
+
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.
  
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}}.
+
The default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file.
  
===Undo and redo===
+
== Merging files ==
  
Vim has a built-in clipboard (also known as a buffer). Actions can be undone with {{keypress|u}} and redone with {{keypress|Ctrl+r}}.
+
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.
  
===Visual mode===
+
{| 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}}
 +
|}
  
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.
+
== Tips and tricks ==
  
{{Note|Whenever you delete something, that something is placed inside a buffer and is available for pasting.}}
+
=== Line numbers ===
  
===Search and replace===
+
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}}.
  
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}}, press {{keypress|N}} for the previous match.
+
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 and replace use the substitute {{keypress|:s/}} command. The syntax is: {{Ic|[range]s///[arguments]}}. For example:
+
=== Spell checking ===
  
{{bc|
+
Vim has the ability to do spell checking, enable by entering:
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]}}.
+
set spell
  
{{bc|
+
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).
Command  Outcome
+
:g/^#/d  Delete all lines that begins with #
+
:g/^$/d  Delete all lines that are empty
+
}}
+
  
===Saving and quitting===
+
{| class="wikitable"
 +
! Action                      !! Shortcut
 +
|-
 +
| 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}}
 +
|}
  
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}}.
+
{{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.}}
  
=== Additional commands ===
+
=== Save cursor position ===
  
# 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.
+
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}}:
# {{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.
+
# {{keypress|yy}} will yank an entire line
+
# {{keypress|cc}} will delete the current line and place you in insert mode.
+
# {{keypress|*}} will highlight the current word and {{keypress|n}} will search it
+
  
==Configuration==
+
augroup resCur
 +
  autocmd!
 +
  autocmd BufReadPost * call setpos(".", getpos("'\""))
 +
augroup END
  
Vim's user-specific configuration file is located in the home directory: {{ic|~/.vimrc}}, and files are located inside {{ic|~/.vim/}} The global configuration file is located at {{ic|/etc/vimrc}}. Global files are located inside {{ic|/usr/share/vim/}}.
+
=== Replace vi command with Vim ===
  
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 (such as syntax highlighting, returning to the last known cursor position), consider using Vim's example configuration file:
+
Create an [[alias]] for {{ic|vi}} to {{ic|vim}}.
  
# mv /etc/vimrc /etc/vimrc.bak
+
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 /usr/share/vim/vim73/vimrc_example.vim /etc/vimrc
+
  
===Wrap searches===
+
=== DOS/Windows carriage returns ===
  
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.  
+
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}}.
  
set wrapscan
+
To remove all carriage returns from a file do:
  
=== Spell checking ===
+
:%s/^M//g
  
set spell
+
Note that there {{ic|^}} is a control letter. To enter the control sequence {{ic|^M}} press {{ic|Ctrl+v,Ctrl+m}}.
  
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.
+
Alternatively install the package {{pkg|dos2unix}} and run {{ic|dos2unix ''file''}} to fix the file.
  
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:
+
{{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. }}
  
# pacman -Ss vim-spell
+
=== Empty space at the bottom of gVim windows ===
  
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|1=:setlocal spell spelllang=LL}}
+
When using a [[window manager]] configured to ignore window size hints, gVim will fill the non-functional area with the GTK theme background color.
  
{{Tip|
+
The solution is to adjust how much space gVim reserves at the bottom of the window. Put the following line in {{ic|~/.vimrc}}:
* 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. For spell checking of languages other than English, simply replace {{ic|en_us}} with the value appropriate for your language.
+
* 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 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|1=autocmd FileType plaintext setlocal spell spelllang=en_us}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim.}}
+
  
===Syntax highlighting===
+
set guiheadroom=0
  
To enable syntax highlighting (Vim supports a huge list of programming languages):
+
{{Note|If you set it to zero, you will not be able to see the bottom horizontal scrollbar.}}
  
:filetype plugin on
+
== Plugins ==
:syntax on
+
  
===Using the mouse===
+
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.
  
Vim has the ability to make use of the mouse, but requires xterm's mouse reporting feature.
+
{{Tip|For a list of popular plugins, see [http://vimawesome.com/ Vim Awesome]}}
  
# See the example .vimrc below to enable the mouse.
+
=== Installation ===
# Use xterm. In your console: {{ic|1=export TERM=xterm-256color}} or {{ic|1=export TERM=xterm}}
+
  
Notes:
+
==== Using a plugin manager ====
* This even works in PuTTY over SSH.
+
* In PuTTY, the normal highlight/copy behaviour is changed because Vim enters visual mode when the mouse is used. To select text with the mouse normally, hold down the {{keypress|Shift}} key while selecting text.
+
  
===Traverse line breaks with arrow keys===
+
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.
  
By default, pressing {{keypress|←}} at the beginning of a line, or pressing {{keypress|}} at the end of a line, will not let the cursor traverse to the previous, or following, line.
+
* [https://github.com/gmarik/Vundle.vim Vundle] is currently the most popular plugin manager for Vim.
 +
* [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}}.
  
The default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file.
+
==== From Arch repositories ====
  
=== Example ~/.vimrc ===
+
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.
  
An example [[Vim/.vimrc|Vim configuration]].
+
=== cscope ===
  
==Merging files (vimdiff)==
+
[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.
  
Vim includes a diff editor (a program that can merge differences between two files). vimdiff will open colored windows each showing the content of the file with colored highlights of the differences, line by line. You are left with two modes: the insert one, which let you edit the file, and the screen mode, which let you move around windows and lines. Begin by running {{Ic|vimdiff file1 file2}}. Some example commands are found below:
+
[[Install]] the {{Pkg|cscope}} package.
  
;{{keypress|]c}}                          : next difference
+
Copy the cscope default file where it will be automatically read by Vim:
;{{keypress|[c}}                          : previous difference
+
;{{keypress|Ctrl+w+w}}                    : switch windows
+
;{{keypress|i}}                            : enter Insert mode
+
;{{keypress|Esc}}                          : exit Insert mode
+
;{{keypress|p}}                            : paste a line
+
;{{keypress|do}}                          : diff obtain. when cursor is on a highlighted difference and changes from other window will move into the current one
+
;{{keypress|dp}}                          : diff put. same as diff obtain but will put the changes from current windows into the other one
+
;{{keypress|zo}}                          : open folded text
+
;{{keypress|zc}}                          : close folded text
+
;{{keypress|<nowiki>:</nowiki>diffupdate}} : re-scan the files for differences
+
;{{keypress|yy}}                          : copy a line
+
;{{keypress|:wq}}                          : save and exit the current window
+
;{{keypress|:wqa}}                        : save and exit both windows
+
;{{keypress|:q!}}                          : exit without saving
+
  
Once your file has been correctly edited taking account changes in file.pacnew:
+
  mkdir -p ~/.vim/plugin
  # mv file file.bck
+
  wget -P ~/.vim/plugin http://cscope.sourceforge.net/cscope_maps.vim
  # mv file.pacnew file
+
Check if your new file is correct, then remove your backup:
+
# rm file.bck
+
  
==Vim tips==
+
{{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
 +
}}}}
  
Specific user tricks to accomplish tasks.
+
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):
  
===Line numbers===
+
cd ''/path/to/project/dir''
 +
find . -type f -print | grep -E '\.(c(pp)?|h)$' > cscope.files
  
# Show line numbers by {{Ic|:set number}}.
+
Create database files that cscope will read:
# Jump to line number {{Ic|:<line number>}}.
+
  
===Substitute on lines===
+
cscope -bq
  
To only substitute between certain lines:
+
{{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.}}
  
:''n'',''n''s/one/two/g
+
Default keyboard shortcuts:
  
For example, to replace instances of 'one' with 'two' between lines 3 and 4, one would execute:
+
  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
  
:3,4s/one/two/g
+
Feel free to change the shortcuts.
  
===Make Vim restore cursor position in files===
+
#Maps ctrl-c to find functions calling the function
 +
nnoremap <C-c> :cs find c <C-R>=expand("<cword>")<CR><CR>
  
If you want the cursor to appear in its previous position after you open a file, add the following to your {{ic|~/.vimrc}}:
+
=== Taglist ===
  
{{bc|<nowiki>
+
[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.
if has("autocmd")
+
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.
+
[[Install]] the {{Pkg|vim-taglist}} package.
  
===Empty space at the bottom of gVim windows===
+
Useful options to be put in {{ic|~/.vimrc}}:
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 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
 
 
==Troubleshooting==
 
 
==="^M"===
 
There is a "^M" at the end of each line. This usually happens when you are editing a text file which was created in MS-DOS or Windows.
 
 
Solution:
 
Replace all "^M" using the command:
 
 
{{bc|:%s/^M//g}}
 
 
Pay attention, "^" is the control letter, press {{Keypress|Ctrl+Q}} to get the right "^".
 
 
Alternatively, install the package {{pkg|dos2unix}} from the official repositories, and run {{ic|dos2unix <file name here>}}.
 
 
==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://www.openvim.com/ Open Vim] - Collection of Vim learning tools
+
 
* [http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/ Learn Vim Progressively]
 
* [http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/ Learn Vim Progressively]
* [http://www.knowvim.com/ know vim]
+
* [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.
+
* [http://vimcasts.org/ Vimcasts] — screencasts in ''.ogg'' format.
 +
* [http://derekwyatt.org/vim/tutorials/ Vim Tutorial Videos] — covering the basics up to advanced topics.
 +
 
 +
==== Games ====
  
====Games====
 
 
* [http://vim-adventures.com/ Vim Adventures]
 
* [http://vim-adventures.com/ Vim Adventures]
 
* [http://vimgolf.com/ VimGolf]
 
* [http://vimgolf.com/ VimGolf]
  
===Example configurations===
+
=== Configuration ===
* [http://nion.modprobe.de/setup/vimrc nion's]
+
 
 +
* [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's Vim Distribution]
+
* [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 17:04, 16 July 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/.

To get some commonly expected behaviors (such as syntax highlighting), add the Vim example configuration to /etc/vimrc:

/etc/vimrc/
...

runtime! vimrc_example.vim

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 and Linux console with gpm, see Console mouse support for details).

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

set mouse=a
Note:
  • This even works in PuTTY over SSH.
  • In PuTTY, the normal highlight/copy behavior is changed because Vim enters visual mode when the mouse is used. To select text with the mouse normally, hold down the Shift key while selecting text.

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