Difference between revisions of "Vi"
(→Examples) |
(→Configuring vi/vim) |
||
(4 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
{{lowercase|title=vi}} | {{lowercase|title=vi}} | ||
− | '''vi'''is a screen-oriented text editor computer program run from the [[:Category:Linux Command Line Tools|command line]]. This article will mainly discuss techniques for '''vim''' ('''vi''' improved). | + | '''vi''' is a screen-oriented text editor computer program run from the [[:Category:Linux Command Line Tools|command line]]. This article will mainly discuss techniques for '''vim''' ('''vi''' improved). |
==Commands== | ==Commands== | ||
Line 185: | Line 185: | ||
* Substitute for <code>`dos2unix`</code>: | * Substitute for <code>`dos2unix`</code>: | ||
$ vim +'set ff=unix' +wq file.txt | $ vim +'set ff=unix' +wq file.txt | ||
+ | |||
+ | * Remove ''only'' control characters/symbols: | ||
+ | <nowiki>:%s/[[:cntrl:]]//g</nowiki> | ||
+ | |||
+ | * Remove non-printable characters (note that in versions prior to ~8.1.1 this ''also'' removes non-ASCII characters): | ||
+ | <nowiki>:%s/[^[:print:]]//g</nowiki> | ||
==External commands== | ==External commands== | ||
Line 277: | Line 283: | ||
%s/^\([a-z].*[a-z]\)[ \t]*- /;\1 : / | %s/^\([a-z].*[a-z]\)[ \t]*- /;\1 : / | ||
+ | |||
+ | * Convert curly quotes to straight ones: | ||
+ | :%s/[“”]/"/g | ||
==Abbreviations== | ==Abbreviations== | ||
Line 326: | Line 335: | ||
set ts=4 # tab stop | set ts=4 # tab stop | ||
set sw=4 # shift width | set sw=4 # shift width | ||
+ | |||
+ | * See line breaks and carriage returns in the editor: | ||
+ | <pre> | ||
+ | cat >> ~/.vimrc <<EOF | ||
+ | set ffs=unix | ||
+ | set encoding=utf-8 | ||
+ | set fileencoding=utf-8 | ||
+ | set listchars=eol:¶ | ||
+ | set list | ||
+ | EOF | ||
+ | </pre> | ||
+ | |||
+ | Result: | ||
+ | My line with CRLF EOL here ^M¶ | ||
==External links== | ==External links== |
Latest revision as of 22:38, 21 June 2023
- The correct title of this article is vi. The initial letter is capitalized due to technical restrictions.
vi is a screen-oriented text editor computer program run from the command line. This article will mainly discuss techniques for vim (vi improved).
Contents
Commands
Below is a very short list of the most useful commands:
|
|
Moving around
Note: [count]
means optionally type a number first.
[count]
sentences backward:
(
[count]
sentences forward:
)
[count]
paragraphs backward:
{
[count]
paragraphs forward:
}
[count]
sections forward or to the next '{' in the first column. When used after an operator, then the '}' in the first column:
]]
[count]
sections forward or to the next '}' in the first column:
][
[count]
sections backward or to the previous '{' in the first column:
[[
[count]
sections backward or to the previous '}' in the first column:
[]
Marks
- Set mark
{a-zA-Z}
at cursor position (does not move the cursor, this is not a motion command):
m{a-zA-Z}
- Set the previous context mark. This can be jumped to with the "
" or "
``
" command (does not move the cursor, this is not a motion command):
m' #~OR~ m`
- Set mark
{a-zA-Z}
at last line number in[range]
, column 0. Default is cursor line:
:[range]ma[rk] {a-zA-Z}
- Same as
:mark
, but the space before the mark name can be omitted:
:[range]k{a-zA-Z}
- To the first non-blank character on the line with mark
{a-z}
(line-wise):
'{a-z}
- To the first non-blank character on the line with mark
{A-Z0-9}
in the correct file:
'{A-Z0-9}
- To the mark
{a-z}
:
`{a-z}
- To the mark
{A-Z0-9}
in the correct file:
`{A-Z0-9}
- List all the current marks (not a motion command):
:marks
- List the marks that are mentioned in
{arg}
(not a motion command):
:marks {arg}
Examples
- Search and delete lines: This will search for any line starting with "vi" followed by anything and delete that line.
:%g/^vi.*/d
- Delete all blank lines (with zero spaces):
:g/^$/d
- Delete all blank lines that may include spaces:
:g/^ *$/d
- Filter command: Uses multiple search criteria. This example deletes all lines starting with "ll" or "cd".
:% ! egrep -v "(^ll|^cd)"
- Find non-ASCII characters:
/[\x80-\xff]
- ROT13 text:
ggVGg?
- Edit remote files via scp (or ftp) in vim:
$ vim scp://remote_user@remote_host:remote_port//path/to/file $ vim ftp://[user@]machine[[:#]portnumber]/path
- Wrap existing text at 80 characters:
v # select the lines you wish to wrap gq :h gq # for more information
- Convert all words in a file to lowercase:
ggVGu # gg - goes to first line of text # V - turns on Visual selection, in line mode # G - goes to end of file (at the moment you have whole text selected) # u - lowercase selected area #~OR~ :%s/.*/\L&/g # lowercase :%s/[A-Z]/\L&/g # lowercase :%s/[a-z]/\U&/g # uppercase :0,$!tr "A-Z" "a-z" # lowercase
- Substitute for
`dos2unix`
:
$ vim +'set ff=unix' +wq file.txt
- Remove only control characters/symbols:
:%s/[[:cntrl:]]//g
- Remove non-printable characters (note that in versions prior to ~8.1.1 this also removes non-ASCII characters):
:%s/[^[:print:]]//g
External commands
Ctrl-Z # pause fg # resume
Bang!
- find out how many words are in the currently opened file (from the last save):
:! wc %
- check the PHP syntax of the currently opened (php) file:
:! php5 -l %
- save files with root privileges from within vim:
:w ! sudo tee %
Reading command output
- to include a list of files from a specific directory, try this read command:
:r ! ls -1 /home/user/path/etc
- grab a page, using lynx, and dump it right into your editing session without leaving vim:
:r ! lynx http://en.wikipedia.org/wiki/Vi -dump
- etc:
:r ! ls -1 /home/user/directory | sort -r :r ! grep string /var/log/apache2/site-error.log :set shell ? # check the current shell
Appending data
- append current line (under cursor) to external file:
:.w! >> /for/bar
Pre-commands
vi +10 foo
will open the file foo
and position the cursor at line 10. Another common usage is to specify a pattern:
vi +/END foo
This will open the file foo
and position the cursor at the first occurrence of the pattern 'END'.
Edit binary file in hex format
cp /bin/true /home/bob/mytrue vi mytrue # while in vi, [Esc] and :%!xxd # now in hex mode, change hex values and then revert back to binary :%!xxd -r :wq!
You can also use xxd to transform the file first, edit it, then revert/transform back to binary
xxd mytrue >mytrue.hex # edit, then xxd -r mytrue.hex >mytrue.bin
Regular expressions
Switching cases
In the replacement part of a substitution command, i.e. between the second "/" and third "/",
\u means make the following character upper case \l means make the following character lower case \U means make the rest of the replacement upper case \L means make the rest of the replacement lower case
- Make the first letter of every word from line 18 to 43 uppercase:
:18,43s/\<./\u&/g
- Change "uPPeR" and "LoweR" in any mixture of cases to lowercase:
:s/[UuLl][PpOo][PpWw][Ee][Rr]/\L&/
- Make the whole file uppercase:
:%s/.*/\U&/
- Make the region from line m to line n all uppercase:
:'m,'ns/.*/\U&/
- Make a paragraph all lowercase:
:?^$?,/^$/s/.*/\L&/
- Make the first letter of every word in a paragraph uppercase:
:?^$?,/^$/s/\([^ ][^ ]*\)/\u&/g
- Make the second word of each line uppercase:
:1,$s/^\([^ ]*\) \([^ ]*\) \(.*\)/\1 \U\2\e \3/
Misc
Change all lines containing something like the following:
foo - bar
To:
;foo : bar
%s/^\([a-z].*[a-z]\)[ \t]*- /;\1 : /
- Convert curly quotes to straight ones:
:%s/[“”]/"/g
Abbreviations
If you are like me and use vi for everything, you will find that there are certain words, phrases, bits of code, etc. that you are constantly using. These can all be stored as abbreviations.
The syntax for storing an abbreviation is as follows:
esc: # to go into command mode ab abbr phrase
For an example, say you were editing xhtml, and you wanted 'xzml
' to enter standard xml header tags of <?xml version="1.0" encoding="UTF-8" ?>
, you could enter:
:ab xzml <?xml version="1.0" encoding="UTF-8" ?>
Then, any time you enter 'xzml
' as a word, vi automatically replaces 'xzml
' with your standard table tags. The idea is to choose an abbreviation that has no chance of being a real "word", but is short and easy to remember.
Note that the above abbreviation is stored for your current session only. If you wish for it to be universally applicable and available, put the abbreviation command line in your .vimrc
file.
To list all of your abbreviations, enter
:ab
Using tabs
vi -p foo1 foo2 foo3
Or, without actual "tabs" but still opening multiple files:
vi foo1 foo2 foo3
Once vi has been started with a list of files it is possible to navigate within the list with the following commands:
- :n
- next - Move to the next file in the file list
- :rew
- rewind - rewind the file list and open the first file in the list.
Configuring vi/vim
It is possible to extensively configure vi
(or vim
) to suit your personal needs.
For an example, if you would like syntax-highlighting to be used by default for most of your code files, edit your .vimrc
file (located in your "home" directory. If one does not exist, create it) and add the following line:
syn on
Below are some other useful additions:
:set all # view all current settings :set nowrapscan # do not wrap around file when looking for a string :set number # add line numbers to left of file :set noautoindent # do not automatically indent the file :set report=0 # always report at bottom when any number of lines are yanked :set ignorecase # treat capital and small letters the same when searching :set nobackup # do _not_ create the ~ files :set nowritebackup
Control of tabs:
set expandtab set ts=4 # tab stop set sw=4 # shift width
- See line breaks and carriage returns in the editor:
cat >> ~/.vimrc <<EOF set ffs=unix set encoding=utf-8 set fileencoding=utf-8 set listchars=eol:¶ set list EOF
Result:
My line with CRLF EOL here ^M¶
External links
- Official website
- Vimdoc — the online source for Vim documentation
- Vim Regular Expresions
- Vi Helpfile — by Gábor Egressy
- Vim Cookbook — by Steve Oualline
- Vim Recipes
- Vim Commands Cheat Sheet
- Wikibooks : Learning the vi editor
- vim tips wiki
- Interactive Vim Tutorial