practical vim2 笔记
生活随笔
收集整理的這篇文章主要介紹了
practical vim2 笔记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- windows capslock 修改映射為left-Ctrl
- mark
- 1. The Vim Way
- 2. Normal Mode
- 3. Insert Mode
- 4. Visual Mode
- 5. Command-Line Mode
- 6. Manage Multiple Files
- 7. Open Files and Save Them to Disk
- 8. Navigate Inside Files with Motions
- 9. Navigate Between Files with Jumps
- 10. Copy and Paste
- 11. Macros
- 12. Matching Patterns and Literals
- 13. Search
- 14. Substitution
- 15. Global Commands
- 16. Index and Navigate Source Code with ctags
- 17. Compile Code and Navigate Errors with the Quickfix List
- 18. Search Project-Wide with grep, vimgrep, and Others
- 19. Dial X for Autocompletion
- 20. Find and Fix Typos with Vim’s Spell Checker
- chang vim’s settings on the fly
windows capslock 修改映射為left-Ctrl
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,1D,00,3A,00,00,00,00,00保存為 .reg 文件 執行即可mark
! bang # hashtag & ampersand * asterisk _ underscore ` backtick ' apostrophe " quote : colon ; semicolon / slash \ backslash | pipe > greater-than | angle bracket < less-than | angle bracket () parentheses [] bracket {} curly brace1. The Vim Way
. repeat last change(x dd >G AxxxEsc | moving around in insert mode reset the change)----------------------------------------------var foo = 1 var bar = 'a' var foobar = foo + bartwo for the price of one(all switch from normal to insert mode - help to construct dot formula) C c$ s cl S ^C I ^i A $a o A<CR> O ko----------------------------------------------var foo = "method("+argument1+","+argument2+")";----------------------------------------------repeatable actions and how to reverse them Ident Act Repeat Reverse Make a change {edit} . u Scan line for next character f{char}/t{char} ; , Scan line for previous character F{char}/T{char} ; , Scan document for next match /pattern<CR> n N Scan document for previous match ?pattern<CR> n N Perform substitution :s/target/replacement & u Execute a sequence of changes qx{changes}q @x u Repeat any Ex command any command @: u----------------------------------------------...We're waiting for content before the site can go live... ...If you are content with this, let's go ahead with it... ...We'll launch as soon as we have the content...----------------------------------------------Dot Formula = One keystroke to Move + One keystroke To Execute2. Normal Mode
Vim's Normal Mode analogy to painting----------------------------------------------change : commands trigged from Normal, Visual, and Command-line modes, any text entered or deleted in Insert mode moving around in insert mode resets the change. repeat the most recent change u reverts the most recent changewe can make the undo command operate on words, sentences, or paragraphs just by moderating our use of the <Esc> key each pause leave and reenter Insert mode----------------------------------------------The end is nigh----------------------------------------------[count]<C-a> add [count] to the number at or after the cursor(default one) [count]<C-x> subtract [count] to the number at or after the cursor(default one).blog, .news { background-image: url(/sprite.png); } .blog { background-position: 0px 0px }Vim interprets numerals with a leading zero to be in octal notation rather than in decimal. set nrformats= (This will cause Vim to treat all numerals as decimal)----------------------------------------------Delete more than one wordI have a couple of questions.----------------------------------------------Operator-pending Mode : activated when we invoke an operator command, and then stopped until provided a motionoperator commands(when an operator command is invoked in duplicate, it acts upon the current line) c Change d Delete y Yank into register g~ Swap case gu Make lowercase gU Make uppercase > Shift right < Shift left = Autoindent ! Filter {motion} lines through an external programcustom operator gc comment/uncomment (vim-commentary plug)custom motion ae/ie entire file (vim-textobj-user vim-textobj-entire plug)dw 不刪前字符,刪后空格,停下單詞首字符daw 刪前字符,刪后空格,停下單詞首字符光標在行尾單詞時,刪前空格,停上單詞結尾diw 刪前字符,不刪后空格,停下單詞后空格cw 不刪除光標前字符,不刪除單詞之后空格,停留到單詞后空格caw 同dawciw 同diwyw 同dw yaw 同daw yiw 同diw p單詞:在當前字符后 粘貼p行:在粘貼到下一行3. Insert Mode
insert mode chords(also work in vim's command line and external bash shell) <C-h> Delete back one character (backspace) <C-w> Delete back one word <C-u> Delete back to start of line----------------------------------------------Insert Normal Mode(insert's submode) : fire off a single normal mode command then return insert modeget back to normal mode <Esc> Switch to Normal mode <C-[> Switch to Normal mode <C-o> Switch to Insert Normal mode----------------------------------------------Practical Vim, by Drew Neil Read Drew Neil'svim's registers "" unamed register "a-z named register "0 yank register "_ black hole register "+ system clipboard register "* selection register "= expression register :reg "{reg} inspect register's contentpaste from a register in insert mode <C-r> {reg} paste reg's content <C-r><C-p> {reg} paste reg's content literally (ignore textwidth autoindent which lead to unwanted line breaks or extra indentation)----------------------------------------------evaluate expressions in insert mode <C-r>={vim script}<CR>----------------------------------------------ga : look up character's numeric code at current cursor positioninsert unsual characters by its numeric code <C-v>{123} Insert character by decimal code <C-v>u{1234} Insert character by hexadecimal code <C-v>{nondigit} Insert nondigit literally <C-k>{char1}{char2} Insert character represented by {char1}{char2} digraph----------------------------------------------Typing in Insert mode extends the line. But in Replace mode the line length doesn't change.Replace Mode(identical to Insert Mode except it overwrites existing text) R engage Replace Mode r engage Replace Mode for single character <Esc> return to Normal Mode <Insert> toggle between Insert and Replace modesVirtual Replace Mode(treats the tab character as though it consisted of spaces) gR engage Virtual Replace Mode gr engage Virtual Replace Mode for single character4. Visual Mode
Action = Selection + operator commandSelect Mode(use c instead) : type any character will replace selection and switch to Insert Mode <C-g> toggle between Select Mode and Visual mode----------------------------------------------enabling Visual Mode v Enable character-wise Visual mode V Enable line-wise Visual mode <C-v> Enable block-wise Visual mode gv Reselect the last visual selectionswitching between Visual Modes v / V / <C-v> toggle between Normal mode and character-, line- or block-wise Visual mode, respectively <Esc> / <C-[> Switch to Normal mode o Go to other end of highlighted text----------------------------------------------def fib(n):a, b = 0, 1while a < n: print a, a, b = b, a+b fib(42)Tabs and Spaceshttp://vimcasts.org/transcripts/2/en/set ts=8 sts=0 sw=8 noexpandtab " default settingsinsert: <Tab> insert a tab char with width of 8 <BS> delete a tab char with width of 8normal: > prepend a tab char with width of 8 < delete a tab char with width of 8set ts=8 sts=0 sw=8 expandtabinsert: <Tab> insert 8 space chars <BS> delete single one spacenormal: > prepend 8 space chars < delete 8 space charsset ts=8 sts=8 sw=8 expandtabsame above except : insert <BS> delete 8 space charsset ts=8 sts=4 sw=4 expandtabinsert: <Tab> insert 4 space chars <BS> delete 4 space charsnormal: > prepend 4 space chars < delete 4 space charsany tab already existed it's width is 8set ts=8 sts=4 sw=4 noexpandtabsame above except : insert 2<Tab> become one true tab char <BS> one true tab char becomes 4 space charsnormal same as insertset ts=4 sts=4 sw=4 noexpandtabinsert: <Tab> insert a tab char with width of 4 <BS> delete a tab char with width of 4normal: > prepend a tab char with width of 4 < delete a tab char with width of 4any tab already existed shink it's width to 4----------------------------------------------<a href="#">one</a> <a href="#">two</a> <a href="#">three</a>----------------------------------------------Chapter Page Normal mode 15 Insert mode 31 Visual mode 44----------------------------------------------li.one a{ background-image: url('/images/sprite.png'); } li.two a{ background-image: url('/images/sprite.png'); } li.three a{ background-image: url('/images/sprite.png'); }----------------------------------------------var foo = 1 var bar = 'a' var foobar = foo + barI and A follows similar conventions in Visual-Block and Normal mode, but i and a not which are first half of a text object.5. Command-Line Mode
ZZ :wq ZQ :q! :version 查看vim版本信息 和 .vimrc文件路徑 :echo $VIM 查看環境變量----------------------------------------------Command-Line Mode : enable Command-Line Mode / search prompt <C-r>= access the expression register <CR> execute the command <Esc> switch back to Normal ModeEx Commands That Operate on the Text in a Buffer :[range]print echoes specified lines :[range]delete [x] Delete specified lines [into register x] :[range]yank [x] Yank specified lines [into register x] :[line]put [x] Put the text from register x after the specified line :[range]t(copy) {address} Copy the specified lines to below the line specified by {address} :[range]move {address} Move the specified lines to below the line specified by {address} :[range]join Join the specified lines :[range]normal {commands} Execute Normal mode {commands} on each specified line :[range]substitute/{pattern}/{string}/[flags] Replace occurrences of {pattern} with {string} on each specified line :[range]global/{pattern}/[cmd] Execute the Ex command [cmd] on all specified lines where the {pattern} matches :[range]vglobal/{pattern}/[cmd] Execute the Ex command [cmd] on all specified lines where the {pattern} doesn't matches----------------------------------------------<!DOCTYPE html><!-- --><head><title>Practical Vim</title></head><!-- --><body><h1>Practical Vim</h1></body> </html><!-- --> <body><h1>Practical Vim</h1></body><!-- -->symbols that can be used to create address and ranges for Ex commands 1 First line of the file(line nubmers) $ Last line of the file 0 Virtual line above first line of the file . current Line where the cursor is placed 'm Line containing mark m'm '< first line of visual selection '> last line of visual selection % The entire file (shorthand for :1,$) :/<html>/+1,<\/html>/-1p pattern that uses offset----------------------------------------------Shopping listHardware StoreBuy new hammerBeauty ParlorBuy nail polish removerBuy nails:t command in action :6t. Copy line 6 to just below the current line :t6 Copy the current line to just below line 6 :t. Duplicate the current line (similar to Normal mode yyp) :t$ Copy the current line to the end of the file :'<,'>t0 Copy the visually selected lines to the start of the file----------------------------------------------var foo = 1 var bar = 'a' var baz = 'z' var foobar = foo + bar var foobarbaz = foo + bar + baz----------------------------------------------repeat last Ex command @: @@go back to previous record in the jump list <C-o>----------------------------------------------Tab-Complete Ex commands <Tab> scroll through all possible commands <S-Tab> scroll backward all possible commands <C-d> reveal a list of possible completions----------------------------------------------var tally; for (tally=1; tally <= 10; tally++) {// do something with tally };insert the current word at the command prompt <C-r><C-w> copies the word under the cursor and inserts it at the command-line prompt <C-r><C-a> copies the WORD under the cursor and inserts it at the command-line prompt----------------------------------------------recall commands from history <Up> go further back through Ex command/search history <Down> go in the opposite direction:write :!ruby %summon/close command-line window q: Open the command-line window with history of Ex commands q/ Open the command-line window with history of searches :q close the command-line window(line any other window) ctrl-f Switch from Command-Line mode to the command-line window----------------------------------------------first name,last name,email john,smith,john@example.com drew,neil,drew@vimcasts.org jane,doe,jane@example.comcalling external commands :!{cmd} firing one-off command in shell :shell start a interactive shell session (exit kills the shell and return to vim) :read !{cmd} Execute {cmd} in the shell and insert its standard output below the cursor :[range]write !{cmd} Execute {cmd} in the shell with [range] lines as standard input(default is whole buffer) :[range]!{filter} The lines specified by [range] are passed as standard input for the {cmd}, and then the output from {cmd} overwrites the original contents of [range].The !{motion} operator command drops us into Command-Line mode and prepopulates the [range] with the lines covered by the specified {motion}.putting vim in the background <Ctrl-z> suspend vim process jbos inspect the list of jobs fg resume a suspended job----------------------------------------------<ol><li><a href="/episodes/show-invisibles/">Show invisibles</a></li><li><a href="/episodes/tabs-and-spaces/">Tabs and Spaces</a></li> </ol>:source {filename} execute each line of {filename} as Ex commands :argdo ExCommand execute Ex command for each of the files in the argument list(launching vim with with a wildcard will populate the argument list)6. Manage Multiple Files
buffer management :ls list all buffers :bnext switch to the next buffer :bprevious switch to the previous buffer :bfirst switch to the first buffer :blast switch to the last buffer :b {bufferNumber or bufferName} switch to designated buffer :bufdo execute an Ex command in all buffers :bdelete delete disigned bufferssymbols in ls command % indicates which of the buffers is visible in the current window # represents the alternate file(pressing <C-^> to toggle between current file and alternate file) + indicates that the buffer has been modified a active h hiddenhttps://github.com/tpope/vim-unimpaired----------------------------------------------arg management :args {arglist} show argument list if arglist ommited or set the content of the argument list(arglist can include filenames,wildcard,output from a shell command) :next switch to the next arg :previous switch to the previous arg :first switch to the first arg :last switch to the last arg :argdo execute an Ex command in all args----------------------------------------------:w[rite] Write the contents of the buffer to disk :e[dit]! Read the file from disk back into the buffer (that is, revert changes) :qa[ll]! Close all windows, discarding changes without warning :wa[ll] Write all modified buffers to disk(or use :first :wn to eyeball each file):set hidden use :next,:bnext,:cnext commands without a trailing bang----------------------------------------------dividing workspace into split windows <C-w>s Split the current window horizontally, reusing the current buffer in the new window <C-w>v Split the current window vertically, reusing the current buffer in the new window :sp[lit] {file} Split the current window horizontally, loading {file} into the new window :vsp[lit] {file} Split the current window vertically, loading {file} into the new windowchange the focus between windows <C-w>w Cycle between open windows <C-w>h Focus the window to the left <C-w>j Focus the window below <C-w>k Focus the window above <C-w>l Focus the window to the rightclose window :clo[se] <C-w>c Close the active window :on[ly] <C-w>o Keep only the active window, closing all othersresize window <C-w>= Equalize width and height of all windows <C-w>_ Maximize height of the active window <C-w>| Maximize width of the active window [N]<C-w>_ Set active window height to [N] rows [N]<C-w>| Set active window width to [N] columns----------------------------------------------setting window's working directory :lcd {path} set the working directory for the current window :windo lcd {path} set the working directory for the current tab pageopen and close tabs :tabedit {filename} Open {filename} in a new tab(if filename omitted create a new tab page containing empty buffer) <C-w>T Move the current window into its own tab :tabclose Close the current tab page and all of its windows :tabonly Keep the active tab page, closing all othersswitching between tabs :tabn[ext] {N} {N}gt Switch to tab page number {N} :tabn[ext] gt Switch to the next tab page :tabp[revious] gT Switch to the previous tab pagerearrange tabs :tabmove [N] rearrange current tab page if N=0 move to the begining if N is omitted move to the end7. Open Files and Save Them to Disk
:pwd print working directory :edit {file} open files(specified an absolute or relative path) %:h expands to filepath of the active buffer but removed the filenamecnoremap <expr> %% getcmdtype() == ':' ? expand('%:h').'/' : '%%'----------------------------------------------:find open file by its name :set path+= specify a set of directories inside of which vim will search when :find is invoked ----------------------------------------------netrw vim . start up with a file explore window :edit {dir} Open file explorer for designated directory :edit . Open file explorer for project root :edit %:h Open file explorer for current file :Explore Open file explorer for current file :Sexplore open file explorer for current file in a horizontal split :Vexplore open file explorer for current file in a vertical split----------------------------------------------save files to Nonexistent Directories :e {nonexistentFile} create a new empty buffer <C-g> echos the name and status of the current file :!mkdir -p %:h create nonexistent directories----------------------------------------------save files as the super user :w !sudo tee % > /dev/null8. Navigate Inside Files with Motions
_ soft bol g_ soft eol ctrl + f/b move to page down/up ctrl + e/y move to line down/up zz/zt/zb scroll cursor to middle/top/bottom----------------------------------------------move the cursor around h move One column left (use word-wise or character search motions to move horizontally) l move One column right j move One line down k move One line up----------------------------------------------commands for interacting with real and display lines j Down one real line gj Down one display line k Up one real line gk Up one display line 0 To first character of real line g0 To first character of display line ^ To first nonblank character of real line g^ To first nonblank character of display line $ To end of real line g$ To end of display line ----------------------------------------------Go fast.commands for move the cursor forward and backward w/W Forward to start of next word b/B Backward to start of current/previous word e/E Forward to end of current/next word ge/gE Backward to end of previous word----------------------------------------------character-search commands(working butifully with operator-pending mode)(use capital letter/punctuation mark char) f{char} Forward to the next occurrence of {char}(used to move within current line in normal mode) F{char} Backward to the previous occurrence of {char} t{char} Forward to the character before the next occurrence of {char}(used with c/d in operator-pending mode) T{char} Backward to the character after the previous occurrence of {char} ; Repeat the last character-search command , Reverse the last character-search command f,dt. delete the last clause of a sentenceuser-defined commands \ default leader key noremap <Leader>n nzz noremap <Leader>N Nzz----------------------------------------------search command(work with normal/visual/operator-pending modes) /xxx----------------------------------------------var tpl = ['<a href="{url}">{title}</a>' ]text objects interact with delimiters(first char is always a or i) a) or ab A pair of (parentheses) i) or ib Inside of (parentheses) a} or aB A pair of {braces} i} or iB Inside of {braces} a] A pair of [brackets] i] Inside of [brackets] a> A pair of <angle brackets> i> Inside of <angle brackets> a’ A pair of 'single quotes' i’ Inside of 'single quotes' a" A pair of "double quotes" i" Inside of "double quotes" a` A pair of `backticks` i` Inside of `backticks` at A pair of <xml>tags</xml> it Inside of <xml>tags</xml>----------------------------------------------text objects interact with chunks of text(words,sentences,paragraphs) iw word aw word plus space(s) iW WORD aW WORD plus space(s) is sentence as sentence plus space(s) ip paragraph ap paragraph plus blank line(s)i usually work with c{motion} a wusuall york with d{motion}/y{motion}----------------------------------------------mark m{a-zA-Z} marks current cursor location with designated letter(lowercase marks are local to each individual buffer, uppercase marks are globally accessible) '{mark} move to mark positioning the cursor on the first none-whitespace character `{mark} move to mark positioning the cursor to the exact position where the mark was setVim's automatic marks `` last jump `. last change `^ last insertion `[ Start of last change or yank `] End of last change or yank `< Start of last visual selection `> End of last visual selection----------------------------------------------cities = %w{London Berlin New\ York}http://github.com/tpope/vim-surroundjump between matching parenthese % jump between opening and closing sets of parentheses(such as () [] {} )9. Navigate Between Files with Jumps
traverse Vim's jump list :jump inspect the jump list <C-o> jump backward <C-i> jump forwardjumps(each separate window has its own jump list) % Jump to matching parenthesis (/) Jump to start of previous/next sentence {/} Jump to start of previous/next paragraph H/M/L Jump to top/middle/bottom of screen [count]G Jump to line number /pattern<CR>/?pattern<CR>/n/N Jump to next/previous occurrence of pattern gf Jump to file name under the cursor <C-]> Jump to definition of keyword under the cursor `{mark}/’{mark} Jump to a mark----------------------------------------------traverse Vim's change list(each individual buffer has its own change list) g; jump backward g, jump forward :changes jump listgi restore the cursor position and then swithch back into insert mode----------------------------------------------jump to the filename under the cursor gf goto the filename under the cursor :set suffixesadd+= specify extensions which Vim will attempt to use when looking up a filename with gf command :set path+= specify directories which Vim will attempt to use when looking up a filename with gf command ----------------------------------------------snap between files using global marks(global marks are persisted between editing sessions) m{A-Z} make global marks `{A-Z} jump to global marks10. Copy and Paste
collection = getCollection(); process(somethingInTheWay, target);using unamed register xp transpose two characters ddp transpose two lines yyp duplicate current line----------------------------------------------commands can be prefixed with register x,s,d{motion},c{motion},y{motion}readonly registers(value set implicitly) "% Name of the current file "# Name of the alternate file ". Last inserted text ": Last Ex command "/ Last search pattern----------------------------------------------I like chips and fish.Replace a Visual Selection with a Register p command in Visual mode, it gets the contents of the unnamed register, and it sets the contents of the unnamed register----------------------------------------------<table><tr><td>Symbol</td><td>Name</td></tr></table>Paste from a register p put the content of a register after the cursor position P put the content of a register before the cursor position gp same as p but leave the cursor positioned at the end of the pasted text instead of at the beginning gP same as P but leave the cursor positioned at the end of the pasted text instead of at the beginningduplicat text as a template gP----------------------------------------------[1,2,3,4,5,6,7,8,9,10].each do |n|if n%5==0puts "fizz"elseChapter 10. Copy and Paste ? 158report erratum ? discussputs nend endpasting from the system clipboard :set autoindent preserve the same level of indentation each time we create a new line :set pastetoggle=<f5> press <f5> to toggle the paste option on and off system paste command use system paste command in Insert mode "+p paste the content of system clipboard if Vim with system clipboard integration11. Macros
macro q{reg} recording a macro @{reg} play back a sequence of commands by executing a macro @@ play back the most recent macro being palyed :reg {reg} inspect the content of register----------------------------------------------record a macro normalize the cursor position strike your target with a repeatable motion abort when a motion fails----------------------------------------------play back macro with a count {count}@{reg} play designated count times of macro except motion fails and the macro aborts----------------------------------------------1. one 2. two // break up the monotony 3. three 4. fourexecuting the macro in series {count}@{reg} executing the macro in parallel :'<,'>normal @a----------------------------------------------Append Commands to a Macro q{A-Z}{commands}q----------------------------------------------# ...[end of copyright notice] module Rankclass Animal# implementation...end end----------------------------------------------partridge in a pear tree turtle doves French hens calling birds golden rings----------------------------------------------1. One 2. Two 3. three 4. fourkeyboard codes in macros ^[ Esc <80>kb backspace ^J <CR>12. Matching Patterns and Literals
tune the case sensitivity of search pattern \c\C setting case sensitivity per search (c causes search pattern case incensitive) :set smartcase if pattern is all lowercase then search will be case incensitive :set ignorecase make Vim's search pattern case incensitive----------------------------------------------body { color: #3c3c3c; } a { color: #0000EE; } strong { color: #000; }magic search(default (){| have to be escaped to confer special meaning) /#\([0-9a-fA-F]\{6}\|[0-9a-fA-F]\{3}\)very magic search(all characters assume a special meaning except _ letters digits) /\v#([0-9a-fA-F]{6}|[0-9a-fA-F]{3}) /\v#(\x{6}|\x{3})----------------------------------------------The N key searches backward... ...the \v pattern switch (a.k.a. very magic search)...very nomagic search(only backslash has a special meaning) /\Va.k.a.----------------------------------------------I love Paris in the the springtime.use parenthese to capture submatches /\v<(\w+)\_s+\1> /\v(%(And|D)rew) (Neil) :%s//\2, \1/g----------------------------------------------the problem with these new recruits is that they don't keep their boots clean.stake the boundaries of word /\<the\> < item as \W\zs\w, and the > item as \w\ze\W In very magic searches, the naked < and > characters are interpreted as word delimiters in magic, nomagic, and very nomagic searches we have to escape them.indirectly use of word boundary * #g* g# perform search without word delimiters----------------------------------------------Match "quoted words"---not quote marks.stake the boundaries of a match /Pratical \zsVim /\v"\zs[^"]+\ze"<CR>----------------------------------------------Search items: [http://vimdoc.net/search?q=/\\][s] [s]: http://vimdoc.net/search?q=/\\escape search field terminator and escape character(/ or ? and \) /\Vhttp:\/\/vimdoc.net\/search?q=\/\\\\ /\V<C-r>=escape(@u, getcmdtype().'\')13. Search
search command :set wrapscan! search the document without wrapping aroundoptions for repeating a search n Jump to next match, preserving direction and offset N Jump to previous match, preserving direction and offset /<CR> Jump forward to next match of same pattern ?<CR> Jump backward to previous match of same pattern gn select current or next search match and enable character-wise Visual mode gN select current or previous search match and enable character-wise Visual mode recall historical searches <Up>----------------------------------------------highlight search matches :set hlsearch all matches to be highlighted current document as well as in any other open split windows :set nohlsearch disable hlsearch entirely :nohlsearch mute search highlighting temporarily until the next time you execute a new or repeat search nnoremap <silent> <C-l> :<C-u>nohlsearch<CR><C-l>----------------------------------------------improve search workflow :set incsearch enable incremental search <C-r><C-w> autocompletes search field using remainder of the word (if pattern prefix with /v it will autocompletes the entire word under the cursor)----------------------------------------------Aim to learn a new programming lang each year. Which lang did you pick up last year? Which langs would you like to learn?using search offset /lang/e<CR> //e<CR>----------------------------------------------class XhtmlDocument < XmlDocument; end class XhtmlTag < XmlTag; endoperate on search match /\vX(ht)?ml\C<CR> gUgn n.n.----------------------------------------------This string contains a 'quoted' word. This string contains 'two' quoted 'words.' This 'string doesn't make things easy.'Create Complex Patterns by Iterating upon Search History q/ summon the search history command window /\v'.+' /\v'[^']+' /\v'([^']|'\w)+' /\v'(([^']|'\w)+)' :%s//"\1"/g :%s/\v'(([^']|'\w)+)'/"\1"/g----------------------------------------------var buttons = viewport.buttons; viewport.buttons.previous.show(); viewport.buttons.next.show(); viewport.buttons.index.hide();Count the Matches for the Current Pattern /\<buttons\> :%s///gn :vimgrep //g % :cnext :cprev----------------------------------------------Search for the Current Visual Selectionxnoremap * :<C-u>call <SID>VSetSearch('/')<CR>/<C-R>=@/<CR><CR> xnoremap # :<C-u>call <SID>VSetSearch('?')<CR>?<C-R>=@/<CR><CR> function! s:VSetSearch(cmdtype)let temp = @snorm! gv"sylet @/ = '\V' . substitute(escape(@s, a:cmdtype.'\'), '\n', '\\n', 'g')let @s = temp endfunctionhttps://github.com/nelstrom/vim-visual-star-search14. Substitution
substitute command :[range]s[ubstitute]/{pattern}/{string}/[flags]substitute command flags g change all matches within a line rather than just changing the first one c gives us the opportunity to confirm or reject each change n suppresses the usual substitute behavior, causing the command to report the number of occurrences e silence errors if the pattern has no matches in the current file & reuse the same flags from the previous substitute commandSpecial Characters for the Replacement String \r Insert a carriage return \t Insert a tab character \\ Insert a single backslash \1 Insert the first submatch \2 Insert the second submatch (and so on, up to \9) \0 Insert the entire matched pattern & Insert the entire matched pattern ~ Use {string} from the previous invocation of :substitute \={Vim script} Evaluate {Vim script} expression; use result as replacement {string}----------------------------------------------When the going gets tough, the tough get going. If you are going through hell, keep going.Find and Replace Every Match in a File :%s/going/rolling/g----------------------------------------------...We're waiting for content before the site can go live... ...If you are content with this, let's go ahead with it... ...We'll launch as soon as we have the content...Eyeball Each Substitution :%s/content/copy/gcVim’s Substitute Confirmation Mode y Substitute this match n Skip this match q Quit substituting l "last"—Substitute this match, then quit a "all"—Substitute this and any remaining matches <C-e> Scroll the screen up one line <C-y> Scroll the screen down one line----------------------------------------------paste the contents of the last search register :%s/<C-r>//"\1"/g----------------------------------------------use the content of register in replacement string :%s//<C-r>0/g :%s//\=@0/g----------------------------------------------Repeat a Line-Wise Substitution Across the Entire File :s/target/replacement/g :%s//~/& g&mixin = {applyName: function(config) {return Factory(config, this.getName());}, }replay the last substitue command :&&making & trigger :&& command nnoremap & :&&<CR> xnoremap & :&&<CR>----------------------------------------------last name,first name,email neil,drew,drew@vimcasts.org doe,john,john@example.comreference submatch in replacement string /\v^([^,]*),([^,]*),([^,]*)$ :%s//\3,\2,\1----------------------------------------------<h2>Heading number 1</h2> <h3>Number 2 heading</h3> <h4>Another heading</h4>perform arithmetic on replacement string /\v\<\/?h\zs\d :%s//\=submatch(0)-1/g----------------------------------------------The dog bit the man.Swap Two or More Words :let swapper={"dog":"man","man":"dog"} :echo swapper["dog"] :echo swapper["man"] /\v(<man>|<dog>) :%s//\={"dog":"man","man":"dog"}[submatch(1)]/ghttps://github.com/tpope/vim-abolish :%S/{man,dog}/{dog,man}/g----------------------------------------------Find and replace in current buffer /Pragmatic\ze Vim :%s//Practical/gFind and Replace Across Multiple Files /Pragmatic\ze Vim :vimgrep // **/*.txt :set hidden :cfdo %s//Practical/gc :cfdo update15. Global Commands
global command(run an Ex command on each line that matches a particular pattern, default range is entire file %, default cmd is :print) :[range] global[!] /{pattern}/ [cmd]----------------------------------------------<ol><li><a href="/episodes/show-invisibles/">Show invisibles</a></li><li><a href="/episodes/tabs-and-spaces/">Tabs and Spaces</a></li><li><a href="/episodes/whitespace-preferences-and-filetypes/">Whitespace preferences and filetypes</a></li> </ol>delete lines containing a pattern /\v\<\/?\w+> :g//dkeep lines containing a pattern :v/href/d----------------------------------------------Markdown.dialects.Gruber = {lists: function() {// TODO: Cache this regexp for certain depths.function regex_for_depth(depth) { /* implementation */ }},"`": function inlineCode( text ) {var m = text.match( /(`+)(([\s\S]*?)\1)/ );if ( m && m[2] )return [ m[1].length + m[2].length ];else {// TODO: No matching end code found - warn!return [ 1, "`" ];}} }collect all lines that match a pattern in a register qaq :g/TODO/yank A :g/TODO/t$----------------------------------------------html {margin: 0;padding: 0;border: 0;font-size: 100%;font: inherit;vertical-align: baseline; } body {line-height: 1.5;color: black;background: white; }Alphabetize the Properties of Each Rule in a CSS File :g/{/ .+1,/}/-1 sortgeneralized form of global command :g/{start}/ .,{finish} [cmd]16. Index and Navigate Source Code with ctags
Exuberant Ctags yum ctags ctags *.rb----------------------------------------------specify where Vim should look to find a tags file :set tags? Generate the tags File :!ctags -R :nnoremap <f5> :!ctags -R<CR>Automatically Execute ctags Each Time a File is Saved :autocmd BufWritePost * call system("ctags -R")Automatically Execute ctags with Version Control Hooks http://tbaggery.com/2011/08/08/effortless-ctags-with-git.html----------------------------------------------tag command <C-]> jump from the keyword under the cursor to the definition <C-t> jump backword for tag jump history g<C-]> if keyword has multiple matches prompt a list of tag match :tselect retrospectively pull up the menu of the tag match list :tnext :tprev :tfirst :tlast<C-]> Jump to the first tag that matches the word under the cursor g<C-]> Prompt user to select from multiple matches for the word under the cursor. If only one match exists, jump to it without prompting. :tag {keyword} Jump to the first tag that matches {keyword}, Keyword could be regualr expression :tjump {keyword} Prompt user to select from multiple matches for {keyword}. If only one match exists, jump to it without prompting. Keyword could be regualr expression :pop or <C-t> Reverse through tag history :tag Advance through tag history :tselect Prompt user to choose an item from the tag match list :tnext Jump to next matching tag :tprev Jump to previous matching tag :tfirst Jump to first matching tag :tlast Jump to last matching tag17. Compile Code and Navigate Errors with the Quickfix List
compile the project inside vim :make :make!----------------------------------------------browse the quickfix list :cnext Jump to next item, can be prefixed with a count :cprev Jump to previous item, can be prefixed with a count :cfirst Jump to first item :clast Jump to last item :cnfile Jump to first item in next file :cpfile Jump to last item in previous file :cc N Jump to nth item :copen Open the quickfix window :cclose Close the quickfix window :cdo {cmd} Execute {cmd} on each line listed in the quickfix list :cfdo {cmd} Execute {cmd} once for each file listed in the quickfix listcommands populates quickfix list :make :grep :vimgrepcommands populates location list :lmake :lgrep :lvimgrepbrowse the location list same as quickfix list c replaced with l----------------------------------------------recall results from a previous quickfix list :colder recall an older version of quickfix list, can be prefixed with a count :cnewer revert from an old quickfix list back to a newer one, can be prefixed with a count----------------------------------------------var i; for (i=1; i <= 100; i++) {if(i % 15 == 0) {console.log('Fizzbuzz');} else if(i % 5 == 0) {console.log('Buzz');} else if(i % 3 == 0) {console.log('Fizz');} else {console.log(i);} };Customize the External Compiler npm install nodelint -g :setlocal makeprg=NODE_DISABLE_COLORS=1\ nodelint\ % :setlocal errorformat=%A%f\,\ line\ %l\,\ character\ %c:%m,%Z%.%#,%-G%.%# https://github.com/bigfish/vim-nodelint :compiler nodelint18. Search Project-Wide with grep, vimgrep, and Others
call grep without leaving vim :grep -i Waldo * ----------------------------------------------Customize the grep grepprg="grep -n $* /dev/null" grepformat="%f:%l:%m,%f:%l%m,%f %l%m"make grep call ack yum install ack-grep ln -s /usr/bin/ack-grep /usr/local/bin/ack :set grepprg=ack\ --nogroup\ --column\ $* :set grepformat=%f:%l:%c:%malternative grep plugin https://github.com/tpope/vim-fugitive https://github.com/mileszs/ack.vim----------------------------------------------grep with vim's internal search engine :vim[grep][!] /{pattern}/[g][j] {file} ... :vimgrep /going/ clock.txt tough.txt where.txt :vimgrep /going/g clock.txt tough.txt where.txtvimgrep each file in the argument list :args *.txt :vim /going/g ##vimgrep reuse last search pattern /[Dd]on't :vim //g *.txtlooks inside each of the files in the argument list for the current search pattern :vim //g ##19. Dial X for Autocompletion
autocompletion and case sensitivity if 'ignorecase' option is enabled autocompletion word list will add more candidates enabling the 'infercase' option to improve candidatescommands trigger autocompletion <C-n>/<C-p> Generic keywords(buffer list + included files + tag files) <C-x><C-l> Whole line completion(same as generic keywords source) <C-x><C-n> Current buffer keywords <C-x><C-i> Included file keywords <C-x><C-]> tags file keywords <C-x><C-k> Dictionary lookup <C-x><C-f> Filename completion <C-x><C-o> Omni-completion----------------------------------------------commands interacting with autocompletion suggestions pop-up menu <C-n> Use the next match <C-p> Use the previous match <Down> Select the next match(text in document is left unchanged) <Up> Select the previous match(text in document is left unchanged) <C-y> Accept the currently selected match (yes) <C-e> Revert to the originally typed text (exit from autocompletion) <C-h>(and <BS>) Delete one character from current match <C-l> Add one character from current match {char} Stop completion and insert {char}Refine the Word List as You Type <C-n><C-p>----------------------------------------------inspect buffer list :ls!Customizing the Generic Autocompletion :set complete=.,w,b,u,t,i :set complete+=k (enable completion words from spelling dictionary) :set complete-=i (disable completion words from included files)----------------------------------------------autocomplete words from the dictionary :set spell :h 'dictionary'----------------------------------------------.top {background-color: #ef66ef; } .bottom {----------------------------------------------Here's the "hyperlink" for the Vim tutor: <vimref href="http://vimhelp.appspot.com/usr_01.txt.html#tutor">tutor</vimref>. For more information on autocompletion see: <vimrautocomplete sequences of words <C-x><C-p>autocomplete sequences of lines <C-x><C-l>----------------------------------------------<!DOCTYPE html> <html><head><title>Practical Vim - the app</title><script src="" type="text/javascript"></script></head><body></body> </html>Autocomplete Filenames :pwd inspect current working directory :cd {path} change working directory :cd- revert back to previous working directory----------------------------------------------h1 { ba20. Find and Fix Typos with Vim’s Spell Checker
Yoru mum has a moustache.Spell Check :set spell enabling the built-in spell checker, highlight misspelled wordsspell checker commands ]s Jump to next spelling error [s Jump to previous spelling error z= Suggest corrections for current word(can be prefixed with a count) zg Add current word to spell file(so it doesn't flagged, can be prefixed with a count) zw Remove current word from spell file zug Revert zg or zw command for current word----------------------------------------------Use Alternate Spelling Dictionaries :set spell :set spelllang=en_us (always local to buffer, default value is en)http://ftp.vim.org/vim/runtime/spell/----------------------------------------------setlocal spelllang=en_us setlocal spellfile=~/.vim/spell/en.utf-8.add setlocal spellfile+=~/books/practical_vim/jargon.utf-8.addAdd Words to the Spell File 2zg 1zg----------------------------------------------Fix Spelling Errors in Insert Mode <C-x>s scans backward from the cursor position, stopping when it finds a misspelled word, then builds a word list from suggested corrections and presents them in an autocomplete pop-up menu.chang vim’s settings on the fly
change settings :set ignorecase :set noignorecase :set ignorecase! :set ignorecase? :set ignorecase& :set ts=2 sts=2 sw=2 etchange settings locally :setlocal tabstop=4 :bufdo setlocal tabstop=4 :windo setlocal number總結
以上是生活随笔為你收集整理的practical vim2 笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 经济学家系列之经济危机
- 下一篇: 有用的vscode快捷键大全+自定义快捷