Pro Vim学习笔记

来源:互联网 发布:mac怎么卸载java 编辑:程序博客网 时间:2024/06/05 06:05

Pro vim 笔记

ch2 Installation & configuration

configure your terminal

Zsh is a replacement for Bash and can be thought of as an improvement to the feature found in the Bash.

editing .zshrc

apt-get install zsh
cat /etc/shells
chsh -s /bin/zsh


Ch3 Fundamental

fundamental concepts for VIM:

  • Commands
  • Buffers
  • Windows
  • Tabs
  • Modes

Buffers

When you open a file in Vim and start editing it, you are, in fact, only editing a copy of the file.
The original file remains unchanged until you actually write the buffer back to the file.
Buffers have multiple states: active, hidden, and active.

Windows

Vim allows you to split the current viewpoint/screen into smaller window.

Tabs

Used in a scenariors that you expect another application.

Modes

One of the most important concepts in Vim is its built-in “modes”, of which there are six main ones. The are others, such as SELECT and EX:

  • NORMAL
  • INSERT
  • VISUAL
  • REPLACE
  • COMMAND-LINE
  • VISUAL-BLOCK
Modes Trigger NORMAL <Esc> INSERT i VISUAL v REPLACE R COMMAND-LINE : VISUAL-BLOCK <C-v>
Vim provides couple of options to recap all the commands previously executed:
static list
:history
dynamic list
q: (in any modes but insert, it will open up command line window.)

If you are already in command-line mode, pressing <C-f> to drop you into command line window.

Online community

Stack Overflow Or Experts Exchange

Key bindings

Command Bindings nmap Display key binding for NORMAL mode vmap Display key binding for VISUAL mode imap Display key binding for INSERT mode map Display key binding for all mode

The :only command closes all split windows until there is one window left open.


Ch4 Files

Open file

vim file.txt
vim file1.txt file2.txt
once you’re in vim, using edit (:e ) command:
:e path/to/your/file.txt

When using the edit command :e, press <Space> and then <C-d>, you can list all available dir/files, and press <Tab> key to cycle through all available items.

File formats

set fileformat= {dos|mac|unix}

Inserting File

To do a basic file load, use vim’s :read command.

:read file2.txt
:8read file2.txt
:read !ls -a | grep ‘^.’ | grep –invert-match ‘.DS_Store|.$’

Moving between files

When open multiple files, using vim’s suite of buffer comands.
- :bn: next buffer
- :bp: previous buffer
- :ls: list all buffers that are available
- :b#: to alternative buffer
- :bf/l: to first/last buffer
- :bm: next modified buffer

Saving files

  • :w: save a file
  • :wq: save & close
  • x: write the buffer when a modification is actually detected
  • 5,9wq: save line 5 ~ 9, then quit.


    quit files:
  • :qa!:
  • :wqa.
  • :conf wqa. need a confirm.
  • wqa!

Creating new file

  • :new: empty buffer within a horizontal split window
  • :enew: empty buffer
  • :vnew: tempty buffer within a vertical split window
  • tabnew: empty buffer within a new tab.

Creating New Files from a Template

autocmd BufNewFile *.html Or ~/skeleton.html
autocmd BufNewFile ruby_class.rb Or ~/ruby_class_template.rb

Creating a Scratch Buffer

  • Create Scratch buffer without plug-in.
    • :set buftype=nofile
    • :set bufhidden=hide
    • :setlocal noswapfile
  • With plug-in.
    • :Scratch: create a scratch buffer in current window.
    • :Sscratch: create a scratch buffer in a horizontal split window.

File Name Modifiers

file name modifier takes the form of %{:option},
see h: filename-modifiers

Switching Working Directories

cd %:p:h


Ch5 Commands

Commands for editing content are used primarily within NORMAL mode.

Editing Commands

[count] {operator} {[count] motion|text object}

Operators

Operator Explanation yy Yanks entire line p/P paste after/before current cursor position i/a put into INSERT mode before/after current cursor position f/t finds specified character to the right / until the specified character o/O move cursor to the next/previous line and enter INSERT mode x cuts the character s/S substitute the character / entire line ~ swap character casing dd deletes current line D delete from the cursor until the end of line (same as d$) gx opens URL under your cursor in web browser

Motions

Motion Explanation 0 start of the line $ end of the line (inclusive of newline) g_ ~ (exclusive of newline) b backward through each word e end of the word w start of next word gg/G start/end of the buffer % next bracket (or parenthesis) ( / ) previous / next sentence { / } start / end of a paragraph [( / ]) previous / next available parenthesis [{ / ]} previous / next available bracket

Command Inversion

  • p / P
  • f / F
  • r / R
  • a / A
  • i / I

Cursor Movement

h, j, k, l

Page Movement

Command Explanation <C-u> half page up <C-d> half page down <C-b> one page up <C-f> one page down zt shift page content so current line sits at the top of the viewport zb current line sits at bottom ~ zz current line sits at middle ~ H move cursor to the top of the viewport M ~ middle ~ L ~ bottom ~

one vim configuration:

set scrolloff = {n}

Text Objects

The syntax structure of a text object:
{special motion} {object}

Type Name Explanation sp motion Inside (i) select inside the object (exclusive whitespace) sp motion Arround (a) select arround (inclusive whitespace) object Word(w) select a single word object Sentence(s) single sentence object Paragraph(p) single paragraph object Tag(t) single XML/HTML mark-up tag object Quote(“|’|`) select content inside/around quotation marks object Block({}|[]|<>|()) ~ block (exclusives whitespace)

Executing Commands Within INSERT Mode

Use <C-o>, to enter a special mode in which you’re placed back in NORMAL mode. After a command has completed, it will back into INSERT mode.


Ch6 Register

Vim register types:
1. The unnamed register “”
2. 10 numbered register “0 to “9
3. The small delete register “-
4. 26 named registers “a to “z or “A to “Z
5. 4 read-only registers “:, “., “%, and “#
6. The expression register “=
7. The selection and drop registers “*, “+, and “~
8. The black hole register “_
9. Last search pattern register “/

view registers by command :reg.

Accessing a Specific Register

Enter a double quote character “, followed by the register you want to access.

“bp

Unnamed Register

If we delete(d), change(c), substitute(s), cut(x), or yank(y) content, that content would end up in the unnamed register. Vim use the register effectively as a “last used register”.

“”p

Numbered Register

Text that is yanked(y) or deleted(d) is automatically placed inside the numbered register 0~9. Each subsequent piece of content that is stored willl shift the previous stored content down to the next numbered register.

viw”2y

Named Register

It based on the alphabet, so it has 26 registers in total, and it will be used when you explicitly tell it to do so.

viw”ay : cleanup and store.
viw”Ay : append and store.

Read-Only Register

  • “. : last edit made via INSERT mode.
  • “% : name of the current file
  • “# : name of the alternative file
  • “: : most recently executed COMMAND-LINE command.

Expression Register (“=)

Entering the expression register only works when you’re inside INSERT mode.

0f1viwyea<Space>()<Esc>i<C-r>=strftime(“%Y”)-<C-r>”<CR>

Selection/Drop Register

Related to GUI version.

Blackhole Register

Last Search Register

Clearing Your Registers


Ch7 Folding

Fold Options

  • manual
  • indent
  • expr
  • syntax
  • diff
  • marker
    to change fold method: :set foldmethod=manual. The defualt fold setting is manual, it isn’t remembered after the file has been closed.

Creating Folds

When used with different motions, zf can take the following multiple forms.
* v{motion|text object}zf : fold a selection
* zf{motion|text object} : fold around a motion or text object (e.g., zf3j)
* zf’a : fold from current postion up to the a mark.
* {count}zF : fold counted number of lines from current position.

Opening/Closing/Toggling Folds

  • zc : close the fold.
  • zo : open the fold.
  • za : alternate the fold.

Open/Close All Folds

  • zM : close all folds
  • zR : open all folds

Marker

A marker fold gives the illusion of remembering the folds set in a file, when really it does this by searching the buff as it’s being read for specific tags, wrapping content we want to fold and then processing those tags.

Automatically Closing Folds

autocmd BufRead setlocal foldmethod=mark*
autocmd BufRead normal zM*

Folding by indentation

set foldmethod=indent
set foldlevel=5

Nested Folds

Folding by Syntax

:set foldmethod=syntax

Folding Content Dynamically

Folding Unchanged Lines

:setlocal diff foldmethod=diff scrollbind nowrap foldlevel=1


Ch8 VISUAL-BLOCK

Entering VISUAL-BLOCK Mode

Cmd <C-v> from NORMAL mode.

Canceling

<Esc> : escape and apply changes for all selections.
<C-c> : escape.

Adding Additional Content in Block Format

e.g., gg<C-v>4jI*<Esc>

End-of-Line Concerns

e.g., gg<C-v>$4jA!<Esc>

Better Selection Capabilities

o : opposite position of selection block
O : opposite position in the same line.
see :h visual-change


Ch9 Bulk Command Processing

Vim list: buffer, tab, window, argument. For each list type, Vim providers a command which enables us to carry out actions in bulk.
* bufdo
* windo
* tabdo
* argdo

bufdo

e.g., add a timestamp to the bottom of each file.

:bufdo exe “:normal i” . strftime(“%c”) | update

windo

The :windo command works in a similar fashion to :bufdo but with one very important difference, which is that it only works on visible buffers.

windo %s/2014/1914/ge

tabdo

In each tab, the cursor is placed in the top window, and we want the cursor to be actually in the bottom window instead.

tabdo wincmd j
see :h win-move-cursor

argdo

modifying the Arguments List

args ~/Desktop/{foo, bar, baz}.txt

Example

:argdo echo expand(‘%:p’) | bd!


Ch10 Editing Workflow

Practical Examples

Moving Around a Single File

[count]gg
105gg / 105G

Moving Around a Single Line

f / F

Moving Around Long Files

/#+\w : search using regex.

Moving Between Blocks

using % motion.

Complex Syntax

vt{x}
va{x}

Text Objects
Find and Replace

[range]s/{pattern}/{replacement}/[flags]

Workflow Management

redundant if you use a VCS.


Ch11 Search and Replace

Finding Files

:find foo.txt
:sfind foo.txt

Paths

Most system have the concept of a “load path”, this fundamental principle is that when Vim starts up, it has a path variable that holds a list of folders.
These folders are where Vim to execute find command.

:set path
:set path+=~/Desktop
:Explore / :Sexplore

Searching for Content

With the Current Buffer

Using command \
Navigating search result using n / N

\%>{line_number}l and \%<{line_number}l

Don’t Wast Time Typing

running * command when your cursor inside a word
* and # : search forward for the nearest word to the cursor.

Moving backward

?

Change Pattern Matches More Quickly

Feature for recent Vim7.4. need more study.

Searching Within Multiple Buffers
  • vimgrep
  • lvimgrep
  • grep
  • lgrep
Lists
  • vimgrep uses Vim’s quickfix list
  • lvimgrep uses Vim’s location list

    vimgrep /{searchTerm}/[gj] {path/to/project/*//java}


Search result will displayed in quickfix or location window.Commands for Quickfix and Location window Command Explanation copen/cclose Open/Close the quickfix list lopen/lclose ~ location list cnext/cprev Move cursor to next/previous quickfix result lnext/lprev ~ location result <CR> Opens file and places cursor on the match cnfile/cpfile Open the next/previous file with a match
Multiple Search History
Vim’s search stack can remember the last 10 search lists.

:colder
:cnewer

Search & Replace

Within the Current Buffer

:[range]s/{pattern}/{replacement}/[flags]
e.g., :%s/DataStore/VimStore/g
e.g., :%s/data_\?store/VimStore/gci

Regular Expressions

%s/data(_\?)(store)/Vim\1\2/gci
%s/V(im_store)/v\1/g

Diffrences in Regex Flavors
Word boundary in Vim aren’t common \b syntax but \< and \\>.
Avoiding Escaping Characters
By adding the *\v* flag before the search pattern, we can avoid the need to escape characters.

%s/\vdata(_?)(store)/Vim\1\2/gci

Tricks Specific to Vim’s Regex Flavor
  • \zs : reset the start position for your match.
  • @<=: look behind.
    /.*\zsfoo
    /\v(foo)@<=bar
Validating Substitution Patterns

:%s/^#/!!/n
Vim returns the number of mentions.

Reusing a Previous Search Pattern

/some thing
:%s//more things/g

Search & Replace Within VISUAL-BLOCK Selection

:’<,’>s/foo/bar/g
:<,’>s/\%Vfoo\%V/bar/g


Search & Replace Within Multiple Buffers

  • The Vim way (argdo)
  • The Unix way (sed)
The Vim Way

vim **/*.txt
:argdo %s/{search}/{replace}/ge | update

The Unix Way

sed -i – ‘s/search/replace/’ *.txt && rm *.txt–*

Global Command

:g/{pattern}/{command}
e.g., *:g/\v^(a|g)/:d
:[range]g[lobal][!]/{pattern}/[cmd]
e.g., :g/\w/normal3X

Expression Replacements

:%s/today/\=strftime(“%c”)/


Ch 12 Buffer/Window/Tab Management

Buffer Management

Viewing All Buffers

:ls, % indicates currently visible buffer, and # is alternative buffer.

Splitting Buffers into Windows
  1. :sba
  2. :vert sba
Diffrent Ways to Close Buffers

:bd *.php : file type based.
:bd 1 : number based
:bd 3 5
:4, 7 bd
:bufdo bd

Window Management

*Openinig Split Windows

:sp [file]
:vs [file]

Closing All but Current One

on[ly]

Changing Window Layout

<C-w>H/J/K/L : left/down/up/right

Resizing Windows
Changing window dimensions Incremently

<C-w>+/- : Increase/Reduce height by one row.
<C-w>>/<: ~ width by one column.

Changing window dimentions by a Set Amount

:resize +{n}
:resize -{n}
:vertical resize +{n}
:vertical resize -{n}

Maximizing Windows

<C-w>_
<C-w>|
<C-w>=

Moving a Window to a Tab

<C-w>T

Tab Management

Creating & Navigating Tabs

:tabnew
gt / gT, 4gt

Closing Tabs

:tabonly

Rearranging Tabs

:tabmove [n]


Ch 13 Automation

Ex mode is a variation of Vim’s COMMAND-LINE mode, meaning it has the same syntax :{command}, but instead of only being able to execute one command at a time like COMMAND-LINE mode, you can execute multiple commands, one after the other.

Automation Through Ex Mode

  • Typing ex in your terminal.
  • Starting Vim using the -E flag.
  • Executing Q from within Vim’s NORMAL mode.
  • :h holy-grail

Automation Through Macros

Recording Macros

q{register}{command}q
e.g., qa0f=wvg_xalog()<Esc>”“Pjq

Executing Macros

@{register}

  • Manually run @a two more times
  • Specify a count: 2@a
  • Manually run @@ twice. (second @ mean last executed register)
  • Specify a count with the last executed register: 2@@

e.g., qa0xf”d2li<Space><Esc>eldg_jq

Applying Macros Across Multiple Files

:bufdo normal @a
:bufdo exe “normal @a” | write

More Dynamic Macros Using the Expression Register

qaxi<C-r>=2*<C-r>”<Enter><Esc>jq
:%g{pattern}/norm @a

Editing Macros

Appending
  • qA
Editing

There is a a register looks like: qaxi<C-r>=2*<C-r>”<Enter><Esc>jq
* :put a : Write the relevant macro to the buffer.
* f2 : Find the number 2.
* r4 : Replace it with the number 4.
* 0V : Select the macro again.
* “ay : Yank the selection into the a register.
* :put : Display the udpated register.


Ch14 Lists

Change Lists

:changes

Move Back Through Our Change Positions

:changes {n}

Jump Lists

:jumps

  • <C-o> : Move to the previous jump position
  • <C-i> : Move to next jump position
    2<C-o>
Ignoring Jumps

:keepjumps


Ch15 Marks

  1. Temporary marks : only last as long as the buffer is open.
  2. Long-term marks : last until you delete them.

Creating Marks

m{a-zA-Z}

Viewing Marks

:marks

List of Marks Vim Automatically Generates Mark Explanation ‘ Marks the line where the cursor jumped from (in current buffer) ` Marks the position ~ . Marks the position where the last change occurred (in current buffer) “ ~ where the user last exited the current buffer [ Marks the beginning of the previously changed or yanked text ] ~ end of ~ < Marks the beginning of the last visual selection > ~ end of ~

Local & Global Marks

  • lowercase marks are local
  • uppercase marks are global

List of Commands for Navigating Vim Marks

Operator Explanation ]’ Next mark line position [‘ Previous ~ ]` Next mark line and column position [` Previous ~

Moving to Specific Marks

  • ‘{identifier} : line
  • `{identifier} : line & column

How to Avoid Modifying the Jump List

Use the g prefix: g’{mark} or g`{mark}

Deleting Marks

  • :delmarks A B c 1
  • :delmarks a-d

Manipulating Content with Marks

d`D


Ch 16 Sessions

Views and Sessions

View : which holds information related to a single window.
Session : which holds information related to a complete state of Vim at the time of creating the session.

Creating a View

mkview [1-9|path]

File-Based Views

~~~~

Loading a View

:loadview [1-9]
:source {path}

Creating a Session

:mksession!

it will generate a file named session.vim.

Loading a Session

:source path/to/session.vim
vim -S path/to/session.vim

Removing Sessions

Simply delete the session.vim file.


Ch 17 Plug-ins


Ch 18 Diffing

0 0