Difference between revisions of "Vim (正體中文)"

From ArchWiki
Jump to: navigation, search
m
(update link(s) (avoid redirect))
(7 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{i18n|Vim}}
+
[[Category:正體中文]]
[[Category: 正體中文)]]
+
[[Category:Development (正體中文)]]
 +
[[Category:Text editors (正體中文)]]
 +
[[en:Vim]]
 +
[[es:Vim]]
 +
[[de:Vim]]
 +
[[it:Vim]]
 +
[[lt:Vim]]
 +
[[ru:Vim]]
 +
[[zh-CN:Vim]]
 +
{{translateme}}
 +
「[http://www.vim.org/about.php Vim] 是個進階文字編輯器,旨在提供 UNIX 上正統編輯器 'vi' 的強大功能,並加上更完整的功能集合。」
  
Vim ('''V'''i '''IM'''proved)是Vi衍生的文字編輯器。因為它陡峭的學習曲線及不親切的介面而臭名遠播,但由於它的效率,多元化的插件及客製化的選項,Vim是 *nix 用戶眼中其中一個最好的文字編輯器(與Emacs齊名)。gVim是Vim的圖形版本,它為用戶提供了一個選單。
+
Vim 注重鍵盤的使用,並提供許多有用功能,例如語法標亮和腳本功能。Vim 不像 nano 或 pico 這些簡易的文字編輯器,它需要一段時間去學習,並得花上大量的時間才能精通。
+
<nowiki>*</nowiki>''Note that The Cult of Vi has determined that using emacs may cause dry mouth, blurred vision, drowsiness, dizziness, profuse sweating, tremors, sexual problems, headache, nausea and abdominal pain.''
+
  
==安裝==
+
== 安裝 ==
* <tt>vim</tt>依賴<tt>vi</tt>,因此vi需要先安裝。但vi是基本安裝的其中一部份,所以大部份用戶應該已把它安裝好。
+
  
<pre>
+
[[pacman (正體中文)|安裝]]指令列介面的 {{Pkg|vim}} 軟體包,或安裝 GUI 版本 (同時包含 {{ic|vim}}) 的 {{Pkg|gvim}} 軟體包。
pacman -S vim
+
</pre>
+
  
==設置==
+
{{註記|
vim的設定檔是用戶的家目錄(~/)下的 .vimrc。一個 .vimrc的範例可以在 /etc/vimrc 中找到。
+
* {{Pkg|vim}} 軟體包的目的在於輕量化,因此它不支援 Python, Lua 和 Ruby 直譯,也不支援 X 伺服器 (代表它不支援來自 X 剪貼簿的複製與貼上)。如果您需要這些選項,請改安裝 {{Pkg|gvim}} 軟體包 (它同時包含 {{ic|vim}} 執行檔)。{{ic|herecura-stable}} 非官方軟體庫也提供一些不同的 Vim / gVim 變形:
 +
{{hc|$ pacman -Slq herecura-stable &#124; grep vim|
 +
vim-cli
 +
vim-gvim-gtk
 +
vim-gvim-motif
 +
vim-gvim-qt
 +
vim-gvim-x11
 +
vim-rt
 +
vim-tiny
 +
}}
  
<pre>
+
* KDE 上使用來自官方軟體庫的 {{Pkg|gvim}} 可能會出現某些視覺上的問題。若出現這類型的狀況,可以安裝來自 {{ic|herecura-stable}} 的 {{ic|vim-gvim-qt}},或是 AUR 的 {{AUR|vim-qt}}
"Sample .vimrc
+
}}
set nocompatible
+
set showmatch
+
set incsearch
+
set ignorecase 
+
set smartcase
+
set history=100
+
set backspace=eol,start,indent
+
set ruler
+
set tabstop=4
+
set shiftwidth=4
+
set expandtab
+
set virtualedit=all
+
set background=dark
+
set vb t_vg=
+
set mouse=v
+
set textwidth=79
+
set formatoptions=tcrq
+
</pre>
+
  
* 安裝 gVim (與vim相似但擁有gtk2圖形介面及根據 /etc/gvimrc 及 ~/.gvimrc 去設置)
+
==用法==
<pre>
+
pacman -S gvim
+
</pre>
+
  
* 這裏有一系列常用的插件,並可通過 pacman 安裝。
+
這裡有如何使用 Vim 的簡短概覽。執行 {{Ic|vimtutor}} 或 {{Ic|gvimtutor}} 會啟動 vim 自己的教學,完整跑一遍會花上約 25-30 分鐘。
<pre>
+
pacman -S vim-plugins
+
</pre>
+
  
==VIM 即時使用指南==
+
Vim 有四種不同的模式:
  
 +
* 指令模式 (Command mode):鍵入字串會當作指令執行。
 +
* 輸入模式 (Insert mode):鍵入字串會輸入至檔案。
 +
* 視覺模式 (Visual mode):鍵入選擇、剪下或複製文字
 +
* Ex 模式:額外功能的輸入模式 (例如儲存檔案、取代文字...)
  
===如何啟動vim===
+
===一般編輯===
  
* 啟動vim編輯一個文件(新文件或已存在的文件)
+
If you start Vim with:
  
  vim ''filename''
+
  $ vim somefile.txt
* 啟動vim並開新文件
+
vim
+
  
(當您儲存該文件時,您需要為它命名。)
+
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. It has a difficult 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).}}
  
Vim 有很多模式,以下是最基本的:
+
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.
  
* Insert mode, in which anything you type (except some special keys) will appear on the screen and become part of your file buffer. There are many insert modes. The most basic form of insert mode is entered by pressing '''i'''.
+
Return to command mode at any time by pressing {{ic|Esc}}.
* Command mode (also called normal mode), in which your key strokes are interpreted as commands. Command mode is entered by pressing <ESC>
+
* '''ex''' mode, where you may save a file, split the screen, open additional files, etc. '''ex''' mode commands are preceded by a colon, ''':'''
+
* Visual mode, which allows you to expediently cut, copy and paste large areas of text with the keyboard or mouse. Visual mode is entered by pressing '''v'''
+
Open a new text file with vim:
+
vim mytext
+
After you start vim, you're in command mode.
+
  
*Switch between modes
+
===到處移動===
  
1. From command mode to insert mode, press '''i'''
+
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.
  
Enter some text.
+
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''').
  
2. from insert mode to command mode, press '''<ESC>'''
+
{{ic|^}} will put the cursor at the beginning of the line, and {{ic|$}} will place it at the end.
  
You are now in command mode. Vim is waiting for your commands. Notice if you try typing, you get weird and unexpected results, because, well, you need to learn some commands, and Vim is not in insert mode.
+
{{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.}}
  
3. Press '''<ESC>''' again to make sure you are truly in command mode and press ''':''' (colon)
+
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.
  
Now you are in '''ex''' mode, which will allow us to save your first file. Type:
+
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.
wq
+
for '''w'''rite and '''q'''uit.
+
  
Your file is written and vim will exit. You have just utilized 3 of the main modes of vim.
+
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.
  
We'll focus on visual mode later.
+
===重複指令===
  
===Navigation===
+
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…
  
In both the command mode and the insert mode, the arrow keys function to move the cursor, and with gvim you can mouse click to get to a new position. However, this is not '''''the vim way'''''. The most effective way of moving the cursor is to first enter the command mode by pressing ESC and then use vim's cursor-moving commands to move around. The 4 basic commands are
+
===刪除===
  
* '''j''' move down one line
+
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).
  
* '''k''' move up one line
+
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.
  
* '''h''' move left one character
+
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}}.
  
* '''l''' move right one character
+
===取消和重做===
  
Remember: these commands work only in command mode. At first you may feel a bit uncomfortable. After you get familiar using these commands you will stick to them and forget the arrow keys.
+
Vim has a built-in clipboard (also known as a buffer). Actions can be undone with {{ic|u}} and redone with {{ic|Ctrl+r}}.
+
Advanced movement:
+
  
* '''0''' (zero) move to the first character of a line
+
===視覺模式===
  
* '''$''' move to the last character of a line
+
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.
  
* '''w''' move to the first character of the next word
+
{{Note|Whenever you delete something, that something is placed inside a buffer and is available for pasting.}}
  
* '''e''' move to the last character of the next word
+
===搜尋和取代===
  
* '''(''' move to the beginning of the previous sentence
+
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.
  
* ''')''' move to the beginning of the next sentence
+
To search and replace use the substitute {{ic|:s/}} command. The syntax is: {{Ic|[range]s///[arguments]}}. For example:
  
* '''{''' move to the beginning of the current paragraph
+
{{bc|
 +
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
 +
}}
  
* '''}''' move to the beginning of the next paragraph
+
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]}}.
  
* '''PGUP''' or '''<CTRL>F''' move up one page
+
{{bc|
 +
Command  Outcome
 +
:g/^#/d  Delete all lines that begins with #
 +
:g/^$/d  Delete all lines that are empty
 +
}}
  
* '''PGDOWN''' or '''<CTRL>B''' move down one page
+
===儲存和退出===
  
* '''H''' move cursor to the top left
+
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}}.
  
*  '''L''' move to the bottom of the screen.
+
=== 額外指令 ===
  
* ''':25''' go to line 25
+
# 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
  
* '''gg''' move to beginning of file
+
==設定==
  
* '''G''' move to end of file
+
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:
  
The DELETE key always works, and the BACKSPACE key works with newly typed text in insert mode. However, it is suggested you not use them. Instead, learn to use vim's deletion commands.
+
# mv /etc/vimrc /etc/vimrc.bak
 +
# cp /usr/share/vim/vim74/vimrc_example.vim /etc/vimrc
  
1. Make sure you are in command mode by pressing '''<ESC>'''
+
===循環搜尋===
  
2. move the cursor to the character you want to delete
+
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.
  
3. press '''x''' , this character disappears
+
set wrapscan
  
'''x''' is just one of the many powerful deletion commands. Remember, try to use the cursor motion commands '''j k h l''' to locate your target, and don't leave the command mode.
+
=== 拼字檢查 ===
  
===如何插入文字===
+
set spell
  
While in command mode, move the cursor to the desired location.
+
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.
  
* '''i''' enter insert mode. This will '''i'''nsert before the current character.
+
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:
           
+
* '''a''' enter append mode. This will '''a'''ppend text after the current character.
+
  
* <code>'''I'''</code> move the cursor to the beginning of the current line and subsequently enter insert mode.
+
  # pacman -Ss vim-spell
   
+
* '''A''' move the cursor to the end of the current line and subsequently enter insert append mode.
+
+
* '''o''' create a new blank line ''below'' the current line into which you can insert text.
+
+
* '''O''' (capital O)  To create a new line ''above'' the current line.
+
  
* '''cc''' cut and replace the entire current line with a new line.
+
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}}
  
* '''c$''' cut and replace everything from the current cursor position to the end of the line.  
+
{{Tip|
+
* 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.
* '''c'''0 replace everything from the current cursor position to the beginning of the line.  
+
* 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.}}
  
To re-enter command mode, press <esc>
+
===語法標亮===
  
===如何"剪下"、"複製"及"貼上"===
+
To enable syntax highlighting (Vim supports a huge list of programming languages):
  
If you run the GUI version of vim, gvim, you can use mouse and the pull-down menus to do that---the same fashion with other editors. However, that is not the preferred style. You'll feel better off if you can live without a mouse.
+
:filetype plugin on
 +
:syntax on
  
1. Enter command mode by pressing ESC
+
===使用滑鼠===
  
2. Move the cursor to the line which you want to copy, by pressing j or k
+
Vim has the ability to make use of the mouse, but requires xterm's mouse reporting feature.
  
3. press
+
# See the example .vimrc below to enable the mouse.
 +
# Use xterm. In your console: {{ic|1=export TERM=xterm-256color}} or {{ic|1=export TERM=xterm}}
  
yy
+
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 {{ic|Shift}} key while selecting text.
  
to make a copy of the line, or
+
===讓方向鍵通過斷行===
  
dd
+
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 cut it and make a copy
+
The default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file.
  
4. now move cursor (by pressing k or j) to the the location where you want to put this copy
+
=== ~/.vimrc 範例 ===
  
5. press
+
一個範例 [[Vim/.vimrc|Vim 設定]]。
  
  p
+
==插件==
 +
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.
  
to put the buffer after the current line, or
+
Install the {{Pkg|cscope}} package.
  
  P
+
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
  
to put the buffer before the current line
+
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.}}
  
If you want to copy or cut several lines, put a number before the yy or dd command, like
+
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
  
  8yy
+
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>
  
to copy 8 lines.
+
===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.
  
===CUT, COPY and PASTE with Visual mode===
+
Install the {{Pkg|vim-taglist}} package.
  
*Visual mode  is like Command mode, but the movement commands extend a highlighted areaWhen a non-movement command is used, it is executed for the highlighted area. Cutting, copying and pasting large sections of text is more efficient in visual mode.
+
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>
  
Hit '''v''' to enter visual mode from command mode, then use the cursor to go up or down. As you do, the lines of text will become highlighted. (You may also use the mouse to highlight areas of text)
+
==合併檔案 (vimdiff)==
  
To copy the highlighted section or 'yank':
+
Vim includes a diff editor, a program that aids the merging of differences between two (or more, with limited usefulness) files. {{ic|vimdiff}} opens a horizontally multi-paned view that colorfully highlights differences, each pane containing one of the files to be examined/edited. Vim has [[#Usage|several modes]], two important ones being '''Insert mode''', which lets text be edited, and '''Command mode''', which lets the cursor be moved move across windows and lines. Begin by running {{ic|vimdiff file1 file2}}. Some example commands follow.
y
+
To cut the highlighted section or 'delete':
+
d
+
To paste or 'put'
+
p
+
to place it before, or
+
P
+
for after.
+
  
===Undo and Redo===
+
;{{ic|]c}}                          : next difference
Now that you have learned how to cut and delete, you may need to undo some mistakes
+
;{{ic|[c}}                          : previous difference
u
+
;{{ic|Ctrl+w+w}}                    : switch windows
will undo the last function. Pressing it repeatedly will undo successive functions.
+
;{{ic|i}}                            : enter Insert mode
Likewise, use
+
;{{ic|Esc}}                          : exit Insert mode
Ctrl-R
+
;{{ic|p}}                            : paste
to redo.
+
;{{ic|do}}                          : diff obtain. When the cursor is on a (highlighted) difference, copies the changes from the other window to the current one.
 +
;{{ic|dp}}                          : diff put. Inverse of diff obtain; copies the changes from current windows to 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|dd}}                          : cut 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 into account changes in file.pacnew:
假設您想在您的文件中搜尋整個詞"apple"
+
# mv file file.bck
 +
# mv file.pacnew file
 +
Check whether your new file is correct, then remove your backup:
 +
# rm file.bck
  
1. 請確定你正在命令模式下,按下ESC建
+
==Vim 提示==
  
2. 輸入
+
Specific user tricks to accomplish tasks.
  
/apple
+
===行號===
  
然後按ENTER,若果找到apple,游標會移到第一個出現的apple,並把它反白。當您鍵入"/"時,這個apple及文件中所有的apple都會出現在屏幕的底部。
+
# Show line numbers by {{Ic|:set number}}.
 +
# Jump to line number {{Ic|:<line number>}}.
  
3. 在您找到第一個apple後,您可以鍵入
+
===Substitute on lines===
  
n
+
To only substitute between certain lines:
  
去搜尋其他apple
+
:''n'',''n''s/one/two/g
  
 +
For example, to replace instances of 'one' with 'two' between lines 3 and 4, one would execute:
  
Suppose you want to search for the word under the current cursor position there's no need to type the word. Instead
+
:3,4s/one/two/g
  
1. Make sure you are in command mode by hitting ESC
+
===Make Vim restore cursor position in files===
  
2. type
+
If you want the cursor to appear in its previous position after you open a file, add the following to your {{ic|~/.vimrc}}:
  
  *
+
{{bc|<nowiki>
 +
if has("autocmd")
 +
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif
 +
endif
 +
</nowiki>}}
  
this will highlight the word under the curser. Then just like before use
+
See also [http://vim.wikia.com/wiki/Restore_cursor_to_file_position_in_previous_editing_session this] tip in Vim Wiki.
  
  n
+
===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.
  
to jump to the next occurence of word you're searching for.
+
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
  
'''Hint:''' With default settings the search stops when you hit the end of the file. To make searches wrap around the end of a file add
+
===用 vim 取代 vi 指令===
  
  set wrapscan
+
Create an [[Bash#Aliases|alias]] for {{ic|vi}} to {{ic|vim}}.
  
to your ~/.vimrc.
+
==疑難排解==
  
===How to substitute text===
+
==="^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.
  
First make sure you're in command mode by pressing '''<ESC>'''.
+
Solution:
 +
Replace all "^M" using the command:
  
* to replace a single character, move the cursor over the character and hit '''r''' followed by its replacement.
+
{{bc|:%s/^M//g}}
  
The following commands utilize '''ex'''. Recall from above that '''ex''' commands are all preceded by a colon, ''':'''
+
Pay attention, "^" is the control letter, press {{ic|Ctrl+Q}} to get the right "^".
  
* replace first occurrence of old in current line with new
+
Alternatively, install the package {{pkg|dos2unix}} from the official repositories, and run {{ic|dos2unix <file name here>}}.
  
:s/old/new/
+
==另請參閱==
  
* replace all occurrence of old in current line with new
+
===官方===
 +
* [http://www.vim.org/ 首頁]
 +
* [http://vimdoc.sourceforge.net/ 文件]
 +
* [http://vim.wikia.com Tips Wiki]
  
:s/old/new/g
+
===教學===
 +
* [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://blog.interlinked.org/tutorials/vim_tutorial.html Vim Introduction and Tutorial]
 +
* [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]
  
* replace the first occurrence of old in each line between line n1 and n2 with new
+
====影片====
 +
* [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.
  
:n1,n2s/old/new/
+
====遊戲====
 +
* [http://vim-adventures.com/ Vim Adventures]
 +
* [http://vimgolf.com/ VimGolf]
  
* replace all occurrence of oldbetween line n1 and n2 with new
+
===範例設定===
 +
* [http://nion.modprobe.de/setup/vimrc nion's]
 +
* [http://amix.dk/vim/vimrc.html A detailed configuration from Amir Salihefendic]
 +
* [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]
  
:n1,n2s/old/new/g
+
===其他===
 
+
* [http://www.gentoo-wiki.info/HOWTO_VIM HOWTO Vim] - Gentoo wiki article which this article was based on (author unknown).
* replace all occurrence of old in the whole buffer with new, prompt for confirmation.
+
* [http://bytefluent.com/vivify/ Vivify] - A ColorScheme Editor for Vim
 
+
:1,$s/old/new/gc
+
 
+
* replace all occurrence of old in the whole buffer with new, prompt for confirmation.
+
 
+
:%s/old/new/gc
+
 
+
===如何離開Vim===
+
 
+
* To save and exit: press '''<ESC>''' to enter command mode, then use '''ex''':
+
 
+
:wq
+
or
+
:x
+
or, from command mode, without '''ex''':
+
ZZ
+
 
+
* to save your file as '''newname''' before exiting:
+
 
+
press '''<ESC>''' to enter command mode, then type
+
 
+
:wq newname
+
 
+
* To exit without saving, press '''<ESC>''', then type
+
 
+
:q
+
 
+
* Forced quit
+
 
+
If :q doesn't work, it's probably because you didn't save the change. If you want to save, use :wq. If you don't want to save the changes, type
+
 
+
:q!
+
 
+
== Line Numbers and Jumping to Lines ==
+
* Showing all line numbers - to show line numbers for a document, in insert mode, type ''':set number'''
+
* Jumping to a line - If you want to jump to a particular line in a file, in insert mode, type ''':<line number>''', for example, :43 to jump to line #43.
+
== Comparing or Merging 2 or more files (vimdiff and vsplit)==
+
Occasionally, you may need to compare or merge multiple files.
+
* Hypothetical 1
+
While editing ~/.bashrc,
+
vim ~/.bashrc
+
you recall there are some global environment variables set within /etc/profile that you would like to merge into ~/.bashrc.
+
 
+
Simply enter ex mode and invoke vsplit:
+
:vsplit
+
which will split the screen, and then re-enter ex mode and load /etc/profile with the ''e'' command:
+
:e /etc/profile
+
to load /etc/profile into the newly split window.
+
 
+
Recall from above that
+
CTRL-w
+
and then '''h''' and '''l''' will allow you to switch windows.
+
 
+
Subsequently invoking vsplit from ex mode will again split your sessions, so it is possible to compare 3, 4 or more files.
+
 
+
* Hypothetical 2
+
After a ''pacman -Syu'', pacman warns you that there are files to be merged, saved with the extension ''.pacnew''
+
 
+
Invoke vimdiff from the shell:
+
$ vimdiff ''filename filename.pacnew''
+
Recall from above that
+
CTRL-w
+
and then '''h''' and '''l''' will allow you to switch windows.
+
 
+
Cursor location will indicate the window for which commands will affect.
+
 
+
==Spell checking==
+
Vim's built-in spell checking (available since version 7) can be enabled by entering
+
<pre>
+
:set spell
+
</pre>
+
Only English language dictionaries are installed by default, but you can find many more in the [http://ftp.vim.org/vim/runtime/spell/ vim ftp archive].
+
After downloading the spl files for the given language (e.g. hu.cp1250.spl, hu.iso-8859-2.spl and hu.utf-8.spl for Hungarian) into ~/.vim/spell, you can run
+
<pre>
+
:set spell spelllang=LL
+
</pre>
+
to activate spell checking for the selected language (i.e. ':set spell spelllang=hu' for the above mentioned example).
+
For more information, see
+
<pre>
+
:help spell
+
</pre>
+
in vim or read [http://vimdoc.sourceforge.net/htmldoc/spell.html the html documentation] on vim's sourceforge page.
+
 
+
==Vim Tutor==
+
For more, run:
+
<pre>
+
vimtutor
+
</pre>
+
from a shell. Vim will open the tutor file.
+
 
+
==External links==
+
* [http://www.vim.org/ The Official website]
+
* [http://vimdoc.sourceforge.net/ Vim Documentation]
+
* [http://vim.wikia.com Vim Tips Wiki]
+
* [http://usalug.org/vi.html Vi tutorial and reference]
+

Revision as of 11:57, 24 February 2014

Tango-preferences-desktop-locale.pngThis article or section needs to be translated.Tango-preferences-desktop-locale.png

Notes: please use the first argument of the template to provide more detailed indications. (Discuss in Talk:Vim (正體中文)#)

Vim 是個進階文字編輯器,旨在提供 UNIX 上正統編輯器 'vi' 的強大功能,並加上更完整的功能集合。」

Vim 注重鍵盤的使用,並提供許多有用功能,例如語法標亮和腳本功能。Vim 不像 nano 或 pico 這些簡易的文字編輯器,它需要一段時間去學習,並得花上大量的時間才能精通。

安裝

安裝指令列介面的 vim 軟體包,或安裝 GUI 版本 (同時包含 vim) 的 gvim 軟體包。

註記:
  • vim 軟體包的目的在於輕量化,因此它不支援 Python, Lua 和 Ruby 直譯,也不支援 X 伺服器 (代表它不支援來自 X 剪貼簿的複製與貼上)。如果您需要這些選項,請改安裝 gvim 軟體包 (它同時包含 vim 執行檔)。herecura-stable 非官方軟體庫也提供一些不同的 Vim / gVim 變形:
$ pacman -Slq herecura-stable | grep vim
vim-cli
vim-gvim-gtk
vim-gvim-motif
vim-gvim-qt
vim-gvim-x11
vim-rt
vim-tiny
  • KDE 上使用來自官方軟體庫的 gvim 可能會出現某些視覺上的問題。若出現這類型的狀況,可以安裝來自 herecura-stablevim-gvim-qt,或是 AUR 的 vim-qtAUR

用法

這裡有如何使用 Vim 的簡短概覽。執行 vimtutorgvimtutor 會啟動 vim 自己的教學,完整跑一遍會花上約 25-30 分鐘。

Vim 有四種不同的模式:

  • 指令模式 (Command mode):鍵入字串會當作指令執行。
  • 輸入模式 (Insert mode):鍵入字串會輸入至檔案。
  • 視覺模式 (Visual mode):鍵入選擇、剪下或複製文字
  • Ex 模式:額外功能的輸入模式 (例如儲存檔案、取代文字...)

一般編輯

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.

Note: Vim is an example of classic Unix-style ware. It has a difficult 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 (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.

到處移動

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.

Note: ^ 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.

重複指令

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…

刪除

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.

取消和重做

Vim has a built-in clipboard (also known as a buffer). Actions can be undone with u and redone with Ctrl+r.

視覺模式

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.

Note: Whenever you delete something, that something is placed inside a buffer and is available for pasting.

搜尋和取代

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

儲存和退出

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.

額外指令

  1. 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.
  2. 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.
  3. yy will yank an entire line
  4. cc will delete the current line and place you in insert mode.
  5. * will highlight the current word and n will search it

設定

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

循環搜尋

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

拼字檢查

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

Tip:
  • 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 replace en_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 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 syntax highlighting (Vim supports a huge list of programming languages):

:filetype plugin on
:syntax on

使用滑鼠

Vim has the ability to make use of the mouse, but requires xterm's mouse reporting feature.

  1. See the example .vimrc below to enable the mouse.
  2. Use xterm. In your console: export TERM=xterm-256color or export 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.

讓方向鍵通過斷行

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.

~/.vimrc 範例

一個範例 Vim 設定

插件

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
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.

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>

合併檔案 (vimdiff)

Vim includes a diff editor, a program that aids the merging of differences between two (or more, with limited usefulness) files. vimdiff opens a horizontally multi-paned view that colorfully highlights differences, each pane containing one of the files to be examined/edited. Vim has several modes, two important ones being Insert mode, which lets text be edited, and Command mode, which lets the cursor be moved move across windows and lines. Begin by running vimdiff file1 file2. Some example commands follow.

]c  
next difference
[c  
previous difference
Ctrl+w+w  
switch windows
i  
enter Insert mode
Esc  
exit Insert mode
p  
paste
do  
diff obtain. When the cursor is on a (highlighted) difference, copies the changes from the other window to the current one.
dp  
diff put. Inverse of diff obtain; copies the changes from current windows to the other one.
zo  
open folded text
zc  
close folded text
:diffupdate 
re-scan the files for differences
yy  
copy a line
dd  
cut 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 into account changes in file.pacnew:

# mv file file.bck
# mv file.pacnew file

Check whether your new file is correct, then remove your backup:

# rm file.bck

Vim 提示

Specific user tricks to accomplish tasks.

行號

  1. Show line numbers by :set number.
  2. 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

用 vim 取代 vi 指令

Create an alias for vi to vim.

疑難排解

"^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>.

另請參閱

官方

教學

影片

遊戲

範例設定

其他

  • HOWTO Vim - Gentoo wiki article which this article was based on (author unknown).
  • Vivify - A ColorScheme Editor for Vim