Introduction to Programming in C/C++ with Vim Written By: Kmj 用Vim進行C/C++編程介紹
Vi has been one of the most, if not the most, popular editing tools for programmers since Bill Joy first created it. 自從Bill Joy最初寫出Vi編輯器以來, Vi就一直是編程者中廣為流傳的(即使不說 是最流行的)編程工具.
Over the years it has evolved, and the current version of vim has many capabilities which make a programmer's life easy. Listed below is a brief description of some tools which have made so many programmers loyal to vi and vim. The purpose of this document is to inform linux newbies of, and introduce them to these tools, not necessarily to be the definitive source of information on them. In most cases, interested readers should check the noted "extra information" sources. Vi產生以來, 歷經不斷革新, 現在最新版的Vim已經具有了非常多的功能, 這些功 能使程序員能更加輕松, 便捷地使用它們. 下面是它的一些功能描述, 正是這些 豐富強大的功能使vi和vim成為無數程序員的至愛. 本文志在向linux的初學者們 介紹這些功能, 而不是追溯其歷史淵源. 對此感興趣的讀者可以 查看"extra information"獲得這些信息.
(Note that throughout this paper, I may use the name vi when referring to vim. Some options may only be compatible with vim, and not vi.) (注: 本文中使用vi兼指vim, 但有一些選項可能只有vim支持)
Ctags Ctags is a program that comes with vim. Basically, it's purpose is to help a programmer get to various parts of his program with relative ease. The typical method of running ctags is by simply typing the following in your source directory: Ctags是vim的伴生工具, 它的基本功能是讓程序員能自由穿梭於程序的不同部分( 如從一個函數名跳轉到該函數的定義處), 最通常的用法是象下面這樣以源程序目 錄下所有文件作為參數.
[/home/someuser/src]$ ctags * This will create a 'tags' file in you current directory with the following information for all C or C++ files in you directory. This file contains a listing of the following objects: 該命令會在當前目錄下創建一個名為`tags'的文件, 該文件包含了你當前目錄下 所有的C/C++文件中的相關信息, 具體來說包含以下對象的信息:
macros defined by #define enumerated values function definitions, prototypes, and declarations class, enum, struct, and union names namespaces typedefs variables (definitions and declarations) class, struct, and union members 由#define定義的宏 枚舉值 函數定義, 原型和聲明. 類, 枚舉類型名, 結構名和聯合結構名 名字空間 類型定義 變量(定義和聲明) 類,結構和聯合結構的成員
Vim then uses this file to help you locate these tagged items. This can be done in a few ways. First, one can open vim to the location of a tagged object. To do this, run vim with the '-t' flag and the tag-name as an argument . For example: 接下來, Vim就通過該文件中的信息定位這些程序元素. 有幾種方法可以對這些元 素進行定位. 第一種方法, 可以在命令行上啟動vi程序時通過-t選項加要跳轉的程序 元素名, 如下:
[/home/someuser/src]$ vi -t foo_bar
would open to the file containing the definition of foo_bar at that line . 將會打開包含foo_bar定義的文件並定位到定義foo_bar的那一行上.
If you are already in vi, you can enter the command by the tag-name: 如果你已經在vi編輯環境中, 也可以在底線命令行上鍵入:
:ta foo_bar
This may take you out of the file you are currently in, unless the 'autowrite ' option is enabled. (It is off by default.) For more information on autowrite , type ':h autowrite' from with vi command-mode. 該命令可能使你離開你當前打開的文件(而跳轉到包含foo_bar定義的文件的相關行 上去, 如果你已經改變了當前文件的內容而沒有存盤, 則只能在你設置了 `autowrite'時才會跳轉到該文件, 否則會給出警告, 另, autowrite可簡寫為等效 的aw, 譯者注), 欲了解`autowrite'選項的詳細信息, 可以使用在線幫助:h autowrite 命令(也可簡寫為:h aw, 譯者注)
The final way to jump to a tagged location is by typing 'Ctrl-]' in command mode while the cursor is on a specific word. For example, if you are looking at my program, and you come across a point where I call foo_bar(), you can type 'Ctrl-]', while the cursor is somewhere on that word, and it will jump to that definition. Note that 'Ctrl-]' is the escape character for telnet , so this may cause some issues if your editing files remotely. Type ':h ^]' for more information. 最後一種跳轉到一個程序元素的方法是在(命令模式下)光標停在該程序元素上時按 下`CTRL-]'鍵, 如, 你在看程序時看到某處調用了一個叫foo_bar()的程序, 你 可以將光標停在foo_bar單詞上(停在該單詞任何一個字符都可, 譯者注), 然後按 下`CTRL-]'鍵, 它就會跳轉到該函數的定義處. 值得注意的是Ctrl-]碰巧是telnet 的終端符, 所以如果你在編輯遠程計算機上的文件(通常是通過telnet登錄到遠程 主機上, 譯者注), 可能會遇到一些問題. 通過在線幫助':h^]'可以了解這方面的 更多信息.(譯者: 在:h^]中關於該問題是這樣說的, 多數telnet都允許使用命令 telnet -E hostname來打開或關閉該脫字符, 或者用telnet -e escape hostname 來指定另外一個脫字符來代替^], 此外, 如果可能的話, 可以使用rsh來代替telnet 來避免這個問題, 關於telnet -E 及 telnet -e的詳情, 請參看man telnet中相關 的幫助)
Ctags can also be used with other languages (java, fortran, ...and more) and editors (emacs, NEdit, ...and more). When set up properly, this tool can make your job tremendously easier, especially when you have to jump into a large ongoing project head-first. Ctags程序也可用於其它語言寫就的源程序, 並且可以與其它的一些編輯器(如emacs , NEdit等等)協同工作. 正確地使用它, 會給你的編程工作帶來極大的便利, 尤其是你在 開發一個大的項目時.
For more information: View the man page, man ctags, or view the vim help , :h ctags. 關於ctags程序的更多用法, 請參看它的相關幫助頁, man ctags, 或者通過vim的 在線幫助系統查看它的用法, :h ctags
c-style indenting c語言風格的縮進 Vi has various methods of implementing auto-indenting. The best for C and C++ programmers is, obviously, cindent mode. This is a very versatile tool which gives the programmer much control over the look and feel of his source code, without any effort (except the effort of initial setup, of course ). To enable c-indenting, just type ':set cindent' from the command mode . The most important thing to note is that cindenting makes use of shiftwidth , not tabstops. The default shiftwidth is 8. In order to change this, enter ':set shiftwidth=x' where x is the desired number of spaces to shift. Vi有幾種不同的方法實現自動縮進. 對於C/C++程序員來說, 最好的方法顯然是 cindent模式, 該模式具有多種功能幫助程序員美化程序的外觀, 無需任何額外的 工作(當然, 設置正確的模式:se cindent是必需的). 欲打開該模式, 只需鍵入命 令:set cindent(所有的set都可以簡寫為se, 雖然只節省了一個字符, 譯者注) 需要注意的是cindent控制縮進量是通過shiftwidth選項的值, 而不是通過tabstop 的值, shiftwidth的默認值是8(也就是說, 一個縮進為8個空格, 譯者注), 要改變 默認的設置, 可以使用`:set shiftwidth=x'命令, 其中x是你希望一個縮進量代表 的空格的數目.
The default cindent options tend to be nice, but if you find your program indenting in some way that is annoying, you can modify the behaviour. To set the cindent options, type ':set cino=string', where string is a list defining exactly how you want your cindent options to behave. There are quite a few different types of indenting which can be done, and vim 's help does a good job explaining them, so I won't go over them here. To view the help for the possible values of cinoptions, type ':h cinoptions -values'. To view the current values, simply type ':set cino'. Most likely there will be none, since everything starts at a default value. cindent的默認設置選項一般來說是比較可人的, 但如果你的程序有特殊需求, 也 可以改變它, 設置cindent的選項, 通過`:set cino=string'選項(其中, string 是要用戶自己鍵入的字符串, 譯者), string定義了一個列表, 該列表決定了你 的cindent的行為. 你可以定義多種indent類型, vim的幫助對此有很詳細的說明. 欲查找關於該主題的幫助, 使用命令`:h cinoptions-values'. 要想查看當前的 設置值, 可以使用命令`:set cino'.
For more information, check out the following: ':h shiftwidth', ':h cindent ', ':h cinoptions', ':h cinoptions-values', ':h cinkeys', and ':h cinwords '. 要了解更多的細節, 可以使用在線幫助`:h shiftwidth', ':h cindent', `:h cinoptions', `:h cinoptions-values', `:h cinkeys', 和`:h cinwords'
syntax highlighting 語法高亮 Programmers who are used to integrated development environments know the beauty of syntax highlighting. It doesn't just make your code more readable ; it also helps prevent annoying commenting and string errors. Vim has syntax highlighting for a number of languages, including C and C++ of course. To enable it, type ':syntax on'. Using it is as simple as that if you're happy with the default values. Vim's syntax highlighting tools can be quite complex , with a number of different things to play around with. To view information on syntax hilighting, type ':h syntax', which will lead you to vim's extensive help system. Syntax hilighting with color terminals and with gvim is nice , but if you don't have color, vim uses underlining, boldface, etc. To me , this is pretty ugly. 用過集成開發環境的程序員都知道語法高亮的妙處所在, 它不光使你的代碼更具 可讀性, 它也使你免於拼寫錯誤, 使你明確注釋的范圍, Vim對多種語言都有語法 高亮的功能, 當然, C/C++一定包括在內, 打開語法高亮功能, 可使用命令`:syntax on'. 如果你覺得默認的設置已經夠好了, 使用它就是如此簡單. Vim的語法高亮工具也 可以十分復雜, 擁有眾多選項. 要了解更多的細節, 可通過命令`:h syntax'查看 在線幫助, 在支持彩色的終端上或者使用gvim(vim的GUI版, 增強了一些功能, 譯 者注), 但如果你當前的環境不支持彩色顯示, vim會使用下劃線, 粗體字, 試圖 進行等效的替代, 但對我而言, 這樣太難看了. For more information: ':h syntax', ':h syn-qstart', ':h syntax-printing ' 要了解更詳細的內容, 可通過命令`:h syn-gstart', ':h syntax-printing'查看 在線幫助
edit-compile-edit, a.k.a. Quickfix 編輯-編譯-再編輯 This is a really nifty feature. Basically, by typing one command, you can cause vim to attempt to make the program you're working on, then open to whatever file first compiler error is in at the line of that error. The command to execute is ':mak' (or ':make'). Vim will run whatever program is denoted by the value of 'makeprg'. The default value for 'makeprg' is 'make'. You can change this, if you wish, by typing ':set makeprg=', where string denotes the desired command. Vim uses the 'errorformat' value to figure out how to understand the output from the compiler. Since different compilers have different output format's, you'll probably have to enter the format string. The method used is rather similar to C-style formatting with scanf. The most important format specifiers are %f, meaning filename , %l, meaing line-number, and %m, meaning message. 這實在是極好的功能, 其基本功能是, 你可能不用離開當前編輯環境, 通過指定 一個命令, 就可以編譯你當前編輯的項目, 然後, 如果編譯時因發生錯誤而中斷, vim將會打開第一個發生錯誤的文件並定位於引起錯誤的行上. 這一命令就是`:mak' (或者':make'). vim將會運行由選項makeprg指定的make程序, 它的默認值就是 make(已經夠好用了, 譯者注). 如果願意的話, 你也可以使用命令`:set makeprg =string'改變項目維護工具(比如, 在VC下使用nmake, :set makeprg=nmake.exe , 譯者注), vim使用選項`errorformat'的設置去解析編譯囂輸出的錯誤信息的格式. 由於不同 的編譯囂有不同的錯誤信息格式, 所以可能需要顯式地指定錯誤信息的格式. 選項 `errorformat'的設置使用與c函數scanf風格類似的語法, 最重要的是指定%f, 代 表文件名, %l, 行號, %m, 錯誤信息.
GCC's format string: %f:%l:\%m GCC格式的errorformat設置:%f:%l:\%m This can become quite complex with different compilers, but fortunately, vim has a world of information in their help at ':h errorformat'. 有些編譯器的errorformat可能十分復雜, 但好在vim對此提供了完整的在線幫助 ':h errorformat'.
For more information, check out: ':h quickfix', ':h mak', ':h makeprg', ':h errorfile', ':h errorformat'. 要了解其它細節, 可用命令`:h quickfix', `:h mak', `:h makeprg', `:h errorfile ', `:h errorformat'查看相應的幫助.
useful keystrokes 有用的快捷按鍵 There are certain command-mode keystrokes that are especially useful for programmers. Below is a small subset of these: 有一些快捷按鍵對程序員而言特別有用, 下面是其中的一部分: Moving around within functions: 在函數中移動 [ [ = Go to previous first-column '{'; equivalent to ?^{ 移動到前一個行首的'{'字符上, 等價於?^{ ] ] = Go to next first-column '{'; equivalent to /^{ 移動到下一個行首的'{'字符上, 等價於/^{ [ ] = Go to previous first-column '}'; equivalent to ?^} 移動到前一個行首的'}'字符上, 等價於?^} ] [ = Go to next first-column '}'; equivalent to /^} 移動到下一個行首的'}'字符上, 等價於?^}
{ = Go to previous blank line. 到前一個空行上 } = Go to next blank line. 到下一個空行上
gd = Go to definition of current local variable (current = cursor is on it) 到當前局部變量的定義處(當前的意思是光標停留其上的單詞). * = Go to next instance of current word 到與當前單詞相同的下一個單詞上 # = Go to previous instance of current word '' = Go to location where last search was started. 到與當前單詞相同的上一個單詞上
Parenthesis Matching: % Takes you to the matching parenthesis, curly brace, or bracket, depending on what you are on. This always comes in handy as a quick double-check. 括號匹配: % 可以讓光標從它當前所在的括號跳轉到與它相匹配的括號上去, 對花括號和 圓括號, 方括號都有效, 常用於手工檢查括號是否匹對.
Substution: Vim has powerful substition capabilities, with a very simple interface. No annoying GUI to get in the way (though you may need to keep a cheat-sheet handy). To search for and replace text, use the following command: 替換操作: Vim具有強大的字符串替換功能, 操作起來十分簡單, 不需惹人生厭的GUI(圖形用 戶界面), 查找並替換文本, 可以使用下面的命令: : [address] s/
/string/[g|c|N] (where N is an integer value). (其中的N是一個整數值).
This finds one (or more) instance of the grep-style regular expression represented by
, and substitutes it with string. 'address', 'g', and 'N ' are modifiers which determine which and how many occurances of
are replaced. 此命令查找由grep風格的正則表達式指定的匹配模式
, 並將其替換為由 string指定的字符串, `address', `g', 和`N' 是對命令的補充選項, 它們分別 決定了命令的作用范圍, 是只替換第一個匹配的字符串還是替換所有匹配的字符串, 只替換每行中第N次匹配的字符串. g = Global: Replace all occurances of
on the line. 全部: 替換每行中所有匹配的字符串. c = Cond. Ask before making each replacement. 詢問. 在每次替換之前詢問用戶是否確定要進行替換. N = Nth Replace only the Nth occurance of
on the line. 第N次 只替換在一行中第N個匹配的字符串(如:s/zhao/slimzhao/2, 而 當前行的內容是zhao zhao zhao, 則替換後的內容為zhao slimzhao zhao, 譯 者注) (No modifier implies N=1, the first occurance on that line) (如果沒有指定這些輔助修飾標志, 則vim默認為只替換一行中第一個匹配的字符串 ) (即等價於address1, address2s/
/string/1, 譯者注)
[address values] -May be one specifier or two seperated by a comma. (below , x represents an integer). 可以是一個或是由逗號分開的兩個輔助修改標志. (下面的x代表一個整數) . = The current line 表示當前行(即光標所在的行, 譯者注) $ = The last line in the file 當前文件的最後一行 % = Entire file 整個文件(即對每一行, 等價於1,$, 譯者注) x = The xth line of the file 當前文件的第x行 +x = x lines after the current line 從當前行開始下面的第x行(如果當前行為第1行, 則+3 代表第4行) -x = x lines before the current line 從當前行開始上面的第x行(如果當前行為第4行, 則-3 代表第1行)
The comma may seperate any of the above in order to specify a range. All lines within the given range will undergo the substitution. The best reference I have found for subsituting can be found at the Vi Helpfile, linked below . 逗號用於分隔任何上面指定的單個行, 以形成一個范圍(當然, 這個范圍的下界不 能小於上界, 如10,1為非法的范圍, 此時vim會給出一個警告信息, 問你是否進行 反向操作, 如回答y, 則等價於1,10, 操作仍正常進行, 否則, 撤消當前操作, 譯者注), 其後指定的操作將作用於此處給出的范圍, vim幫助裡有關於替換操作 的充分信息.
Miscellany Vim has so many nifty little things, it would be impossible to list them all. Here are a few more things that are worth taking a look at. 其它雜項 Vim有眾多誘人的小功能, 這裡不可能一一列出, 下面列出一些尤其值得注意的一 些特性.
Include File Searching- ':h include-search' 包含文件搜索- `:h include-search' Bookmarking- 'mx' to set, ' 'x' to return; (x can be any letter, must stay within file to remember) 書簽設置- 'mx'用於設置書簽, ''x'用於從書簽返回;(其中的x可以為任何字母, 但, 只能記錄當前文件裡的書簽) (退出vim後再次進入將不會保留這些書簽, 書簽就是代表在文件中某一特定位置的一種標記, 譯者注) "Clipboard" buffers- ' "xY ' to cut or copy to buffer x (Y represents any normal deletion or yank command), ' "xZ ' to paste contents of x (Z represents pasting... p or P); (x can be any letter, can switch to another file(:e filename) and still maintain contents of buffers). "剪貼板" 緩沖- ' "xY ' 用於剪切或復制到一個名為x的緩沖區(Y 代表任何的 刪除或取樣命令), ' "xZ ' 用於粘貼內容(Z代表粘貼命令p 或 P); (其中x可以為 任何字母, 也可在跳轉到另一文件中時繼續生效(:e filename). Comment Specifiers- ':h comments' 注釋符- `:h comments' .vimrc- Don't forget your .vimrc!!! (Located in your home directory). You 'll find it very handy to add many of the above things to your .vimrc file , so that vim "remembers" everything you want it to. (You may find that some of them are already there.) Remember that you don't need to prepend a ':' to the command when adding them to the .vimrc. .vimrc- 別忘了你的.vimrc文件(在你用戶目錄中~/.vimrc). 該文件可用於 記錄上面你所做的大多數設置, 記住在.vimrc文件中無需在每個命令前使用一 個冒號":".(在DOS下的vim中, .vimrc文件放於vim程序所在的目錄中, 且, 此 時不叫.vimrc, 叫_vimrc, 另, .vimrc也可為.exrc, _vimrc也可為_exrc) Other Resources X_Console has written a really nice Vi Crash Course NHF , which should help you get over the learning curve, if you're just starting out. There are many, many webpages around with information on Vi/Vim, some good , some not so good (depending on what level you're looking for). A search for Vi or Vim at Google or any other search engine will turn up plenty of results. In my opinion, these are two of the best: 其它資源 X_Console(此處不知如何翻譯, 譯者注)上有一個非常好的vi教程, 如果你要開始 學習使用vi, 就從這裡開始吧. 因特網上有非常多的關於vi/vim信息的網頁, 有好有壞(好壞也看你的水平如何了) 在Google或其它搜索引擎上查找vi或vim會找到非常多的搜索結果, 我個人覺得 下面兩個是最好的
THE VI LOVER'S HOMEPAGE - Many links, lots of info... VI愛好者主頁 - 鏈接多多, 信息多多...
The VI Helpfile - Very comlete, terse reference. Great for ex commands. VI幫助文件 -非常完整而簡練的一份參考手冊, 特別是ex命令.
Unixworld Vi Tutorial - Nine parts, from start to finish... Go through this and you'll understand why we love Vi. Unix世界Vi教程- 九部分, 從開始到結束...看了就知道, 我們為什麼喜 歡VI.
This file was created by Keith Jones ([email protected]); I'm no expert on vim, but I hope some of the above was helpful. Enjoy!!! 本文由Keith Jones([email protected])寫就; 我不是vim專家, 但我希望上面 的一些內容對大家有所幫助. 希望大家喜歡!!!