免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: projl
打印 上一主题 下一主题

《Learning the vi editor》 [复制链接]

论坛徽章:
0
211 [报告]
发表于 2008-06-11 15:54 |只看该作者
tags that match the given regular expression.[2] For example, :tag /normal will
find the macro NORMAL, the function normal_cmd, and so on. Use :tselect
/normal and enter the number of the tag you want.

[2] Prior to Version 5.1, vim keyed its treatment of the :tag or :tselect argument as a regular expression
based on the presence or absence of special characters. The use of / disambiguates the process.
The vi command mode commands are described in Table 11.6. Besides using the
keyboard, as in the other editors, you can also use the mouse, if mouse support
is enabled in your version of vim.

Table 11.6. vim Command Mode Tag Commands

Command

Function

^]

Look up the location of the identifier under the cursor in the tags

g

<LeftMouse>

file, and move to that location. The current location is
automatically pushed onto the tag stack.

CTRL<
LeftMouse>

Return to the previous location in the tag stack, i.e., pop off one

^T

element. A preceding count specifies how many elements to pop
off the stack.

The vim options that affect tag searching are described in Table 11.7.

Table 11.7. vim Options for Tag Management

Option

Function

Controls the number of significant characters in a tag that is to be

taglength,

looked up. The default value of zero indicates that all characters

tl

are significant.
The value is a list of filenames in which to look for tags. As a
special case, if a filename starts with ./, the dot is replaced with
tags

the directory part of the current file's pathname, making it possible
to use tags files in a different directory. The default value is
"./tags,tags".

When set to true (the default), and using a tags file in another

tagrelative

directory, filenames in that tags file are considered to be relative to
the directory where the tags file is.

The vim 5.1 distribution comes with Version 2.0.3 of the Exuberant ctags
program. As of this writing, this is the current version of Exuberant ctags.

vim can use emacs style etags files, but this is only for backwards compatibility;
the format is not documented in the vim documentation, nor is the use of etags
files encouraged.

Finally, like elvis, vim also looks up the entire word containing the cursor, not just
the part of the word from the cursor location forward.

论坛徽章:
0
212 [报告]
发表于 2008-06-11 15:54 |只看该作者
11.8.3 Infinite Undo
In vim, being able to undo and redo multiple levels of changes is controlled by
the undolevels option. This option is a number indicating how many levels of
"undo" that vim should allow. A negative value disallows any undoing (which is
not terribly useful).

When undolevels is set to a non-zero value, you enter text as normal. Then each
successive u command undoes one change. To redo (undo the undo), you use the
(rather mnemonic) CTRL-R command.

vim is different from elvis; it starts out with a default value for undolevels of
1,000, which should be close enough to infinite for any given editing session.
Also, the option is global, and not per buffer.

Once undolevels has been set, a count to either the u or ^R commands undoes
or redoes the given number of changes.

vim actually implements undoing and redoing in two different ways. When the
cpoptions (compatibility options) option contains the letter u, the u command
works like in vi, and ^R repeats the previous action (like . in nvi). When u is
absent from cpoptions, u undoes one step and ^R redoes one step. This is easier
to use, but not vi-compatible.

11.8.4 Arbitrary Length Lines and Binary Data
vim does not have a limit on the number or lengths of lines. When editing a
binary file, you should either use the -b command-line option or :set binary.
These set several other vim options that make it easier to edit binary files. To
enter 8-bit text, use ^V followed by three decimal digits.

11.8.5 Incremental Searching
As mentioned in Section 8.6.4, you enable incremental searching in vim using
:set incsearch.

The cursor moves through the file as you type. vim highlights the text that
matches what you've typed so far.

You may wish to use this with the hlsearch option, which highlights all matches
of the most recent search pattern. This option is particularly useful when looking
for all uses of a particular variable or function in program source code.

11.8.6 Left-Right Scrolling
As mentioned in Section 8.6.5, you enable left-right scrolling in vim using :set
nowrap. The value of sidescroll controls the number of characters by which vim
shifts the screen when scrolling left to right. With sidescroll set to zero, each
scroll puts the cursor in the middle of the screen. Otherwise, the screen scrolls by
the desired number of characters.

论坛徽章:
0
213 [报告]
发表于 2008-06-11 15:55 |只看该作者
vim also has several commands that scroll the window sideways, shown in Table

11.8.

Table 11.8. vim Sideways Scrolling Commands

Command

Function

zl

Scroll the window left.

zh

Scroll the window right.

zs

Scroll the window to put the cursor at the left (start) of the screen.

ze

Scroll the window to put the cursor at the right (end) of the screen.

11.8.7 Visual Mode
vim allows you to select regions one character at a time, one line at a time, or
rectangularly, using the commands shown in Table 11.9.

Table 11.9. vim Block Mode Command Characters

Command Function
v Start region selection, character at a time mode.
V Start region selection, line at a time mode.
^V Start region selection, rectangular mode.

vim highlights (using reverse video) the text as you are selecting. To make your
selection, simply use the normal motion keys. If showmode is set, vim will indicate
the mode as one of visual, visual line, or visual block. If vim is running inside an
xterm, you can also use the mouse to select text (see :help mouse-using for the
details). This also works in the GUI versions. The screen below shows a
rectangular region:

The 6th edition of <citetitle>Learning the vi Editor</citetitle>
brings the book into the late 1990&rsquo;s.


In particular, besides the &ldquo;original&rdquo; version of


<command>vi</command> that comes as a standard part of every UNIX


system, there are now a number of freely available
&ldquo;clones&rdquo;
or work-alike editors.


After applying the ~ operator, the screen looks like this:

The 6th edition of <citetitle>Learning the vi Editor</citetitle>
brings the BOOK INTO THE LATE 1990&rsquo;s.
In particulAR, BESIDES THE &LDQUo;original&rdquo; version of
<command>vi</COMMAND> THAT COMES as a standard part of every UNIX
system,
there are nOW A NUMBER OF FREELY available &ldquo;clones&rdquo;

论坛徽章:
0
214 [报告]
发表于 2008-06-11 15:56 |只看该作者
or work-alike editors.

vim permits many operations on the selected text. Some operations work only on
whole lines, even if you've selected a region that does not contain whole lines.

vim has special commands for increasing the "swept out" area, and it allows you
to apply almost any vi mode command to the highlighted text, as well as some
commands that are unique to visual mode.

When defining the area to be operated on, a number of commands make it easy
to treat words, sentences, or blocks of C/C++ code as single objects. These are
described in Table 11.10. These commands can be used by themselves to extend
the region, or they can be used in conjunction with an operator. For example, daB
deletes a brace-enclosed block of text, including the braces.

Table 11.10. vim Block Mode Object Selectors
Command Selects
aw A word (with whitespace)
iw An inner word (without whitespace)
aW A WORD (with whitespace)
iW An inner WORD (without whitespace)
as A sentence (with whitespace)
is An inner sentence (without whitespace)
ap A paragraph (with whitespace)
ip An inner paragraph (without whitespace)
ab A (...) block (includes parentheses)
ib An inner (...) block (not including the parentheses)
aB A {...} block (includes braces)
iB An inner {...} block (not including the braces)
The terms "word" and "WORD" have the same meaning as for the w and W motion
commands.

vim allows you to use many operators on highlighted text. The available
operators are summarized in Table 11.11.

Table 11.11. vim Block Mode Operations

Command

Operation

~

Flip the case of the selected text.
Move to the other end of the highlighted text. o moves from the start of
the highlighted area to end, and vice versa. O in block mode moves to

o, O

the other end of the text on the current line. You can continue sweeping
out the area from the new position.
Shift text left or right, filter text. These operate on the whole lines
<, >, !

containing the marked region. In the future, for a block, only the block
will be shifted.

=

Filters text through the program named by the equalprg option.

论坛徽章:
0
215 [报告]
发表于 2008-06-11 15:56 |只看该作者
(Typically a simple text formatter such as fmt.) This operates on the
whole lines containing the marked region.
gq
Formats the lines containing the marked region to be no longer that
what's set in textwidth. This operates on the whole lines containing
the marked region.
: Start an ex command for the highlighted lines. This operates on the
whole lines containing the marked region.
c, d, y
Change, delete, or yank text. These work even on rectangular text,
although the c command only enters text on the first line in the block.
c, r, s Change the highlighted text.
C, S, R If using CTRL-V, the rectangle is deleted and insert mode is entered in
the first line. Otherwise, whole lines are replaced.
x Delete the highlighted text.
X, Y Delete or yank the whole lines containing the highlighted area.
D
Delete to the end of the line. When using CTRL-V, the highlighted block
and the rest of the text to end of each line is deleted. If not using CTRLV,
the whole line is deleted.
J Join the highlighted lines. This operates on the whole lines containing
the marked region.
U Make uppercase. This command is unique to visual mode.
u Make lowercase. This command is unique to visual mode.
^] Use the highlighted text as the tag to find in a tag search.

11.9 Programming Assistance
vim has extensive facilities for both the edit-compile-debug cycle and syntax
highlighting.

11.9.1 Edit-Compile Speedup
The facilities in vim were inspired by the "quick fix" mode of the Manx Aztec C
compiler for the Amiga. In fact, the vim documentation refers to this feature as
"quick fix" mode. The features are quite flexible, allowing you to tailor them to
your programming environment (see Table 11.12).

Table 11.12. vim Program Development Commands

Command Function
mak[e] [arguments] Run make, based on the settings of several options as
described below, then go to the location of the first error.
Read the error file and jump to the first error. With an
cf[ile][!] errorfile, use that file for errors and set the errorfile
[errorfile] option to it. The ! forces vim to move to another buffer if
the current one has been modified but not saved.
cl[ist][!]
List the errors that include a filename. With !, list all
errors.
Display the countth next error that includes a filename. If
[count]cn[ext][!] there are no filenames at all, go to the countth next
error.

论坛徽章:
0
216 [报告]
发表于 2008-06-11 15:57 |只看该作者
[count]cN[ext][!] Display the countth previous error that includes a
filename. If there are no filenames at all, go to the
countth previous error.[count]cp[revious][!]
clast[!] [n] Display error n if supplied. Otherwise, display the last
error.
crewind[!] [n] Display error n if supplied. Otherwise, display the first
error.
cc[!] [n] Displays error n if supplied, otherwise redisplays the
current error.
cq[uit]
Quit with an error code, so that the compiler will not
compile the same file again. This is intended primarily for
use with the Amiga compiler.

Like elvis, as you move through the errors vim also compensates for changes in
the file, so that when you go to the next error, you end up on the correct line.

The vim options that control the :make command are presented in Table 11.13.

Table 11.13. vim Program Development Options
Option Value Function
shell /bin/sh The shell to use to execute the command for
rebuilding your program.
makeprg make The program that will actually handle all the
recompilation.
shellpipe 2>&1| tee
Whatever is needed to cause the shell to save
both standard output and standard error from the
compilation in the error file.
makeef /tmp/vim##.err
The name of a file which will contain the compiler
output. The ## causes vim to create unique
filenames.
errorformat %f:%l:\ %m
A description of what error messages from the
compiler look like. This example value is for GCC,
the GNU C compiler.
When you execute :make, vim constructs a command by concatenating the
various pieces described above. Any arguments you supply are passed to make in
the appropriate place. It then echoes this command to your screen. For example,
if you type :make -k, you might see something like this:

:!make -k 2>&1| tee /tmp/vim34215.err
...

By using the tee(1) program, the output from make and the compiler is saved in
the error file (/tmp/vim34215.err), and also sent to standard output, in this case
your screen.

When the make finishes, vim reads the error file, and goes to the location of the
first error. It uses the value of the errorformat option to parse the contents of
the error file, in order to find file names and line numbers. (The format of this
variable is described in full in :help errorformat.) You can then use the :cc

论坛徽章:
0
217 [报告]
发表于 2008-06-11 15:57 |只看该作者
command to see the error messages, and the :cnext command to move to the
next error.

11.9.2 Syntax Highlighting
Highlighting in vim is based primarily on colors. To enable syntax highlighting, put
syntax on into your .vimrc file. This will cause vim to read the syntax.vim file,
which defines the default highlight coloring and then sets things up to use
highlighting appropriate to each language.

vim has a very powerful sub-language for defining syntax highlighting. The
syntax.txt help file in vim 5.1 that describes it is over 1,500 lines long. Therefore,
we won't attempt to give all the details here. Instead, the sample file below
should give you some taste for what vim can do. The example consists of portions
of the syntax file for Awk:

" Vim syntax file" Language: awk, nawk, gawk, mawk" Maintainer: Antonio Colombo <antonio.colombo@jrc.org>
" Last change: 1997 November 29

" Remove any old syntax stuff hanging aroundsyn clear

" A bunch of useful Awk keywords

syn keyword awkStatement break continue delete exit
...
syn keyword awkFunction\
atan2 close cos exp int log rand sin
sqrt srand
...
syn keyword awkConditionalsyn keyword awkRepeat
if else
while for do
syn keyword awkPatternssyn keyword awkVariables
BEGIN END
ARGC ARGV FILENAME FNR FS NF NR
...
" Octal format character.

syn match awkSpecialCharacter contained "\\[0-7]\{1,3\}
"
" Hex format character.
syn match awkSpecialCharacter contained "\\x[0-9A-Fa-f]\+
"


syn match awkFieldVars "\$[0-9]\+
"


syn match awkCharClass contained "\[:[^:\]]*:\]
"
syn match awkRegExp contained "/\^"ms=s+
1
syn match awkRegExp contained "\$/"me=e-
1
syn match awkRegExp contained "[?.*{}|+]
"
..
.


" Numbers, allowing signs (both -, and +
)
" Integer number.
syn match awkNumber "[+-]\=\<[0-9]\+\>
"
" Floating point number.
syn match awkFloat "[+-]\=\<[0-9]\+\.[0-9]+\>
"
..
.

论坛徽章:
0
218 [报告]
发表于 2008-06-11 15:58 |只看该作者
syn match awkComment "#.*" contains=awkTodo

if !exists("did_awk_syntax_inits")

let did_awk_syntax_inits = 1

" The default methods for highlighting. Can be overridden later

hi link awkConditional Conditional
hi link awkFunction Function
hi link awkRepeathi link awkStatement
RepeatStatement
...
hi link awkNumber Number
hi link awkFloat Float
...
hi link awkComment Comment
...
endif
let b:current_syntax = "awk"

The file above uses syntax keyword to give names to certain classes of keywords
(such as real Awk keywords and built-in functions), and syntax match to give
names to regular expressions that match certain kinds of objects (such as
numbers). Then the hi link statements link the named classes of objects to the
predefined highlighting conventions.

The syntax.vim file predefines the standard conventions, with a number of lines
like these:

hi Comment term=bold ctermfg=Cyan guifg=#80a0ffhi Constant term=underline ctermfg=Magenta guifg=#ffa0a0hi Special term=bold ctermfg=LightRed guifg=Orangehi Identifier term=underline ctermfg=DarkCyan guifg=#40ffff
...

The first argument defines the class, and the rest define what kind of highlighting
to do on what kind of terminal. term is for a normal terminal, cterm is for a color
terminal (in this case, the ForeGround color), and gui is for vim's GUI interface.

In vim, the syntax colors are global attributes. Changing the Comment color
changes the color for all comments in all windows, no matter what programming
language you're editing.

Since the syntax descriptions use attribute linking, you can make language-
specific changes. For example, to change the comment color for Awk, you can
define attributes for awkComment, like this:

hi awkComment guifg=Green

vim comes with a large number of syntax descriptions for different languages.
The coloring for Awk is slightly psychedelic (lots of red and pink), although the
coloring for context diffs is actually rather pleasant, as is the color scheme for
UNIX mailbox files. The HTML mode is also pretty interesting. Overall, it's quite a
lot of fun to use.

论坛徽章:
0
219 [报告]
发表于 2008-06-11 15:58 |只看该作者
11.10 Interesting Features
vim is a very featureful editor. We cannot describe everything in full detail here.
Instead, we've chosen to discuss several of the most important and unique
features that it has.

Automatic file type detection

vim will notice how the lines of a text file end. It sets the fileformat
variable to one of dos (CR-LF), unix (LF), or mac (CR) to indicate the file's
current mode. By default, vim will write the file back out in the same
format, but if you change the value of fileformat, vim will use that
convention. This is an easy way to convert between Linux (or UNIX) and
MS-DOS files, and makes editing DOS files under UNIX or Linux very easy.
(In contrast, the other clones all display a ^M at the end of each line.)

vim is "charityware"

The licensing terms are described later in this chapter; they are fairly
liberal. However, the author encourages users who like vim to send a
donation to a children's center in Uganda.

Significant C programming extensions

vim has a large set of features for working with C and C++ programs.

The "auto command" facility

vim defines a large number of events, such as before or after reading a
file, entering or leaving a window, and so on. For each event, you can set
up an "auto command," i.e., a command to be executed when that event
occurs.

11.10.1 vim Is Charityware
With vim, Bram Moolenaar has taken a different approach from the usual
shareware or freeware author. If you use vim and you like it, Mr. Moolenaar
requests that you send a donation to help orphans in Uganda. We applaud his
efforts.

Mr. Moolenaar spent a year as a volunteer at Kibaale Children's Centre (KCC),
located in Kibaale, a small town in the south of Uganda, near Tanzania. The KCC
works to provide food, medical care, and education for children in this area, which
is suffering from AIDS more than in any other part of the world. Because of the
high incidence of AIDS, many of the children are orphans.

In order to continue supporting KCC, Mr. Moolenaar is trying to raise funds and
organize sponsorship. You can find a much longer explanation in the file
uganda.txt in the vim distribution. This includes directions for sending donations.
You can also look at http://www.vim.org/iccf/ .

论坛徽章:
0
220 [报告]
发表于 2008-06-11 15:59 |只看该作者
11.10.2 C and C++ Programming Features
vim, in the grand tradition of vi, is first and foremost a programmer's editor. In
particular, it is a C programmer's editor, and happily, C++ programmers can take
advantage of it too. There are lots of features that make the C programmer's life
easier. We describe the most significant ones here.

11.10.2.1 Smart indenting
All versions of vi have the autoindent option, which, when set, automatically
indents the current line by the same amount as the one next to it. This is handy
for C programmers who indent their code, and for anyone else who may need to
indicate some kind of structure in their text via indentation.

vim carries this feature further, with two options, smartindent and cindent. The
cindent option is the more interesting of the two, and is the topic of this
subsection. See Table 11.14 for a list of vim indentation and formatting options.

Table 11.14. vim Indentation and Formatting Options
Option Function
autoindent Simple-minded indentation, uses that of the previous line.
smartindent Similar to autoindent, but knows a little about C syntax.
Deprecated in favor of cindent.
cindent Enables automatic indenting for C programs, and is quite smart.
C formatting is affected by the rest of the options in this table.
cinkeys Input keys that trigger indentation options.
cinoptions Allows you to tailor your preferred indentation style.
cinwords Keywords that start an extra indentation on the following line.
formatoptions
Made up of a number of single letter flags that control several
behaviors, notably how comments are formatted as you type
them.
comments
Describes different formatting options for different kinds of
comments, both those with starting and ending delimiters, as in
C, and those that start with a single symbol and go to the end of
the line, such as in a Makefile or shell program.
When set up appropriately, vim automatically rearranges the indentation of your
C program as you type. For instance, after an if, vim automatically indents the
next line. If the body of the if is enclosed in braces, when you type the right
brace, vim will automatically indent it back one tab stop, to line up underneath
the if. As another example, with the settings shown below, upon typing the
colon that goes with a case, vim will shift the line with the case left one tab stop
to line up under the switch.

The following .vimrc produces, in our opinion, very nicely formatted C code:

set nocp incsearchset cinoptions=:0,p0,t0set cinwords=if,else,while,do,for,switch,caseset formatoptions=tcqrset cindent
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP