Difference between revisions of "Vim"
m (→Spell Checking: formatting) |
m (added link to my awesome vimrc) |
||
(36 intermediate revisions by 20 users not shown) | |||
Line 2: | Line 2: | ||
[[Category:Text editors]] | [[Category:Text editors]] | ||
[[es:Vim]] | [[es:Vim]] | ||
+ | [[de:Vim]] | ||
[[it:Vim]] | [[it:Vim]] | ||
[[lt:Vim]] | [[lt:Vim]] | ||
Line 7: | Line 8: | ||
[[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."'' | |
− | |||
− | |||
− | + | 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. | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
== Installation == | == Installation == | ||
Line 26: | Line 16: | ||
[[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. | [[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. | ||
− | {{Note|{{Pkg|vim}} | + | {{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: | |
− | |||
{{hc|$ pacman -Slq herecura-stable | grep vim| | {{hc|$ pacman -Slq herecura-stable | grep vim| | ||
vim-cli | vim-cli | ||
Line 38: | Line 27: | ||
vim-tiny | vim-tiny | ||
}} | }} | ||
+ | |||
+ | * 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}} | ||
}} | }} | ||
==Usage== | ==Usage== | ||
− | This is a basic overview on how to use | + | 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. |
+ | |||
+ | Vim has four different modes: | ||
* Command mode: keystrokes are interpreted as commands. | * Command mode: keystrokes are interpreted as commands. | ||
Line 49: | Line 42: | ||
* Ex mode: input mode for additional commands (e.g. saving a file, replacing text...) | * Ex mode: input mode for additional commands (e.g. saving a file, replacing text...) | ||
− | ===Basic | + | ===Basic editing=== |
− | If you start | + | If you start Vim with: |
$ vim somefile.txt | $ vim somefile.txt | ||
− | 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 | + | 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. |
− | {{Note|Vim is an example of classic Unix-style ware. | + | {{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 ({{ic|s}} will replace a character, {{ic|S}} will replace a line), other times they are completely different commands ({{ic|j}} will move down, {{ic|J}} will join two lines).}} |
− | You insert text (stick it before the cursor) with the {{ | + | You insert text (stick it before the cursor) with the {{ic|i}} command. {{ic|I}} (uppercase '''i''') inserts text at the beginning of the line. You append text (place text after the cursor, what most people expect) with {{ic|a}}. Typing {{ic|A}} will place the cursor at the end of the line. |
− | Return to command mode at any time by pressing {{ | + | Return to command mode at any time by pressing {{ic|Esc}}. |
− | ===Moving | + | ===Moving around=== |
− | In | + | 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. |
− | In | + | In Vim you can move down by pressing {{ic|j}}. You can remember this because the “j” hangs down. You move the cursor back up by pressing {{ic|k}}. Left is {{ic|h}} (it's left of the “j”), and right is {{ic|l}} (lowercase '''L'''). |
− | {{ | + | {{ic|^}} will put the cursor at the beginning of the line, and {{ic|$}} will place it at the end. |
− | {{Note|{{ | + | {{Note|{{ic|^}} and {{ic|$}} 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.}} |
− | To advance a word, press the {{ | + | To advance a word, press the {{ic|w}} key. {{ic|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, {{ic|b}} is used. Once again, {{ic|B}} will include more characters in what Vim considers a word. To advance to the end of a word, use {{ic|e}}, {{ic|E}} includes more characters. |
− | To advance to the beginning of a sentence, {{ | + | To advance to the beginning of a sentence, {{ic|(}} will get the job done. {{ic|)}} will do the opposite, moving to the end of a sentence. For an even bigger jump, {{ic|{}} will move the the beginning a whole paragraph. {{ic|<nowiki>}</nowiki>}} will advance to the end of a whole paragraph. |
− | To advance to the header (top) of the screen, {{ | + | To advance to the header (top) of the screen, {{ic|H}} will get the job done. {{ic|M}} will advance to the middle of the screen, and {{ic|L}} will advance to the last (bottom). {{ic|gg}} will go to the beginning of the file, {{ic|G}} will go to the end of the file. {{ic|Ctrl+D}} will let you scroll page by page. |
===Repeating commands=== | ===Repeating commands=== | ||
− | 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 {{ | + | 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 {{ic|s}} command). For example, pressing {{ic|3i}} then “Help! ” then {{ic|Esc}} will print “Help! Help! Help!“. Pressing {{ic|<nowiki>2}</nowiki>}} will advance you two paragraphs. This comes in handy with the next few commands… |
===Deleting=== | ===Deleting=== | ||
− | The {{ | + | The {{ic|x}} command will delete the character under the cursor. {{ic|X}} will delete the character before the cursor. This is where those number functions get fun. {{ic|6x}} will delete 6 characters. Pressing {{ic|.}} (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 {{ic|3x}}, move to the next "foobar" and hit {{ic|.}} (dot). |
− | The {{ | + | The {{ic|d}} will tell Vim that you want to delete something. After pressing {{ic|d}}, you need to tell Vim what to delete. Here you can use the movement commands. {{ic|dW}} will delete up to the next word. {{ic|d^}} will delete up unto the beginning of the line. Prefacing the delete command with a number works well too: {{ic|3dW}} will delete the next three words. {{ic|D}} (uppercase) is a shortcut to delete until the end of the line (basically {{ic|d$}}). Pressing {{ic|dd}} will delete the whole line. |
− | To delete then replace the current word, place the cursor on the word and execute the command {{ | + | To delete then replace the current word, place the cursor on the word and execute the command {{ic|cw}}. This will delete the word and change to insert mode. To replace only a single letter use {{ic|r}}. |
− | ===Undo and | + | ===Undo and redo=== |
− | + | Vim has a built-in clipboard (also known as a buffer). Actions can be undone with {{ic|u}} and redone with {{ic|Ctrl+r}}. | |
− | ===Visual | + | ===Visual mode=== |
− | Pressing {{ | + | Pressing {{ic|v}} will put you in visual mode . Here you can move around to select text, when you’re done, you press {{ic|y}} to yank the text into the buffer (copy), or you may use {{ic|c}} to cut. {{ic|p}} pastes after the cursor, {{ic|P}} pastes before. {{ic|V}}, Visual Line mode, is the same for entire lines. {{ic|Ctrl+v}} is for blocks of text. |
{{Note|Whenever you delete something, that something is placed inside a buffer and is available for pasting.}} | {{Note|Whenever you delete something, that something is placed inside a buffer and is available for pasting.}} | ||
− | ===Search and | + | ===Search and replace=== |
− | To search for a word or character in the file, simply use {{ | + | To search for a word or character in the file, simply use {{ic|/}} and then the characters your are searching for and press enter. To view the next match in the search press {{ic|n}}, press {{ic|N}} for the previous match. |
− | To search and replace use the substitute {{ | + | To search and replace use the substitute {{ic|:s/}} command. The syntax is: {{Ic|[range]s///[arguments]}}. For example: |
{{bc| | {{bc| | ||
Line 115: | Line 108: | ||
}} | }} | ||
− | You can use the global {{ | + | You can use the global {{ic|:g/}} command to search for patterns and then execute a command for each match. The syntax is: {{Ic|[range]:g//[cmd]}}. |
{{bc| | {{bc| | ||
Line 123: | Line 116: | ||
}} | }} | ||
− | ===Saving and | + | ===Saving and quitting=== |
− | To save and/or quit, you will need to use Ex mode. Ex mode commands are preceded by a {{ | + | To save and/or quit, you will need to use Ex mode. Ex mode commands are preceded by a {{ic|:}}. To write a file use {{ic|:w}} or if the file doesn’t have a name {{ic|''':w''' filename}}. Quitting is done with {{ic|:q}}. If you choose not to save your changes, use {{ic|:q!}}. To save and quit {{ic|:x}}. |
− | === Additional | + | === Additional commands === |
− | # Pressing {{ | + | # Pressing {{ic|s}} will erase the current letter under the cursor, and place you in insert mode. {{ic|S}} will erase the whole line, and place you in insert mode. |
− | # {{ | + | # {{ic|o}} will create a newline below the line and put you insert mode, {{ic|O}} will create a newline above the line and put you in insert mode. |
− | # {{ | + | # {{ic|yy}} will yank an entire line |
− | # {{ | + | # {{ic|cc}} will delete the current line and place you in insert mode. |
− | # {{ | + | # {{ic|*}} will highlight the current word and {{ic|n}} will search it |
==Configuration== | ==Configuration== | ||
− | Vim's | + | 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/}}. |
− | + | 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: | |
− | + | # mv /etc/vimrc /etc/vimrc.bak | |
− | cp /usr/share/vim/ | + | # cp /usr/share/vim/vim74/vimrc_example.vim /etc/vimrc |
− | + | ===Wrap searches=== | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | ===Wrap | ||
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. | 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. | ||
Line 162: | Line 143: | ||
set wrapscan | set wrapscan | ||
− | === Spell | + | === Spell checking === |
set spell | set spell | ||
− | With this setting, Vim will highlight incorrectly spelled words. Place the cursor on a misspelled word and enter {{ | + | With this setting, Vim will highlight incorrectly spelled words. Place the cursor on a misspelled word and enter {{ic|1=z=}} to view spelling suggestions. |
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: | 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: | ||
Line 172: | Line 153: | ||
# pacman -Ss vim-spell | # pacman -Ss vim-spell | ||
− | 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 | + | 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}} |
{{Tip| | {{Tip| | ||
− | * To enable spell checking for LaTeX (or TeX) documents only, add {{ic|autocmd FileType tex setlocal spell spelllang | + | * 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|set spelllang | + | * 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|autocmd FileType plaintext setlocal spell spelllang | + | * 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 | + | ===Syntax highlighting=== |
− | To enable syntax highlighting ( | + | To enable syntax highlighting (Vim supports a huge list of programming languages): |
− | filetype plugin on | + | :filetype plugin on |
− | syntax on | + | :syntax on |
− | ===Using the | + | ===Using the mouse=== |
− | + | Vim has the ability to make use of the mouse, but requires xterm's mouse reporting feature. | |
# See the example .vimrc below to enable the mouse. | # See the example .vimrc below to enable the mouse. | ||
− | # Use xterm. In your console: {{ic|1=export TERM=xterm- | + | # Use xterm. In your console: {{ic|1=export TERM=xterm-256color}} or {{ic|1=export TERM=xterm}} |
Notes: | Notes: | ||
* This even works in PuTTY over SSH. | * This even works in PuTTY over SSH. | ||
− | * In PuTTY, the normal highlight/copy behaviour is changed because | + | * 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 {{ic|Shift}} key while selecting text. |
===Traverse line breaks with arrow keys=== | ===Traverse line breaks with arrow keys=== | ||
− | By default, pressing {{ | + | 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 default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file. | The default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file. | ||
Line 207: | Line 188: | ||
An example [[Vim/.vimrc|Vim configuration]]. | An example [[Vim/.vimrc|Vim configuration]]. | ||
− | == | + | ==Plugins== |
+ | Adding plugins to vim can increase your productivity. The group vim-plugins has many plugins to choose from(there are more in the repos though ie: vim-supertab). | ||
+ | pacman -Ss vim-plugins | ||
+ | ===cscope=== | ||
+ | [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. Multiple steps are required to search a code base. | ||
+ | |||
+ | Install the {{Pkg|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 | ||
+ | |||
+ | Create a file which contains the files you wish cscope to index(Cscope can handle many languages but this example finds .c, .cpp, and .h files): | ||
+ | cd ''/path/to/projectfolder/'' | ||
+ | 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=== | |
+ | [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. | ||
− | + | Install the {{Pkg|vim-taglist}} package. | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | ==Vim | + | Usefull 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> | ||
+ | |||
+ | ==Merging files (vimdiff)== | ||
+ | |||
+ | 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: | ||
+ | |||
+ | ;{{ic|]c}} : next difference | ||
+ | ;{{ic|[c}} : previous difference | ||
+ | ;{{ic|Ctrl+w+w}} : switch windows | ||
+ | ;{{ic|i}} : enter Insert mode | ||
+ | ;{{ic|Esc}} : exit Insert mode | ||
+ | ;{{ic|p}} : paste a line | ||
+ | ;{{ic|do}} : diff obtain. when cursor is on a highlighted difference and changes from other window will move into the current one | ||
+ | ;{{ic|dp}} : diff put. same as diff obtain but will put the changes from current windows into the other one | ||
+ | ;{{ic|zo}} : open folded text | ||
+ | ;{{ic|zc}} : close folded text | ||
+ | ;{{ic|<nowiki>:</nowiki>diffupdate}} : re-scan the files for differences | ||
+ | ;{{ic|yy}} : copy a line | ||
+ | ;{{ic|:wq}} : save and exit the current window | ||
+ | ;{{ic|:wqa}} : save and exit both windows | ||
+ | ;{{ic|:q!}} : exit without saving | ||
+ | |||
+ | Once your file has been correctly edited taking account changes in file.pacnew: | ||
+ | # mv file file.bck | ||
+ | # mv file.pacnew file | ||
+ | Check if your new file is correct, then remove your backup: | ||
+ | # rm file.bck | ||
+ | |||
+ | ==Vim tips== | ||
Specific user tricks to accomplish tasks. | Specific user tricks to accomplish tasks. | ||
− | ===Line | + | ===Line numbers=== |
# Show line numbers by {{Ic|:set number}}. | # Show line numbers by {{Ic|:set number}}. | ||
# Jump to line number {{Ic|:<line number>}}. | # Jump to line number {{Ic|:<line number>}}. | ||
− | ===Substitute on | + | ===Substitute on lines=== |
To only substitute between certain lines: | To only substitute between certain lines: | ||
Line 251: | Line 290: | ||
See also [http://vim.wikia.com/wiki/Restore_cursor_to_file_position_in_previous_editing_session this] tip in Vim Wiki. | See also [http://vim.wikia.com/wiki/Restore_cursor_to_file_position_in_previous_editing_session this] tip in Vim Wiki. | ||
− | ===Empty space at the bottom of | + | ===Empty space at the bottom of gVim windows=== |
− | When using a [[window manager]] configured to ignore window size hints, | + | 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. Take note that if you set it to zero, you won't be able to see the bottom horizontal scrollbar, if you have one. Put the following line in {{ic|~/.vimrc}}: | |
− | + | set guiheadroom=0 | |
− | |||
− | |||
− | |||
===Replace vi command with vim=== | ===Replace vi command with vim=== | ||
− | + | Create an [[Bash#Aliases|alias]] for {{ic|vi}} to {{ic|vim}}. | |
− | |||
− | |||
− | |||
− | + | ==Troubleshooting== | |
− | |||
− | == | ||
==="^M"=== | ==="^M"=== | ||
Line 284: | Line 311: | ||
{{bc|:%s/^M//g}} | {{bc|:%s/^M//g}} | ||
− | Pay attention, "^" is the control letter, press | + | Pay attention, "^" is the control letter, press {{ic|Ctrl+Q}} to get the right "^". |
Alternatively, install the package {{pkg|dos2unix}} from the official repositories, and run {{ic|dos2unix <file name here>}}. | Alternatively, install the package {{pkg|dos2unix}} from the official repositories, and run {{ic|dos2unix <file name here>}}. | ||
Line 297: | Line 324: | ||
===Tutorials=== | ===Tutorials=== | ||
* [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- | + | * [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:// | + | * [http://www.openvim.com/ Open Vim] - Collection of Vim learning tools |
+ | * [http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/ Learn Vim Progressively] | ||
+ | * [http://www.knowvim.com/ know vim] | ||
====Videos==== | ====Videos==== | ||
* [http://vimcasts.org/ Vimcasts] - Screencasts in .ogg format. | * [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://www.derekwyatt.org/vim/vim-tutorial-videos/vim-novice-tutorial-videos/ Tutorial Videos] - Covering the basics up to advanced topics. | ||
+ | |||
+ | ====Games==== | ||
+ | * [http://vim-adventures.com/ Vim Adventures] | ||
+ | * [http://vimgolf.com/ VimGolf] | ||
===Example configurations=== | ===Example configurations=== | ||
Line 309: | Line 342: | ||
* [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] | * [http://www.jukie.net/~bart/conf/vimrc Bart Trojanowski] | ||
+ | * [https://github.com/spf13/spf13-vim Steve Francia'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] | ||
===Other=== | ===Other=== | ||
* [http://www.gentoo-wiki.info/HOWTO_VIM HOWTO Vim] - Gentoo wiki article which this article was based on (author unknown). | * [http://www.gentoo-wiki.info/HOWTO_VIM HOWTO Vim] - Gentoo wiki article which this article was based on (author unknown). | ||
* [http://bytefluent.com/vivify/ Vivify] - A ColorScheme Editor for Vim | * [http://bytefluent.com/vivify/ Vivify] - A ColorScheme Editor for Vim |
Revision as of 11:40, 3 October 2013
zh-CN:Vim zh-TW:Vim "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 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.
Contents
Installation
Install the command line version with the vim package, or you can install the GUI version (which also provides vim
) by installing the gvim package.
- The 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 gvim package instead (it includes the
vim
binary as well). Theherecura-stable
unofficial repository also provides a couple different Vim / gVim variants:
$ pacman -Slq herecura-stable | grep vim
vim-cli vim-gvim-gtk vim-gvim-motif vim-gvim-qt vim-gvim-x11 vim-rt vim-tiny
Usage
This is a basic overview on how to use Vim. Alternately, running vimtutor
or gvimtutor
will launch vim's tutorial, which takes about 25-30 minutes.
Vim has four different modes:
- Command mode: keystrokes are interpreted as commands.
- 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
If you start Vim with:
$ vim somefile.txt
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.
s
will replace a character, S
will replace a line), other times they are completely different commands (j
will move down, J
will join two lines).You insert text (stick it before the cursor) with the i
command. I
(uppercase i) inserts text at the beginning of the line. You append text (place text after the cursor, what most people expect) with a
. Typing A
will place the cursor at the end of the line.
Return to command mode at any time by pressing Esc
.
Moving around
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.
In Vim you can move down by pressing j
. You can remember this because the “j” hangs down. You move the cursor back up by pressing k
. Left is h
(it's left of the “j”), and right is l
(lowercase L).
^
will put the cursor at the beginning of the line, and $
will place it at the end.
^
and $
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.To advance a word, press the w
key. 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, b
is used. Once again, B
will include more characters in what Vim considers a word. To advance to the end of a word, use e
, E
includes more characters.
To advance to the beginning of a sentence, (
will get the job done. )
will do the opposite, moving to the end of a sentence. For an even bigger jump, {
will move the the beginning a whole paragraph. }
will advance to the end of a whole paragraph.
To advance to the header (top) of the screen, H
will get the job done. M
will advance to the middle of the screen, and L
will advance to the last (bottom). gg
will go to the beginning of the file, G
will go to the end of the file. Ctrl+D
will let you scroll page by page.
Repeating commands
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 s
command). For example, pressing 3i
then “Help! ” then Esc
will print “Help! Help! Help!“. Pressing 2}
will advance you two paragraphs. This comes in handy with the next few commands…
Deleting
The x
command will delete the character under the cursor. X
will delete the character before the cursor. This is where those number functions get fun. 6x
will delete 6 characters. Pressing .
(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 3x
, move to the next "foobar" and hit .
(dot).
The d
will tell Vim that you want to delete something. After pressing d
, you need to tell Vim what to delete. Here you can use the movement commands. dW
will delete up to the next word. d^
will delete up unto the beginning of the line. Prefacing the delete command with a number works well too: 3dW
will delete the next three words. D
(uppercase) is a shortcut to delete until the end of the line (basically d$
). Pressing dd
will delete the whole line.
To delete then replace the current word, place the cursor on the word and execute the command cw
. This will delete the word and change to insert mode. To replace only a single letter use r
.
Undo and redo
Vim has a built-in clipboard (also known as a buffer). Actions can be undone with u
and redone with Ctrl+r
.
Visual mode
Pressing v
will put you in visual mode . Here you can move around to select text, when you’re done, you press y
to yank the text into the buffer (copy), or you may use c
to cut. p
pastes after the cursor, P
pastes before. V
, Visual Line mode, is the same for entire lines. Ctrl+v
is for blocks of text.
Search and replace
To search for a word or character in the file, simply use /
and then the characters your are searching for and press enter. To view the next match in the search press n
, press N
for the previous match.
To search and replace use the substitute :s/
command. The syntax is: [range]s///[arguments]
. For example:
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 :g/
command to search for patterns and then execute a command for each match. The syntax is: [range]:g//[cmd]
.
Command Outcome :g/^#/d Delete all lines that begins with # :g/^$/d Delete all lines that are empty
Saving and quitting
To save and/or quit, you will need to use Ex mode. Ex mode commands are preceded by a :
. To write a file use :w
or if the file doesn’t have a name :w filename
. Quitting is done with :q
. If you choose not to save your changes, use :q!
. To save and quit :x
.
Additional commands
- Pressing
s
will erase the current letter under the cursor, and place you in insert mode.S
will erase the whole line, and place you in insert mode. -
o
will create a newline below the line and put you insert mode,O
will create a newline above the line and put you in insert mode. -
yy
will yank an entire line -
cc
will delete the current line and place you in insert mode. -
*
will highlight the current word andn
will search it
Configuration
Vim's user-specific configuration file is located in the home directory: ~/.vimrc
, and files are located inside ~/.vim/
The global configuration file is located at /etc/vimrc
. Global files are located inside /usr/share/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:
# mv /etc/vimrc /etc/vimrc.bak # cp /usr/share/vim/vim74/vimrc_example.vim /etc/vimrc
Wrap searches
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.
set wrapscan
Spell checking
set spell
With this setting, Vim will highlight incorrectly spelled words. Place the cursor on a misspelled word and enter z=
to view spelling suggestions.
Only English language dictionaries are installed by default, more can be found in the official repositories. To get the list of available languages type:
# pacman -Ss vim-spell
Language dictionaries can also be found at the Vim FTP archive. Put the downloaded dictionar(y/ies) into the ~/.vim/spell
folder and set the dictionary by typing: :setlocal spell spelllang=LL
- 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. For spell checking of languages other than English, simply replaceen_us
with the value appropriate for your language. - 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 in
*.txt
, create the file/usr/share/vim/vimfiles/ftdetect/plaintext.vim
, and insert the lineautocmd BufRead,BufNewFile *.txt setfiletype plaintext
into that file. Next, insert the lineautocmd FileType plaintext setlocal spell spelllang=en_us
into your~/.vimrc
or/etc/vimrc
, and then restart Vim.
Syntax highlighting
To enable syntax highlighting (Vim supports a huge list of programming languages):
:filetype plugin on :syntax on
Using the mouse
Vim has the ability to make use of the mouse, but requires xterm's mouse reporting feature.
- See the example .vimrc below to enable the mouse.
- Use xterm. In your console:
export TERM=xterm-256color
orexport TERM=xterm
Notes:
- 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
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.
Example ~/.vimrc
An example Vim configuration.
Plugins
Adding plugins to vim can increase your productivity. The group vim-plugins has many plugins to choose from(there are more in the repos though ie: vim-supertab).
pacman -Ss vim-plugins
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. Multiple steps are required to search a code base.
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
Create a file which contains the files you wish cscope to index(Cscope can handle many languages but this example finds .c, .cpp, and .h files):
cd /path/to/projectfolder/ find . -type f -print | grep -E '\.(c(pp)?|h)$' > cscope.files
Create database files that cscope will read:
cscope -bq
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.
Usefull 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>
Merging files (vimdiff)
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 vimdiff file1 file2
. Some example commands are found below:
]c
- next difference
[c
- previous difference
Ctrl+w+w
- switch windows
i
- enter Insert mode
Esc
- exit Insert mode
p
- paste a line
do
- diff obtain. when cursor is on a highlighted difference and changes from other window will move into the current one
dp
- diff put. same as diff obtain but will put the changes from current windows into the other one
zo
- open folded text
zc
- close folded text
:diffupdate
- re-scan the files for differences
yy
- copy a line
:wq
- save and exit the current window
:wqa
- save and exit both windows
:q!
- exit without saving
Once your file has been correctly edited taking account changes in file.pacnew:
# mv file file.bck # mv file.pacnew file
Check if your new file is correct, then remove your backup:
# rm file.bck
Vim tips
Specific user tricks to accomplish tasks.
Line numbers
- Show line numbers by
:set number
. - Jump to line number
:<line number>
.
Substitute on lines
To only substitute between certain lines:
:n,ns/one/two/g
For example, to replace instances of 'one' with 'two' between lines 3 and 4, one would execute:
:3,4s/one/two/g
Make Vim restore cursor position in files
If you want the cursor to appear in its previous position after you open a file, add the following to your ~/.vimrc
:
if has("autocmd") au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif endif
See also this tip in Vim Wiki.
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. Take note that if you set it to zero, you won't be able to see the bottom horizontal scrollbar, if you have one. Put the following line in ~/.vimrc
:
set guiheadroom=0
Replace vi command with vim
Create an alias for vi
to vim
.
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:
:%s/^M//g
Pay attention, "^" is the control letter, press Ctrl+Q
to get the right "^".
Alternatively, install the package dos2unix from the official repositories, and run dos2unix <file name here>
.
See also
Official
Tutorials
- vi Tutorial and Reference Guide
- Graphical vi-Vim Cheat Sheet and Tutorial
- Vim Introduction and Tutorial
- Open Vim - Collection of Vim learning tools
- Learn Vim Progressively
- know vim
Videos
- Vimcasts - Screencasts in .ogg format.
- Tutorial Videos - Covering the basics up to advanced topics.
Games
Example configurations
- nion's
- A detailed configuration from Amir Salihefendic
- Bart Trojanowski
- Steve Francia's Vim Distribution
- W4RH4WK's Vim configuration
- Fast vimrc/colorscheme from askapache