Chinaunix首页 | 论坛 | 博客
  • 博客访问: 68094
  • 博文数量: 22
  • 博客积分: 1406
  • 博客等级: 上尉
  • 技术积分: 190
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-13 13:18
文章分类

全部博文(22)

文章存档

2011年(1)

2010年(21)

我的朋友

分类: LINUX

2010-02-21 21:26:26

Vim Intro:

This "vi" tutorial is intended for those who wish to master and advance their skills beyond the basic features of the basic editor. It covers buffers, "vi" command line instructions, interfacing with UNIX commands, and ctags. The vim editor is an enhanced version of vi. The improvements are clearly noticed in the handling of tags.

The advantage of learning vi and learning it well is that one will find vi on all Unix based systems and it does not consume an inordinate amount of system resources. Vi works great over slow network ppp modem connections and on systems of limited resources. One can completely utilize vi without departing a single finger from the keyboard. (No hand to mouse and return to keyboard latency)

NOTE: Microsoft PC Notepad users who do not wish to use "vi" should use "gedit" (GNOME edit) or "gnp" (GNOME Note Pad) on Linux. This is very similar in operation to the Microsoft Windows editor, "Notepad". (Other Unix systems GUI editors: "dtpad", which can be found in /usr/dt/bin/dtpad for AIX, vuepad on HP/UX, or xedit on all Unix systems.)


Vim Installation:

Red Hat / CentOS / Fedora:

  • rpm -ivh vim-common-...rpm vim-minimal-...rpm vim-enhanced-...rpm vim-X11-...rpm
  • yum install vim-common vim-minimal vim-enhanced vim-X11
Ubuntu / Debian:
  • apt-get install vim vim-common vim-gnome vim-gui-common vim-runtime
Compiling Vim from source:
  • Download vim source from
  • tar xzf vim-7.0.tar.gz
  • cd vim70
  • ./configure --prefix=/opt --enable-cscope
  • make
  • make install
Basic "vi" features

One edits a file in vi by issuing the command: vi file-to-edit.txt

The vi editor has three modes, command mode, insert mode and command line mode.

  1. Command mode: letters or sequence of letters interactively command vi. Commands are case sensitive. The ESC key can end a command.
  2. Insert mode: Text is inserted. The ESC key ends insert mode and returns you to command mode. One can enter insert mode with the "i" (insert), "a" (insert after), "A" (insert at end of line), "o" (open new line after current line) or "O" (Open line above current line) commands.
  3. Command line mode: One enters this mode by typing ":" which puts the command line entry at the foot of the screen.

Partial list of interactive commands:

Cursor movement:
Keystrokes Action
h/j/k/l Move cursor left/down/up/right
spacebar Move cursor right one space
-/+ Move cursor down/up in first column
ctrl-d Scroll down one half of a page
ctrl-u Scroll up one half of a page
ctrl-f Scroll forward one page
ctrl-b Scroll back one page
M (shift-h) Move cursor to middle of page
H Move cursor to top of page
L Move cursor to bottom of page
W
w
5w
Move cursor a word at a time
Move cursor ahead 5 words
B
b
5b
Move cursor back a word at a time
Move cursor back a word at a time
Move cursor back 5 words
e
5e
Move cursor to end of word
Move cursor ahead to the end of the 5th word
0 (zero) Move cursor to beginning of line
$ Move cursor to end of line
) Move cursor to beginning of next sentence
( Move cursor to beginning of current sentence
G Move cursor to end of file
% Move cursor to the matching bracket.
Place cursor on {}[]() and type "%".
'. Move cursor to previously modified line.
'a Move cursor to line mark "a" generated by marking with keystroke "ma"
'A Move cursor to line mark "a" (global between buffers) generated by marking with keystroke "mA"
]' Move cursor to next lower case mark.
[' Move cursor to previous lower case mark.

Editing commands:

Keystrokes Action
i Insert at cursor
a Append after cursor
A Append at end of line
ESC Terminate insert mode
u Undo last change
U Undo all changes to entire line
o Open a new line
dd
3dd
Delete line
Delete 3 lines.
D Delete contents of line after cursor
C Delete contents of line after cursor and insert new text. Press esc key to end insertion.
dw
4dw
Delete word
Delete 4 words
cw Change word
x Delete character at cursor
r Replace character
R Overwrite characters from cursor onward
s Substitute one character under cursor continue to insert
S Substitute entire line and begin to insert at beginning of line
~ Change case of individual character
ctrl-a
ctrl-x
Increment number under the cursor.
Decrement number under the cursor.
/search_string{CR} Search for search_string
?search_string{CR} Search backwards (up in file) for search_string
/\<search_string\>{CR} Search for search_word
Ex: /\
Search for variable "s" but ignore declaration "string" or words containing "s". This will find "string s;", "s = fn(x);", "x = fn(s);", etc
n Find next occurrence of search_word
N Find previous occurrence of search_word
. repeat last command action.

Terminate session:

  • Use command: ZZ
    Save changes and quit.
  • Use command line: ":wq"
    Save (write) changes and quit.
  • Use command line: ":w"
    Save (write) changes without quitting.
  • Use command line: ":q!"
    Ignore changes and quit. No changes from last write will be saved.
  • Use command line: ":qa"
    Quit all files opened.

Advanced "vi" features

Interactive Commands:

  • Marking a line:
    Any line can be "Book Marked" for a quick cursor return.
    • Type the letter "m" and any other letter to identify the line.
    • This "marked" line can be referenced by the keystroke sequence "'" and the identifying letter.
      Example: "mt" will mark a line by the identifier "t".
      "'t" will return the cursor to this line at any time.
      A block of text may be referred to by its marked lines. i.e.'t,'b
  • vi line buffers:
    To capture lines into the buffer:
    • Single line: "yy" - yanks a single line (defined by current cursor position) into the buffer
    • Multiple lines: "y't" - yanks from current cursor position to the line marked "t"
    • Multiple lines: "3yy" - yank 3 lines. Current line and two lines below it.
    Copy from buffer to editing session:
    • "p" - place contents of buffer after current line defined by current cursor position.
  • vim: Shift a block of code left or right:
    • Enter into visual mode by typing the letter "v" at the top (or bottom) of the block of text to be shifted.
    • Move the cursor to the bottom (or top) of the block of text using "j", "k" or the arrow keys.
      Tip: Select from the first collumn of the top line and the last character of the line on the bottom line.
      Zero ("0") will move the cursor to the first character of a line and "$" will move the cursor to the last character of the line.
    • Type >> to shift the block to the right.
      Type << to shift the block to the left.
    Note: The number of characters shifted is controlled by the "shift width" setting. i.e. 4: ":set sw=4"
    This can be placed in your $HOME/.vimrc file.

Command Line:

  • command options:
    The vi command line interface is available by typing ":". Terminate with a carriage return.
    Example commands:
    • :help topic
      If the exact name is unknown, TAB completion will cycle through the various options given the first few letters. Ctrl-d will print the complete list of possibilites.
    • :set all - display all settings of your session.
    • :set ic - Change default to ignore case for text searches
      Default is changed from noignorecase to ignorecase. (ic is a short form otherwise type set ignorecase)
    • Common options to set:
      Full "set" Command Short form Description
      autoindent/noautoindent ai/noai {CR} returns to indent of previous line
      autowrite/noautowrite aw/noaw See tags
      errorbells/noerrorbells eb/noeb Silence error beep
      flash/noflash fl/nofl Screen flashes upon error (for deaf people or when noerrorbells is set)
      tabstop=8 ts Tab key displays 8 spaces
      ignorecase/noignorecase ic/noic Case sensitive searches
      number/nonumber nu/nonu Display line numbers
      showmatch/noshowmatch no abbreviations Cursor shows matching ")" and "}"
      showmode/noshowmode no abbreviations Editor mode is displayed on bottom of screen
      taglength tl Default=0. Set significant characters
      closepunct='".,;)]}
      % key shows matching symbol.
      Also see showmatch
      linelimit=1048560
      Maximum file size to edit
      wrapscan/nowrapscan ws/nows Breaks line if too long
      wrapmargin=0/nowrapmargin wm/nowm Define right margin for line wrapping.
      list/nolist
      Display all Tabs/Ends of lines.
      bg=dark
      bg=light

      VIM: choose color scheme for "dark" or "light" console background.

  • Executing Unix commands in vi:
    Any UNIX command can be executed from the vi command line by typing an "!" before the UNIX command.
    Examples:
    • ":!pwd" - shows your current working directory.
    • ":r !date" - reads the results from the date command into a new line following the cursor.
    • ":r !ls -1" - Place after the cursor, the current directory listing displayed as a single column.
  • Line numbers:
    Lines may be referenced by their line numbers. The last line in the file can be referenced by the "$" sign.
    The entire file may be referenced by the block "1,$" or "%"
    The current line is referred to as "."
    A block of text may be referred to by its marked lines. i.e. 5,38 or 't,'b
  • Find/Replace:
    Example:
    • :%s/fff/rrrrr/ - For all lines in a file, find string "fff" and replace with string "rrrrr" for the first instance on a line.
    • :%s/fff/rrrrr/g - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line.
    • :%s/fff/rrrrr/gc - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line. Ask for confirmation
    • :%s/fff/rrrrr/gi - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line. Case insensitive.
    • :'a,'bs/fff/rrrrr/gi - For all lines between line marked "a" (ma) and line marked "b" (mb), find string "fff" and replace with string "rrrrr" for each instance on a line. Case insensitive.
    • :%s/*$/ - For all lines in a file, delete blank spaces at end of line.
    • :%s/\(.*\):\(.*\)/\2:\1/g - For all lines in a file, move last field delimited by ":" to the first field. Swap fields if only two.
    For more info type:
    • :help substitute
    • :help pattern
    • :help gdefault
    • :help cmdline-ranges
  • Sorting:
    Example:
    • Mark a block of text at the top line and bottom line of the block of text. i.e. "mt" and "mb" on two separate lines. This text block is then referenced as "'t,'b.
    • :'t,'b !sort

  • Moving columns, manipulating fields and awk:
    :'t,. !awk '{print $3 " " $2 " " $1}' - This will reverse the order of the columns in the block of text. The block of text is defined here as from the line marked with the keystroke "bt" and the current line ("."). This text block is referenced as "'t,."
                  aaa bbb ccc              ccc bbb aaa
    xxx yyy zzz becomes-> zzz yyy xxx
    111 222 333 333 222 111
  • Source Code Formatting: C++/Java
    • Use vim visual text selection to mark the lines to format (beautify):
      • eg. Whole file:
        • Go to first line in file: shift-v
        • Go to last line in file: shift-g
        • Select the key equals: =
      This will align all braces and indentations. For the equivalent in emacs see the .
  • Text Formatting:
    • Mark a block of text at the top line and bottom line of the block. i.e. "mt" and "mb" on two separate lines.
    • Example: ":'t,'b !nroff"
    • You can insert nroff commands i.e.:
      .ce 3 Center the next three lines
      .fi Fill text - left and right justify (default)
      .nf No Fill
      .ls 2 Double line spacing
      .sp Single line space
      .sv 1.0i Vertical space at top of page space
      .ns Turn off spacing mode
      .rs Restore spacing mode
      .ll 6.0i Line length = 6 inches
      .in 1.0i Indent one inch
      .ti 1.0i Temporarily one time only indent one inch
      .pl 8.0i Page length = 8 inches
      .bp Page break
      Example:
      .fi
      .pl 2i
      .in 1.0i
      .ll 6.0i
      .ce
      Title to be centered
      .sp
      The following text bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla

      Becomes:

                               Title to be centered

      The following text bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla bla bla bla bla bla bla bla bla
      bla bla bla bla


  • Spell Checking:
    • Mark a block of text by marking the top line and bottom line of the block. i.e. "mt" and "mb" on two separate lines.
    • :'t,'b !spell will cause the block to be replaced with misspelled words.
    • Press "u" to undo.
    • Proceed to correct words misspelled.
  • Macros:
    :map letter commands_strung_together
    :map - lists current key mappings
    Example - :map g n cwNEW_WORD{ctrl-v}{esc}i{ctrl-v}{CR}
    This example would find the next search occurrence, change the word and insert a line feed after the word. The macro is invoked by typing the letter "g".
    • Control/Escape/Carriage control characters must be prefixed with ctrl-V.
    • Choose a letter which is not used or important. (i.e. a poor choice would be "i" as this is used for insert)
  • Double spacing:
    • :%s/$/{ctrl-V}{CR}/g
      This command applies an extra carriage return at the end of all lines
  • Strip blanks at end of line:
    • :%s/{TAB}*$//
  • Delete all lines beginning with or matching a pattern:
    • :1,$ /^#/d
      Delete all (first to last line: 1,$ or g) comments lines in file. Delete all lines beginning (^) with "#" (specify text pattern).
    • :g/#/d
      Delete all lines (g) containing comments (comments follow "#") in file. Delete all lines containing "#".
    • :g!/^#/d
      Delete all lines except (g! or v) comment lines beginning (^) with "#".
  • Strip DOS ctrl-M's:
    • :1,$ s/{ctrl-V}{ctrl-M}//

    Note: In order to enter a control character, one muust first enter ctrl-v. This is true throughout vi. For example, if searching for a control character (i.e. ctrl-m): /ctrl-v ctrl-M If generating a macro and you need to enter esc without exiting the vi command line the esc must be prefixed with a ctrl-v: ctrl-v esc.
  • Editing multiple files:
    • vi file1 file2 file3
    • :n Edit next file (file2)
    • :n Edit next file (file3)
    • :rew Rewind to the first file (file1)
  • Line folding:

    Many times one may encounter a file with folded lines or may wish to fold lines. The following image is of a file with folded lines where each "+" represents a set of lines not viewed but a marker line prefixed with a "+" is shown stating how many lines have been folded and out of view. Folding helps manage large files which are more easily managed when text lines are grouped into "folds".

    Example: vim /usr/share/vim/vim63/plugin/netrw.vim

    VIM folded lines

    Keystrokes:

    Keystroke Description
    zR Unfold all folded lines in file.
    za Open/close (toggle) a folded group of lines.
    zA Open a closed fold or close an open fold recursively.
    zc Close a folded group of lines.
    zC Close all folded lines recursively.
    zd Delete a folded line.
    zD Delete all folded lines recursively.
    zE Eliminate all folded lines in file.
    zF Create "N" folded lines.
  • Hyper-Linking to include files:
    • Place cursor over the file name (i.e. #include "fileABC.h")
    • Enter the letter combination: gf
      (go to file)
    This will load file fileABC.h into vim. Use the following entry in your ~/.vimrc file to define file paths. Change path to something appropriate if necessary.
    "Recursively set the path of the project.
    set path=$PWD/**
  • Batch execution of vi from a command file:
    Command file to change HTML file to lower case and XHTML compiance:
    :1,$ s///g
    :1,$ s/<\/HTML>/<\/html>/g
    :1,$ s///g
    :1,$ s/<\/HEAD>/<\/head>/g
    :1,$ s//<title>/g<br>:1,$ s/<\/TITLE>/<\/title>/g<br>:1,$ s/<BODY/<body/g<br>:1,$ s/<\/BODY/<\/body/g<br>:1,$ s/<UL>/<ul>/g<br>:1,$ s/<\/UL>/<\/ul>/g<br>...<br>..<br>.<br>:1,$ s/<A HREF/<a href/g<br>:1,$ s/<A NAME/<a name/g<br>:1,$ s/<\/A>/<\/a>/g<br>:1,$ s/<P>/<p>/g<br>:1,$ s/<B>/<b>/g<br>:1,$ s/<\/B>/<\/b>/g<br>:1,$ s/<I>/<i>/g<br>:1,$ s/<\/I>/<\/i>/g<br>:wq<br> <br></pre> </td> </tr> </tbody> </table> </dd></dl>Execute: <tt>vi -e <i>file-name</i>.html < </tt> <p><font color="#ff0000">[Potential Pitfall]</font>: This must be performed while vim has none of the files open which are to be affected. If it does, vim will error due to conflicts with the vim swap file.</p> </li></ul> <hr> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#ffcc33"> <td><b><big>Tagging:</big></b></td> </tr> </tbody> </table> <p>This functionality allows one to jump between files to locate subroutines.</p> <dl><dd> <ul><li><b>ctags *.h *.c</b> This creates a file names "tags".</li></ul> </dd></dl> <p>Edit the file using <b>vi</b>.</p> <dl><dd> <ul><li>Unix command line: <b><tt>vi -t   subroutine_name</tt></b> This will find the correct file to edit.<br> OR</li><li>Vi command line: <b><tt>:tag subroutine_name</tt></b> This will jump from your current file to the file containing the subroutine. (short form <b><tt>:ta subroutine_name</tt></b> )<br> OR</li><li>By cursor position: <b>ctrl-]</b> Place cursor on the first character of the subroutine name and press <b>ctrl-]</b> This will jump to the file containing the subroutine.<br> <b>Note:</b> The key combination <tt>ctrl-]</tt> is also the default telnet connection interrupt. To avoid this problem when using telnet block this telnet escape key by specifying NULL or a new escape key: <ul><li><tt>telnet -E <i>file-name</i></tt></li><li><tt>telnet -e "" <i>file-name</i></tt></li></ul> </li></ul> </dd></dl> <p>In all cases you will be entered into the correct file and the cursor will be positioned at the subroutine desired.<br> If it is not working properly look at the "tags" file created by <b>ctags</b>. Also the tag name (first column) may be abbreviated for convenience. One may shorten the significant characters using <b>:set taglength=number</b></p> <p>Tag Notes:</p> <ul><li>A project may have a tags file which can be added and referred to by: <b><tt>:set tags=tags\ /ad/src/project1.tags</tt></b><br> A "\" must separate the file names.</li><li><b><tt>:set autowrite</tt></b> will automatically save changes when jumping from file to file, otherwise you need to use the <b>:w</b> command.</li></ul> <p><b>vim tagging notes:</b> (These specific tag features not available in vi)</p> <table border="1"> <tbody> <tr bgcolor="#c0c0c0"> <th>Tag Command</th> <th>Description</th> </tr> <tr> <td><tt>:tag <i>start-of-tag-name_</i>TAB</tt></td> <td>Vim supports tag name completion. Start the typing the tag name and then type the TAB key and name completion will complete the tag name for you.</td> </tr> <tr> <td><tt>:tag /<i>search-string</i></tt></td> <td>Jump to a tag name found by a search.</td> </tr> <tr> <td valign="top"><b><tt>ctrl-]</tt></b></td> <td>The vim editor will jump into the tag to follow it to a new position in the file or to a new file.</td> </tr> <tr> <td valign="top"><b><tt>ctrl-t</tt></b></td> <td>The vim editor will allow the user to jump back a level.<br> (or <tt>:pop</tt>)</td> </tr> <tr> <td valign="top"><b><tt>:tselect <i><function-name></i></tt></b></td> <td>When multiple entries exist in the tags file, such as a function declaration in a header file and a function definition (the function itself), the operator can choose by issuing this command. The user will be presented with all the references to the function and the user will be prompted to enter the number associated with the appropriate one.</td> </tr> <tr> <td valign="top"><b><tt>:tnext</tt></b></td> <td>When multiple answers are available you can go to the next answer.</td> </tr> <tr> <td valign="top"><tt>:set ignorecase</tt><br> (or <tt>:set ic</tt>)</td> <td>The ignore case directive affects tagging.</td> </tr> <tr> <td valign="top"><tt>:tags</tt></td> <td>Show tag stack (history)</td> </tr> <tr> <td valign="top"><tt>:4pop</tt></td> <td>Jump to a particular position in the tag stack (history).<br> (jump to the 4th from bottom of tag stack (history).<br> The command "<tt>:pop</tt>" will move by default "1" backwards in the stack (history).)<br> or<br> <tt>:4tag</tt><br> (jump to the 4th from top of tag stack)</td> </tr> <tr> <td><tt>:tnext</tt></td> <td>Jump to next matching tag.<br> (Also short form <tt>:tn</tt> and jump two <tt>:2tnext</tt>)</td> </tr> <tr> <td valign="top"><tt>:tprevious</tt></td> <td>Jump to previous matching tag.<br> (Also short form <tt>:tp</tt> and jump two <tt>:2tp</tt>)</td> </tr> <tr> <td valign="top"><tt>:tfirst</tt></td> <td>Jump to first matching tag.<br> (Also short form <tt>:tf</tt>, <tt>:trewind</tt>, <tt>:tr</tt>)</td> </tr> <tr> <td valign="top"><tt>:tlast</tt></td> <td>Jump to last matching tag.<br> (Also short form <tt>:tl</tt>)</td> </tr> <tr> <td valign="top"> <pre>:set tags=./tags,./<i>subdir</i>/tags<br></pre> </td> <td>Using multiple tag files (one in each directory).<br> Allows one to specify all tags files in directory tree: <tt>set tags=src/**/tags</tt><br> Use Makefile to generate tags files as well as compile in each directory.</td> </tr> </tbody> </table> <p>Links:</p> <ul><li></li><li></li><li></li></ul> <hr> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#ffcc33"> <td><b><big>The ctags utility:</big></b></td> </tr> </tbody> </table> <p>There are more than one version of ctags out there. The original Unix version, the GNU version and the version that comes with vim. This discussion is about the one that comes with vim. (default with Red Hat)</p> <p>For use with C++:</p> <ul><li>ctags version 5.5.4: <pre> ctags *.cpp ../inc/*.h<br><br> </pre> </li><li>ctags version 5.0.1: <pre> --lang=c++ --c-types=+Ccdefgmnpstuvx *.cpp ../inc/*.h<br><br></pre> </li></ul> <p>To generate a tags file for all files in all subdirectories: <tt>ctags -R .</tt> </p> <p>The ctags program which is written by the VIM team is called " Exuberant Ctags" and supports the most features in VIM.</p> <p>Man page: - Generate tag files for source code</p> <hr> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#ffcc33"> <td><b><big>Defaults file:</big></b></td> </tr> </tbody> </table> <p><b>VIM: <tt>$HOME/.exrc</tt></b></p> <ul><li><tt>~/.vimrc</tt></li><li><tt>~/.gvimrc</tt></li><li><tt>~/.vim/</tt> (directory of vim config files.)</li></ul> <p><b>VI: <tt>$HOME/.exrc</tt></b></p> <dl><dd> Example: <table width="100%" bgcolor="#000000" border="1" cellpadding="4" cellspacing="1"> <tbody> <tr bgcolor="#c0c0c0"> <td> <pre> set autoindent<br> set wrapmargin=0<br> map g hjlhjlhjlhlhjl<br> "<br> " S = save current vi buffer contents and run spell on it,<br> " putting list of misspelled words at the end of the vi buffer.<br> map S G:w!^M:r!spell %^M<br> colorscheme desert<br> "Specify that a dark terminal background is being used.<br> set bg=dark<br> <br></pre> </td> </tr> </tbody> </table> </dd></dl> <p>Notes:</p> <ul><li>Look in <tt>/usr/share/vim/vim61/colors/</tt> for available colorschemes.<br> (I also like "colorscheme desert")</li><li>Alternate use of autoindent: <tt>set ai sw=3</tt></li></ul> <p></p> <hr> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#ffcc33"> <td><b><big>Using vim and cscope:</big></b></td> </tr> </tbody> </table> <p>Cscope was developed to cross reference C source code. It now can be used with C++ and Java and can interface with vim.</p> <p>Using Cscope to cross reference souce code will create a database and allow you to traverse the source to find calls to a function, occurances of a function, variable, macros, class or object and their respective declarations. Cscope offers more complete navigation than ctags as it has more complete cross referencing.</p> <p>Vim must be compiled with Cscope support. Red Hat Enterprise Linux 5 (or CentOS 5), includes vim 7.0 with cscope support. Earlier versions of Red Hat or Fedora RPM does not support Cscope and thus must be compiled.</p> <h4>Compiling Vim from source:</h4> <ul><li>Download vim source from </li><li><tt>tar xzf vim-7.0.tar.gz</tt></li><li><tt>cd vim70</tt></li><li><tt>./configure --prefix=/opt --enable-cscope</tt></li><li><tt>make</tt></li><li><tt>make install</tt></li></ul> <h4>Using Cscope with vim:</h4>The Cscope database (<tt>cscope.out</tt>) is generated the first time it is invoked. Subsequent use will update the database based on file changes.<br> The database can be generated manually using the command i.e.: <tt>cscope -b *.cpp *.h</tt> or <tt>cscope -b -R .</tt> <p>Invoke Cscope from within vim from the vim command line. Type the following: <tt>:cscope find <i>search-type search-string</i></tt> The short form of the command is ":cs f" where the "search-type" is:</p> <dl><dd> <table border="1"> <tbody> <tr> <th>Search Type</th> <th>Type short form</th> <th>Description</th> </tr> <tr> <td>symbol</td> <td>s</td> <td>Find all references to a symbol</td> </tr> <tr> <td>global</td> <td>g</td> <td>Find global definition</td> </tr> <tr> <td>calls</td> <td>c</td> <td>Find calls of this function</td> </tr> <tr> <td>called</td> <td>d</td> <td>Find functions that the specified function calls</td> </tr> <tr> <td>text</td> <td>t</td> <td>Find specified text string</td> </tr> <tr> <td>file</td> <td>f</td> <td>Open file</td> </tr> <tr> <td>include</td> <td>i</td> <td>Find files that "#include" the specified file</td> </tr> </tbody> </table> </dd></dl> <p>Results of the Cscope query will be displayed at the bottom of the vim screen.</p> <ul><li>To jump to a result type the results number (+ enter)</li><li>Use tags commands to return after a jump to a result: <tt>ctrl-t</tt><br> To return to same spot as departure, use <tt>ctrl-o</tt></li><li>To use "tags" navigation to search for words under the cursor (ctrl-\) instead of using the vim command line "<tt>:cscope</tt>" (and "ctrl-spaceBar" instead of "<tt>:scscope</tt>"), use the vim plugin, <tt></tt> []<br> When using this plugin, overlapping ctags navigation will not be available. This should not be a problem since cscope plugin navigation is the same but with superior indexing and cross referenceing.<br> Place this plugin in your directory "<tt>$HOME/.vim/plugin</tt>"<br> Plugin required for vim 5 and 6. This feature is compiled in with vim 7.0 on Red Hat Enterprise Linux 5 and CentOS 5 and newer Linux OS's. Attempts to use the plugin when not required will result in the following error: <dl><dd><tt>E568: duplicate cscope database not added</tt></dd></dl> </li><li>Cycle through results: <ul><li>Next result: <tt>:tnext</tt></li><li>Previous result: <tt>:tprevious</tt></li></ul> </li><li>Create a split screen for Cscope results: <tt>:scscope find <i>search-type search-string</i></tt><br> (Short form: <tt>:scs f <i>search-type search-string</i></tt>)</li><li>Use command line argument "<tt>:cscope -R</tt>": Scan subdirectories recursively</li><li>Use Cscope ncurses based GUI without vim: <tt>cscope</tt> <ul><li>ctrl-d: Exit Cscope GUI</li></ul> </li></ul> <h4>Cscope command line arguments:</h4> <dl><dd> <table border="1"> <tbody> <tr> <th>Argument</th> <th>Description</th> </tr> <tr> <td>-R</td> <td>Scan subdirectories recursively</td> </tr> <tr> <td>-b</td> <td>Build the cross-reference only.</td> </tr> <tr> <td>-C</td> <td>Ignore letter case when searching.</td> </tr> <tr> <td>-f<tt>FileName</tt></td> <td>Specify Cscope database file name instead of default "cscope.out".</td> </tr> <tr> <td>-I<i>include-directories</i></td> <td>Look in "include-directories" for any #include files whose names do not begin with "/".</td> </tr> <tr> <td>-i<i>Files</i></td> <td>Scan specified files listed in "Files". File names are separated by linefeed. Cscope uses the default file name "cscope.files".</td> </tr> <tr> <td>-k</td> <td>Kernel mode ignores <tt>/usr/include</tt>.<br> Typical: <tt>cscope -b -q -k</tt></td> </tr> <tr> <td>-q</td> <td>create inverted index database for quick search for large projects.</td> </tr> <tr> <td>-s<i>DirectoryName</i></td> <td>Use specified directory for source code. Ignored if specified by "-i".</td> </tr> <tr> <td>-u</td> <td>Unconditionally build a new cross-reference file..</td> </tr> <tr> <td>-v</td> <td>Verbose mode.</td> </tr> <tr> <td><i>file1 file2 ...</i></td> <td>List files to cross reference on the command line.</td> </tr> </tbody> </table> </dd></dl> <h4>Cscope environment variable:</h4> <dl><dd> <table border="1"> <tbody> <tr> <th>Environment Variable</th> <th>Description</th> </tr> <tr> <td>CSCOPE_EDITOR</td> <td>Editor to use: <tt>/usr/bin/vim</tt></td> </tr> <tr> <td>EDITOR</td> <td>Default: <tt>/usr/bin/vim</tt></td> </tr> <tr> <td>INCLUDEDIRS</td> <td>Colon-separated list of directories to search for #include files.</td> </tr> <tr> <td>SOURCEDIRS</td> <td>Colon-separated list of directories to search for additional source files.</td> </tr> <tr> <td>VPATH</td> <td>Colon-separated list of directories to search. If not set, cscope searches only in the current directory.</td> </tr> </tbody> </table> </dd></dl> <hr> <p>Manually Generating file <tt>cscope.files</tt></p> <dl><dd> File: <tt>$HOME/bin/gen_cscope</tt> or <tt>/opt/bin/gen_cscope</tt> <table width="100%" bgcolor="#000000" border="1" cellpadding="4" cellspacing="1"> <tbody> <tr bgcolor="#c0c0c0"> <td> <pre>#!/bin/bash<br>find ./ -name "*.[ch]pp" -print > cscope.files<br>cscope -b -q -k<br></pre> </td> </tr> </tbody> </table>Generates <tt>cscope.files</tt> of ".cpp" and ".hpp" source files for a C++ project. <p>Note that this generates CScope files in the current working directory. The CScope files are only usefull if you begin the vim session in the same directory. Thus if you have a heirarchy of directories, perform this in the top directory and reference the files to be edited on the command line with the relative path from the same directory in which the CScope files were generated.</p> </dd></dl> <hr> <p>Also see:</p> <ul><li></li><li></li><li></li></ul> <p></p> <hr> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#ffcc33"> <td><b><big>Vim plugins:</big></b></td> </tr> </tbody> </table> <p><b>Vim default plugins:</b></p> <p>Vim comes with some default plugins which can be found in:</p> <ul><li>Red Hat / CentOS / Fedora: <ul><li>RHEL4: <tt>/usr/share/vim/vim70/autoload/</tt></li><li>Fedora 3:<tt>/usr/share/vim/vim63/plugin/</tt></li></ul> </li><li>Ubuntu / Debian: <ul><li>Ubuntu 6.06: <tt>/usr/share/vim/vim64/plugin/</tt></li></ul> </li></ul> <p><b>Additional custom plugins:</b></p> <p>User added plugins are added to the user's local directory: <tt>~/.vim/plugin/</tt> or <tt>~/.vimrc/plugin/</tt></p> <ul><li>Vim.org: </li></ul> <hr noshade="noshade" size="5"> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#b0b0b0"> <td><b><big>Default vim plugins:</big></b></td> </tr> </tbody> </table> <h4>File Explorer / List Files: <tt>explorer.vim</tt></h4> <p>Help is available with the following command: <tt>:help file-explorer</tt></p> <dl><dd> <table border="1"> <tbody> <tr bgcolor="#c0c0c0"> <th>Command</th> <th>Description</th> </tr> <tr> <td valign="top">:Explore</td> <td valign="top">List files in your current directory</td> </tr> <tr> <td valign="top">:Explore <i>directory-name</i></td> <td valign="top">List files in specified directory</td> </tr> <tr> <td valign="top">:Vexplore</td> <td valign="top">Split with a new vertical window and then list files in your current directory</td> </tr> <tr> <td valign="top">:Sexplore</td> <td valign="top">Split with a new horizontal window and then list files in your current directory</td> </tr> </tbody> </table> </dd></dl> <p>The new window buffer created by ":Vexplore" and ":Sexplore" can be closed with ":bd" (buffer delete).</p> <hr noshade="noshade" size="5"> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#b0b0b0"> <td><b><big>Additional custom plugins:</big></b></td> </tr> </tbody> </table> <h4>CScope: <tt>cscope_maps.vim</tt></h4>See cscope and vim description and use . <hr> <h4>Tabbed pages: <tt>minibufexpl.vim</tt></h4>This plugin allows you to open multiple text files and accessed by their tabs displayed at the top of the frame. <dl><dd> <table border="1"> <tbody> <tr bgcolor="#c0c0c0"> <th>Keystroke</th> <th>Description</th> </tr> <tr> <td>:bn</td> <td>New buffer</td> </tr> <tr> <td>:bd</td> <td>Buffer delete</td> </tr> <tr> <td>:b3</td> <td>Go to buffer number 3</td> </tr> <tr> <td>ctrl-w followed by "k"</td> <td>New buffer. Puts curson in upper tabbed portion of window. Navigate with arrow keys or "h"/"l".</td> </tr> <tr> <td>:qa</td> <td>Quit vim out of all buffers</td> </tr> <tr> <td>tab</td> <td>The "tab" key jumps between tabbed buffers.</td> </tr> </tbody> </table> </dd></dl> <p>Recommended <tt>~/.vimrc</tt> file entry:</p> <dl><dd> <table width="100%" bgcolor="#000000" border="1" cellpadding="4" cellspacing="1"> <tbody> <tr bgcolor="#c0c0c0"> <td> <pre>"Hide abandon buffers in order to not lose undo history.<br>set hid<br></pre> </td> </tr> </tbody> </table>This vim directive will allow undo history to remain when switching buffers. </dd></dl> <p>The new window buffer tab created can be closed with ":bd" (buffer delete).</p> <p>Links:</p> <ul><li></li></ul> <hr> <h4>Alternate between the commensurate include and source file: <tt>a.vim</tt></h4>Most usefull when used with the vim plugin "minibufexpl.vim" <p>Usefull for C/C++ programmers to switch between the source ".cpp" and commensurate ".hpp" or ".h" file and vice versa.</p> <dl><dd> <table border="1"> <tbody> <tr bgcolor="#c0c0c0"> <th>Command</th> <th>Description</th> </tr> <tr> <td>:A</td> <td>switches to the header file corresponding to the current file being edited (or vise versa)</td> </tr> <tr> <td>:AS</td> <td>splits and switches</td> </tr> <tr> <td>:AV</td> <td>vertical splits and switches</td> </tr> <tr> <td>:AT</td> <td>new tab and switches</td> </tr> <tr> <td>:AN</td> <td>cycles through matches</td> </tr> <tr> <td>:IH</td> <td>switches to file under cursor</td> </tr> <tr> <td>:IHS</td> <td>splits and switches</td> </tr> <tr> <td>:IHV</td> <td>vertical splits and switches</td> </tr> <tr> <td>:IHT</td> <td>new tab and switches</td> </tr> <tr> <td>:IHN</td> <td>cycles through matches</td> </tr> </tbody> </table>If you are editing <tt>fileX.c</tt> and you enter ":A" in vim, you will be switched to the file <tt>fileX.h</tt> </dd></dl> <p>Links:</p> <ul><li></li></ul> <hr> <table width="100%" border="0" cellpadding="2" cellspacing="0"> <tbody> <tr bgcolor="#ffcc33"> <td><b><big>Vim tip:</big></b></td> </tr> </tbody> </table> <p>Using a mousewheel with vim in an xterm. Place in file <tt>$HOME/.Xdefaults</tt></p> <dl><dd> <table width="100%" bgcolor="#000000" border="1" cellpadding="4" cellspacing="1"> <tbody> <tr bgcolor="#c0c0c0"> <td> <pre>XTerm*VT100.Translations: #override \n\ <br>: string("0x9b") string("[64~") \n\ <br>: string("0x9b") string("[65~")<br></pre></td></tr></tbody></table></dd></dl></td></tr></tbody></table> </div> <!-- <div class="Blog_con3_1">管理员在2009年8月13日编辑了该文章文章。</div> --> <div class="Blog_con2_1 Blog_con3_2"> <div> <!--<img src="/image/default/tu_8.png">--> <!-- JiaThis Button BEGIN --> <div class="bdsharebuttonbox"><A class=bds_more href="#" data-cmd="more"></A><A class=bds_qzone title=分享到QQ空间 href="#" data-cmd="qzone"></A><A class=bds_tsina title=分享到新浪微博 href="#" data-cmd="tsina"></A><A class=bds_tqq title=分享到腾讯微博 href="#" data-cmd="tqq"></A><A class=bds_renren title=分享到人人网 href="#" data-cmd="renren"></A><A class=bds_weixin title=分享到微信 href="#" data-cmd="weixin"></A></div> <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> <!-- JiaThis Button END --> </div> 阅读(3460) | 评论(0) | 转发(0) | <div class="HT_line3"></div> </div> <div class="Blog_con3_3"> <div><span id='digg_num'>0</span><a href="javascript:void(0)" id='digg' bid='750193' url='/blog/digg.html' ></a></div> <p>上一篇:<a href="/uid-20740995-id-750192.html">How to Exchange Two Variables without Others</a></p> <p>下一篇:<a href="/uid-20740995-id-750194.html">Stack and Heap in Memory</a></p> </div> </div> <!-- <div class="Blog_con3_4 Blog_con3_5"> <div class="Blog_tit2 Blog_tit7">热门推荐</div> <ul> <li><a href="" title="" target='blank' ></a></li> </ul> </div> --> </div> </div> <div class="Blog_right1_7" id='replyList'> <div class="Blog_tit3">给主人留下些什么吧!~~</div> <!--暂无内容--> <!-- 评论分页--> <div class="Blog_right1_6 Blog_right1_12"> </div> <!-- 评论分页--> <div class="Blog_right1_10" style="display:none"> <div class="Blog_tit3">评论热议</div> <!--未登录 --> <div class="Blog_right1_8"> <div class="nologin_con1"> 请登录后评论。 <p><a href="http://account.chinaunix.net/login" onclick="link(this)">登录</a> <a href="http://account.chinaunix.net/register?url=http%3a%2f%2fblog.chinaunix.net">注册</a></p> </div> </div> </div> <div style="text-align:center;margin-top:10px;"> <script type="text/javascript" smua="d=p&s=b&u=u3118759&w=960&h=90" src="//www.nkscdn.com/smu0/o.js"></script> </div> </div> </div> </div> <input type='hidden' id='report_url' value='/blog/ViewReport.html' /> <script type="text/javascript"> //测试字符串的长度 一个汉字算2个字节 function mb_strlen(str) { var len=str.length; var totalCount=0; for(var i=0;i<len;i++) { var c = str.charCodeAt(i); if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { totalCount++; }else{ totalCount+=2; } } return totalCount; } /* var Util = {}; Util.calWbText = function (text, max){ if(max === undefined) max = 500; var cLen=0; var matcher = text.match(/[^\x00-\xff]/g), wlen = (matcher && matcher.length) || 0; //匹配url链接正则 http://*** var pattern = /http:\/\/([\w-]+\.)+[\w-]+(\/*[\w-\.\/\?%&=][^\s^\u4e00-\u9fa5]*)?/gi; //匹配的数据存入数组 var arrPt = new Array(); var i = 0; while((result = pattern.exec(text)) != null){ arrPt[i] = result[0]; i++; } //替换掉原文本中的链接 for(var j = 0;j<arrPt.length;j++){ text = text.replace(arrPt[j],""); } //减掉链接所占的长度 return Math.floor((max*2 - text.length - wlen)/2 - 12*i); }; */ var allowComment = '0'; //举报弹出层 function showJuBao(url, cid){ $.cover(false); asyncbox.open({ id : 'report_thickbox', url : url, title : '举报违规', width : 378, height : 240, scroll : 'no', data : { 'cid' : cid, 'idtype' : 2 , 'blogurl' : window.location.href }, callback : function(action){ if(action == 'close'){ $.cover(false); } } }); } $(function(){ //创建管理员删除的弹出层 $('#admin_article_del').click(function(){ $.cover(false); asyncbox.open({ id : 'class_thickbox', html : '<div class="HT_layer3_1"><ul><li class="HT_li1">操作原因:<select class="HT_sel7" id="del_type" name="del_type"><option value="广告文章">广告文章</option><option value="违规内容">违规内容</option><option value="标题不明">标题不明</option><option value="文不对题">文不对题</option></select></li><li class="HT_li1" ><input class="HT_btn4" id="admin_delete" type="button" /></li></ul></div>', title : '选择类型', width : 300, height : 150, scroll : 'no', callback : function(action){ if(action == 'close'){ $.cover(false); } } }); }); $('#admin_delete').live('click' , function(){ ///blog/logicdel/id/3480184/url/%252Fblog%252Findex.html.html var type = $('#del_type').val(); var url = '/blog/logicdel/id/750193/url/%252Fuid%252F20740995.html.html'; window.location.href= url + '?type=' + type; }); //顶 js中暂未添加&过滤 $('#digg').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var bid = $('#digg').attr('bid'); var url = $('#digg').attr('url'); var digg_str = $.cookie('digg_id'); if(digg_str != null) { var arr= new Array(); //定义一数组 arr = digg_str.split(","); //字符分割 for( i=0 ; i < arr.length ; i++ ) { if(bid == arr[i]) { showErrorMsg('已经赞过该文章', '消息提示'); return false; } } } $.ajax({ type:"POST", url:url, data: { 'bid' : bid }, dataType: 'json', success:function(msg){ if(msg.error == 0) { var num = parseInt($('#digg_num').html(),10); num += 1; $('#digg_num').html(num); $('#digg').die(); if(digg_str == null) { $.cookie('digg_id', bid, {expires: 30 , path: '/'}); } else { $.cookie('digg_id', digg_str + ',' + bid, {expires: 30 , path: '/'}); } showSucceedMsg('谢谢' , '消息提示'); } else if(msg.error == 1) { //showErrorMsg(msg.error_content , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); } else if(msg.error == 2) { showErrorMsg(msg.error_content , '消息提示'); } } }); }); //举报弹出层 /*$('.box_report').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var url = $('#report_url').val(); var cid = $(this).attr('cid'); $.cover(false); asyncbox.open({ id : 'report_thickbox', url : url, title : '举报违规', width : 378, height : 240, scroll : 'no', data : { 'cid' : cid, 'idtype' : 2 }, callback : function(action){ if(action == 'close'){ $.cover(false); } } }); });*/ //评论相关代码 //点击回复显示评论框 $('.Blog_a10').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } if(allowComment == 1) { showErrorMsg('该博文不允许评论' , '消息提示'); return false; } var tid = $(this).attr('toid');//留言作者id var bid = $(this).attr('bid');//blogid var cid = $(this).attr('cid');//留言id var tname = $(this).attr('tname'); var tpl = '<div class="Blog_right1_9">'; tpl += '<div class="div2">'; tpl += '<textarea name="" cols="" rows="" class="Blog_ar1_1" id="rmsg">文明上网,理性发言...</textarea>'; tpl += '</div>'; tpl += '<div class="div3">'; tpl += '<div class="div3_2"><a href="javascript:void(0);" class="Blog_a11" id="quota_sbumit" url="/Comment/PostComment.html" tid="'+tid+'" bid="'+bid+'" cid="'+cid+'" tname="'+tname+'" ></a><a href="javascript:void(0)" id="qx_comment" class="Blog_a12"></a></div>'; tpl += '<div class="div3_1"><a href="javascript:void(0);" id="mface"><span></span>表情</a></div>'; tpl += '<div class="clear"></div>'; tpl += '</div>'; tpl += '</div>'; $('.z_move_comment').html(''); $(this).parents('.Blog_right1_8').find('.z_move_comment').html(tpl).show(); }); //引用的评论提交 $('#quota_sbumit').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var bid = $(this).attr('bid'); var tid = $(this).attr('tid');//被引用人的id var qid = $(this).attr('cid');//引用的id var url = $(this).attr('url'); var text = $('#rmsg').val(); var tname = $(this).attr('tname'); if(text == '' || text=='文明上网,理性发言...') { showErrorMsg('评论内容不能为空!' , '消息提示'); return false; } else { if(mb_strlen(text) > 1000){ showErrorMsg('评论内容不能超过500个汉字' , '消息提示'); return false; } } $.ajax({ type: "post", url: url , data: {'bid': bid , 'to' : tid , 'qid' : qid , 'text': text , 'tname' : tname }, dataType: 'json', success: function(data){ if(data.code == 1){ var tpl = '<div class="Blog_right1_8">'; tpl+= '<div class="Blog_right_img1"><a href="' +data.info.url+ '" >' + data.info.header + '</a></div>'; tpl+= '<div class="Blog_right_font1">'; tpl+= '<p class="Blog_p5"><span><a href="' +data.info.url+ '" >' + data.info.username + '</a></span>' + data.info.dateline + '</p>'; tpl+= '<p class="Blog_p7"><a href="' + data.info.quota.url + '">' + data.info.quota.username + '</a>:'+ data.info.quota.content + '</p>'; tpl+= '<p class="Blog_p8">' + data.info.content + '</p><span class="span_text1"><a href="javascript:void(0);" class="Blog_a10" toid=' + data.info.fuid + ' bid=' + data.info.bid + ' cid=' + data.info.cid + ' tname = ' + data.info.username + ' >回复</a> |  <a class="comment_del_mark" style="cursor:pointer" url="' + data.info.delurl + '" >删除</a> |  <a href="javascript:showJuBao(\'/blog/ViewReport.html\','+data.info.cid+')" class="box_report" cid="' + data.info.cid + '" >举报</a></span></div>'; tpl+= '<div class="z_move_comment" style="display:none"></div>'; tpl+= '<div class="Blog_line1"></div></div>'; $('#replyList .Blog_right1_8:first').before(tpl); $('.z_move_comment').html('').hide(); } else if(data.code == -1){ //showErrorMsg(data.info , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); } }, error: function(){//请求出错处理 } }); }); //底部发表评论 $('#submitmsg').click(function(){ if(allowComment == 1) { showErrorMsg('该博文不允许评论' , '消息提示'); return false; } var bid = $(this).attr('bid'); var toid = $(this).attr('toid'); var text = $('#reply').val(); var url = $(this).attr('url'); if(text == '' || text=='文明上网,理性发言...') { showErrorMsg('评论内容不能为空!' , '消息提示'); return false; } else { if(mb_strlen(text) > 1000){ showErrorMsg('评论内容不能超过500个汉字' , '消息提示'); return false; } } $.ajax({ type: "post", url: url , data: {'bid': bid , 'to' : toid ,'text': text}, dataType: 'json', success: function(data){ if(data.code == 1) { var tpl = '<div class="Blog_right1_8">'; tpl += '<div class="Blog_right_img1"><a href="' +data.info.url+ '" >' + data.info.header + '</a></div>'; tpl += '<div class="Blog_right_font1">'; tpl += '<p class="Blog_p5"><span><a href="' +data.info.url+ '" >' + data.info.username + '</a></span>' + data.info.dateline + '</p>'; tpl += '<p class="Blog_p6">' + data.info.content + '</p>'; tpl += '<div class="div1"><a href="javascript:void(0);" class="Blog_a10" toid=' + data.info.fuid + ' bid=' + data.info.bid + ' cid=' + data.info.cid + '>回复</a> |  <a class="comment_del_mark" style="cursor:pointer" url="' + data.info.delurl + '">删除</a> |  <a href="javascript:showJuBao(\'/blog/ViewReport.html\','+data.info.cid+')" class="box_report" cid="' + data.info.cid + '">举报</a></div>'; tpl += '<div class="z_move_comment" style="display:none"></div>'; tpl += '</div><div class="Blog_line1"></div></div>'; $('.Blog_tit3:first').after(tpl); $('#reply').val('文明上网,理性发言...'); } else if(data.code == -1) { showErrorMsg(data.info , '消息提示'); } }, error: function(){//请求出错处理 } }); }); //底部评论重置 $('#reset_comment').click(function(){ $('#reply').val('文明上网,理性发言...'); }); //取消回复 $('#qx_comment').live('click' , function(){ $('.z_move_comment').html('').hide(); }); $('#rmsg, #reply').live({ focus:function(){ if($(this).val() == '文明上网,理性发言...'){ $(this).val(''); } }, blur:function(){ if($(this).val() == ''){ $(this).val('文明上网,理性发言...'); } } }); //删除留言确认 $('.comment_del_mark').live('click' , function(){ var url = $(this).attr('url'); asyncbox.confirm('删除留言','确认', function(action){ if(action == 'ok') { location.href = url; } }); }); //删除时间确认 $('.del_article_id').click(function(){ var delurl = $(this).attr('delurl'); asyncbox.confirm('删除文章','确认', function(action){ if(action == 'ok') { location.href = delurl; } }); }); /* //字数限制 $('#rmsg, #reply').live('keyup', function(){ var id = $(this).attr('id'); var left = Util.calWbText($(this).val(), 500); var eid = '#errmsg'; if(id == 'reply') eid = '#rerrmsg'; if (left >= 0) $(eid).html('您还可以输入<span>' + left + '</span>字'); else $(eid).html('<font color="red">您已超出<span>' + Math.abs(left) + '</span>字 </font>'); }); */ //加载表情 $('#face').qqFace({id : 'facebox1', assign : 'reply', path : '/image/qqface/'}); $('#mface').qqFace({id : 'facebox', assign : 'rmsg', path:'/image/qqface/'}); /* $('#class_one_id').change(function(){ alert(123213); var id = parseInt($(this).val() , 10); if(id == 0) return false; $('.hidden_son_class span').each(function( index , dom ){ if( dom.attr('cid') == id ) { } }); }); */ //转载文章 var turn_url = "/blog/viewClassPart.html"; $('#repost_bar').click(function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var id = $(this).attr('bid'); asyncbox.open({ id : 'turn_class_thickbox', url : turn_url, title : '转载文章', width : 330, height : 131, scroll : 'no', data : { 'id' : id }, callback : function(action){ if(action == 'close'){ $.cover(false); } } }); }); /* //转发文章 $('#repost_bar').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var bid = $(this).attr('bid'); var url = $(this).attr('url'); asyncbox.confirm('转载文章','确认', function(action){ if(action == 'ok'){ $.ajax({ type:"POST", url:url, data: { 'bid' : bid }, dataType: 'json', success:function(msg){ if(msg.error == 0){ showSucceedMsg('转发成功!', '消息提示'); }else if(msg.error == 1){ //location.href = '/index.php?r=site/login'; showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); }else{ showErrorMsg(msg.error_content, '消息提示'); } } }); } }); }); */ }); </script> <!--该部分应该放在输出代码块的后面才起作用 --> <script type="text/javascript"> SyntaxHighlighter.autoloader( 'applescript /highlight/scripts/shBrushAppleScript.js', 'actionscript3 as3 /highlight/scripts/shBrushAS3.js', 'bash shell /highlight/scripts/shBrushBash.js', 'coldfusion cf /highlight/scripts/shBrushColdFusion.js', 'cpp c /highlight/scripts/shBrushCpp.js', 'c# c-sharp csharp /highlight/scripts/shBrushCSharp.js', 'css /highlight/scripts/shBrushCss.js', 'delphi pascal /highlight/scripts/shBrushDelphi.js', 'diff patch pas /highlight/scripts/shBrushDiff.js', 'erl erlang /highlight/scripts/shBrushErlang.js', 'groovy /highlight/scripts/shBrushGroovy.js', 'java /highlight/scripts/shBrushJava.js', 'jfx javafx /highlight/scripts/shBrushJavaFX.js', 'js jscript javascript /highlight/scripts/shBrushJScript.js', 'perl pl /highlight/scripts/shBrushPerl.js', 'php /highlight/scripts/shBrushPhp.js', 'text plain /highlight/scripts/shBrushPlain.js', 'py python /highlight/scripts/shBrushPython.js', 'ruby rails ror rb /highlight/scripts/shBrushRuby.js', 'scala /highlight/scripts/shBrushScala.js', 'sql /highlight/scripts/shBrushSql.js', 'vb vbnet /highlight/scripts/shBrushVb.js', 'xml xhtml xslt html /highlight/scripts/shBrushXml.js' ); SyntaxHighlighter.all(); function code_hide(id){ var code = document.getElementById(id).style.display; if(code == 'none'){ document.getElementById(id).style.display = 'block'; }else{ document.getElementById(id).style.display = 'none'; } } </script> <!--回顶部js2011.12.30--> <script language="javascript"> lastScrollY=0; function heartBeat(){ var diffY; if (document.documentElement && document.documentElement.scrollTop) diffY = document.documentElement.scrollTop; else if (document.body) diffY = document.body.scrollTop else {/*Netscape stuff*/} percent=.1*(diffY-lastScrollY); if(percent>0)percent=Math.ceil(percent); else percent=Math.floor(percent); document.getElementById("full").style.top=parseInt(document.getElementById("full").style.top)+percent+"px"; lastScrollY=lastScrollY+percent; if(lastScrollY<200) { document.getElementById("full").style.display="none"; } else { document.getElementById("full").style.display="block"; } } var gkuan=document.body.clientWidth; var ks=(gkuan-960)/2-30; suspendcode="<div id=\"full\" style='right:-30px;POSITION:absolute;TOP:500px;z-index:100;width:26px; height:86px;cursor:pointer;'><a href=\"javascript:void(0)\" onclick=\"window.scrollTo(0,0);\"><img src=\"\/image\/top.png\" /></a></div>" document.write(suspendcode); window.setInterval("heartBeat()",1); </script> <!-- footer --> <div class="Blog_footer" style='clear:both'> <div><a href="http://www.chinaunix.net/about/index.shtml" target="_blank" rel="nofollow">关于我们</a> | <a href="http://www.it168.com/bottomfile/it168.shtml" target="_blank" rel="nofollow">关于IT168</a> | <a href="http://www.chinaunix.net/about/connect.html" target="_blank" rel="nofollow">联系方式</a> | <a href="http://www.chinaunix.net/about/service.html" target="_blank" rel="nofollow">广告合作</a> | <a href="http://www.it168.com//bottomfile/flgw/fl.htm" target="_blank" rel="nofollow">法律声明</a> | <a href="http://account.chinaunix.net/register?url=http%3a%2f%2fblog.chinaunix.net" target="_blank" rel="nofollow">免费注册</a> <p>Copyright 2001-2010 ChinaUnix.net All Rights Reserved 北京皓辰网域网络信息技术有限公司. 版权所有 </p> <div>感谢所有关心和支持过ChinaUnix的朋友们 <p><a href="http://beian.miit.gov.cn/">16024965号-6 </a></p> </div> </div> </div> </div> <script language="javascript"> //全局错误提示弹出框 function showErrorMsg(content, title, url){ var url = url || ''; var title = title || '消息提示'; var html = ''; html += '<div class="HT_layer3_1 HT_layer3_2"><ul><li><p><span class="login_span1"></span>' + content + '</p></li>'; if(url == '' || url.length == 0){ html += '<li class="HT_li1"><input type="button" class="HT_btn2" onclick=\'close_windows("error_msg")\'></li>'; } else { html += '<li class="HT_li1"><input type="button" class="login_btn1" onclick="location.href=\'' + url + '\'"></li>'; } html += '</ul></div>'; $.cover(true); asyncbox.open({ id: 'error_msg', title : title, html : html, 'callback' : function(action){ if(action == 'close'){ $.cover(false); } } }); } //全局正确提示 function showSucceedMsg(content, title , url ){ var url = url || ''; var title = title || '消息提示'; var html = ''; html += '<div class="HT_layer3_1 HT_layer3_2"><ul><li><p><span class="login_span2"></span>' + content + '</p></li>'; if(url == '' || url.length == 0){ html += '<li class="HT_li1"><input type="button" class="HT_btn2" onclick=\'close_windows("error_msg")\'></li>'; } else { html += '<li class="HT_li1"><input type="button" class="HT_btn2" onclick="location.href=\'' + url + '\'"></li>'; } html += '</ul></div>'; $.cover(true); asyncbox.open({ id: 'error_msg', title : title, html : html, 'callback' : function(action){ if(action == 'close'){ $.cover(false); } } }); } //关闭指定id的窗口 function close_windows(id){ $.cover(false); $.close(id); } //公告 var tID; var tn; // 高度 var nStopTime = 5000; // 不同行间滚动时间隔的时间,值越小,移动越快 var nSpeed = 50; // 滚动时,向上移动一像素间隔的时间,值越小,移动越快 var isMove = true; var nHeight = 25; var nS = 0; var nNewsCount = 3; /** * n 用于表示是否为第一次运行 **/ function moveT(n) { clearTimeout(tID) var noticev2 = document.getElementById("noticev2") nS = nSpeed; // 只在第一次调用时运行,初始化环境(有没有参数) if (n) { // 设置行高 noticev2.style.lineHeight = nHeight + "px"; // 初始化显示位置 tn = 0; // 刚进入时在第一行停止时间 nS = nStopTime; } // 判断鼠标是否指向层 if (isMove) { // 向上移动一像素 tn--; // 如果移动到最下面一行了,则移到顶行 if (Math.abs(tn) == nNewsCount * nHeight) { tn = 0; } // 设置位置 noticev2.style.marginTop = tn + "px"; // 完整显示一行时,停止一段时间 if (tn % nHeight == 0) { nS = nStopTime; } } tID = setTimeout("moveT()", nS); } moveT(1); // 此处可以传入任何参数 </script> <script type="text/javascript"> // var _gaq = _gaq || []; // _gaq.push(['_setAccount', 'UA-20237423-2']); // _gaq.push(['_setDomainName', '.chinaunix.net']); // _gaq.push(['_trackPageview']); // // (function() { // var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; // ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; // var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); // })(); </script> <script type="text/javascript"> var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://"); document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F0ee5e8cdc4d43389b3d1bfd76e83216b' type='text/javascript'%3E%3C/script%3E")); function link(t){ var href= $(t).attr('href'); href+="?url="+encodeURIComponent(location.href); $(t).attr('href',href); //setCookie("returnOutUrl", location.href, 60, "/"); } </script> <script type="text/javascript" src="/js/jquery.qqFace.js"></script> </body> </html>