I am trying to define a vim key map for putting the selected line inside an HTML p tag:
vnoremap <leader>bp c<p><cr></p><esc>P
It doesn't work, I think vim is interpreting <p> in a special way. How can I solve this?
It looks like you are using Vim in "compatible mode" which is something only hopelessly masochistic people do. In "nocompatible mode", your mapping works as expected so you should probably make sure nocompatible is set (creating a blank ~/.vimrc should be enough).
Anyway, your <p>s are not where the problem is because they are inserted normally, it's your <cr> and your <esc> that are causing a mess: since you are running Vim in "compatible mode", the cpoptions option includes < which causes Vim to not recognize <CR> and friends as special keys.
Running Vim in "nocompatible mode" is the best way to go but you can also use the following notation if you really insist on going "compatible":
vnoremap <leader>bp c<p>^M</p>^]P
where ^M is inserted with <C-v><CR> and ^] is inserted with <C-v><Esc>.
You may want to look into Tim Pope's Surround plugin. Then you can do S<p> and surround the visually selected text with <p> tags.
However the answer please see #romainl answer. I would also suggest you read up on key-notation via :h key-notation
I just started diving into vi and so far learned only basic moving around/editing commands. While I am going through the book, is there a fast way to comment out a paragraph with -# in the same column with the cursor position (indenting the lines accordingly)?
Let's say I have a piece of code:
%table
- unless paginate(#clients).nil?
%tr
%th
=t('index.name')
%th
=t('index.address')
%th
=t('index.phone')
=render :partial => 'client', :collection => #clients
and I want to comment out lines between - unless and =render :partial with -# in one column and then be able to comment them in again. What command would that be?
In blockwise select mode, you can press I to insert in front of the block and A to insert after the block.
Setting 'relativenumber' (:set rnu) could help to count lines.
Start with CTRL-V to switch to blockwise select mode, then 8j to go down eight lines, then I#Esc to insert the #.
To remove it: dCTRL-V8j will delete blockwise.
Warning, if you happen to use vanilla gvim.exe on Windows, you probably have mswin.vim activated which remaps CTRL-V, use then CTRL-Q instead (or disable this plugin)
If you're less interested about the how and just want it to work, there are a number of plugins that provide (un)commenting functionality for varieties of languages. Tim Pope's commentary.vim is the one I just started using recently, as a replacement for nerdcommenter.
I just installed it so I can't speak to any defects, but Tim Pope's stuff is (nearly?) always excellent. With the plugin you could comment a Haml paragraph by selecting a visual block and typing \\\. It also takes motions, e.g. \\ap.
The link:
https://github.com/tpope/vim-commentary
If you use it often, you can define a command in your .vimrc
command -range=% C :<line1>,<line2>s/^/-#/
Then in vi, you can apply :<range>C in the usual manner. You can do this with :10,20C or .,+10C. You can use the following command for uncommenting.
command -range=% D :<line1>,<line2>s/^-#//
Since I am using vi for with languages with different types of commenting, I also us these commands:
command -range=% -nargs=1 Ca :<line1>,<line2>s/^/<args>/
command -range=% -nargs=1 Da :<line1>,<line2>s/^<args>//
Allowing you to just do :10,20Ca-#, where you can replace -# with the commenting method of choice.
I want to learn the vim documentation given in the standard help file. But I am stuck on a navigating issue - I just cannot go to the next tag without having to position the cursor manually. I think you would agree that it is more productive to:
go to the next tag with some
keystroke
press Ctrl-] to read corresponding
topic
press Ctrl-o to return
continue reading initial text
PS. while I was writing this question, I tried some ideas on how to resolve this. I found that searching pipe character with /| is pretty close to what I want. But the tag is surrounded with two pipe '|' characters, so it's still not really optimized to use.
Use the :tn and :tp sequences to navigate between tags.
If you want to look for the next tag on the same help page, try this search:
/|.\{-}|
This means to search for:
The character |
Any characters up to the next |, matching as few as possible (that's what \{-} does).
Another character |
This identifies the tags in the VIM help file.
If you want to browse tags occasionally only, without mapping the search string to keyboard,
/|.*|
also does the trick, which is slightly easier to type in than the suggested
/|.\{-}|
For the case, that the "|" signs for the links in the help file are not visible, you can enable them with
:set conceallevel=0
To establish this setting permanently, please refer to Defining the settings for the vim help file
Well, I don't really see the point. When I want to read everything, I simply use <pagedown> (or <c-f> with some terminals)
" .vim/ftplugin/help/navigate.vim
nnoremap <buffer> <tab> /\*\S\+\*/<cr>zt
?
Or do you mean:
nnoremap <buffer> <tab> /\|\zs\S\{-}\|/<cr><c-]>
?
You could simply remap something like:
nmap ^\ /<Bar><Bslash>zs<Bslash>k<Bslash>+<Bar><CR>
where ^\ is entered as (on my keyboard) Ctrl-V Ctrl-#: choose whatever shortcut you want.
This does a single key search for a | followed by one or more keyword characters and then a |. It puts the cursor on the first keyword character. The and bits are there due to the way map works, see
:help :map-special-chars
As an aside, I imagine that ctrl-t would make more sense than ctrl-o as it's a more direct opposite of ctrl-], but it's up to you. Having said that, ctrl-o will allow you to go back to before the search as well.
I often find myself removing and adding XML sections in configuration files:
tomcat's server.xml
maven's settings.xml
and many others.
Is there a vim plugin/command to make this simple?
You can use a combination of matching XML tags, as can be seen in this question and Perl's search and replace.
For instance, given this snippet:
<TypeDef name="a">
<ArrayType high="14" low="0">
<UndefType type="node">
</UndefType>
</ArrayType>
</TypeDef>
Put the cursor on either the opening or closing TypeDef and type the following sequence:
vat:s/^\(.*\)$/<!--\1-->/
v - puts you into visual mode
at - selects the whole XML tag
:s/^\(.*\)$/<!--\1-->/ - surrounds each line with '<!--...-->', the comment delimiters for XML
Alternatively, you can just delete it like this:
dat
d - delete according to the following movements
at - as before
use surround.vim for general tag matching, deleting, inserting, surrounding etc,
For commenting tags, it is easy to use vim text objects & and a simple macro
Example:
enter
vmap ,c <esc>a--><esc>'<i<!--<esc>'>$
somewhere suitable, then place your cursor at the capital "A" of "ArrayType" on line two of the following (borrowed from Nathan Fellmans example above)
<TypeDef name="a">
<ArrayType high="14" low="0">
<UndefType type="node">
</UndefType>
</ArrayType>
</TypeDef>
then hit
vat,c
and you will get:
<TypeDef name="a">
<!--<ArrayType high="14" low="0">
<UndefType type="node">
</UndefType>
</ArrayType>-->
</TypeDef>
with your cursor at the end of the comment
I love the simplicity of https://github.com/tpope/vim-commentary. Easy to add other languages, though seems to support most out of the box. Under 100 lines of code.
gcc to comment the current line, or select the text you want to comment and hit gc. Super easy.
Vim doesn't have smart commenting for all file types by itself. You should get a script for your commenting needs.
I use the enhcomentify script which has been around and maintained for a long time
http://www.vim.org/scripts/script.php?script_id=23
It seems to do xml well and you get the advantage of the same key bindings for any filetype you are using.
There are others.. notably the NERD Commenter
http://www.vim.org/scripts/script_search_results.php?keywords=comment&script_type=&order_by=rating&direction=descending&search=search
I think that adapting this vim tip might be useful.
I propose adding:
" Wrap visual selection in an XML comment
vmap <Leader>c <Esc>:call CommentWrap()<CR>
function! CommentWrap()
normal `>
if &selection == 'exclusive'
exe "normal i-->"
else
exe "normal a-->"
endif
normal `<
exe "normal i<!--"
normal `<
endfunction
to your .vimrc
Then, with a visual selection active (V), hit \c (backslash then c) to wrap your block in <!-- --> XML-style comments.
Alternatively, as suggested on the wiki you can put the code in ~/.vim/scripts/wrapwithcomment.vim and add to your .vimrc:
au Filetype html,xml source ~/.vim/scripts/wrapwithcomment.vim
to only load that functionality when working on a html or xml file.
Best it'd be if you'd find a command that adds things in the beginning and end of the selection.
When I'm commenting python code, I'm doing this:
:2,4s/^/#/g
What are the essential vim commands? What does a new-user need to know to keep themselves from getting into trouble? One command per comment, please.
What I find irreplaceable (because it works in vi also, unlike vim's visual mode) are marks. You can mark various spots with m (lower case) and then a letter of your choice (eg x). Then you go elsewhere, and can go back with ``x(backquote letter) to the exact spot, or with'x` (apostrophe letter) to go to the line.
These movements can be used as arguments to commands (yank, delete, etc). For example, you want to delete 10 lines; instead of counting and then moving to the topmost line and entering 10dd, you go to either the start or the end of the block, press mm (mark m), then go to the other end of the block, and press d'm (delete apostrophe m). If you use backquote instead of apostrophe in this example, then the deletion will work character-wise, not line-wise. Try marking in the middle of the line with "mark m", moving to the middle of another line, then entering "d backquote m" and you will see what I mean.
I was very happy the day I learned about using * or # to search, down or up respectively, for the word under the cursor. Make sure to :set incsearch and :set hlsearch first.
I like this QRC!
http://www.fsckin.com/wp-content/uploads/2007/10/vi-vim_cheat_sheet.gif
When you have some repetitive action to take Macros are usually faster than regex.
Just type
q[0-9a-z] in normal mode
Many people use
qq
because it's fast.
Press
q in normal mode
again to stop recording.
Then just type
#[0-9a-z] in normal mode
to repeat what you just recorded.
#q
for the example like above.
Edited to add: you can also repeat the macro. Let's say you programed a macro to jump to the head of a line, insert a tab, and then jump down one line. You then test your macro by typing "#q" to run it once. Then you can repeat the action nine more times by typing "9#q".
:q -> quit
:w -> save
:q! -> quit and don't save
:x -> save and quit
:[number] -> go to line number
G -> go to end of file
dd -> delete line
p -> "put" line
yy -> "copy" line
:s/[searchfor] -> search
I guess those are the basic one to start from
Use the 'J' (J for Join; upper-case) command to delete the newline at the end of a line. You'll find it tricky otherwise.
This recent Vim tutorial from IBM is pretty good
First of all you need to know how to close vi:
ctrl-c : q!
Rest can be found from vimtutor. Launch vimtutor by typing vimtutor at your command line
Although this is a matter of personal preference I've found that one of the essential things to do is to remap Esc to something else.
I find it very uncomfortable to reach for the Esc key to exit insert mode, but the beautiful thing about Vim is that allows key mappings.
I'm currently using the following mapping using Control + S:
inoremap <C-s> <Esc>:w<CR>
This has the advantage of being a key mapping I have already committed to memory and has the added value of saving my work every time I go to normal mode. Yeah, I know it is crazy but I would be hitting the save command that frequently anyway. It's like a bad habit, you know.
" ~/.vimrc
" Turn on line numbering
set nu
" Turn on syntax highlighting
syntax on
" Set 4 space expanding tabs
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
"turn off line wrapping
set nowrap
" Map CTRL-N to create a new tab
:map <C-n> <ESC>:tabnew<RETURN>
" Map Tab and CTRL-Tab to move between tabs
:map <Tab> <ESC>:tabn<RETURN>
:map <C-Tab> <ESC>:tabp<RETURN>
If you're using vim, the 'u' command (in command mode) will Undo the last command you typed. You can use this command repeatedly to undo mistakes you may have made before saving the file.
See http://www.rayninfo.co.uk/vimtips.html for a great collection of Vim tips, from the basic can't-live-without to very sophisticated stuff that you might never have thought of trying.
Lots of great commands are listed at the Vim Tips Wiki.
It's also good to run the vimtutor when learning these commands
alias vi nedit :)
all humor aside..
for vi WHEN NOT using nedit..
i (switch to insert mode)
a (append = move to end of line and switch to insert mode)
esc (exit insert mode)
dd delete a line
x delete a character
:wq (save and quit)
/ start a search
n find Next
? search backwards..
yy (yank) copy a line to the buffer
pp (paste) paste it here
r (replace a character)
<N> <command> this is a neat - but aggravating feature that lets you type digits and then a command so
5dd will delete 5 lines
but at this point you might as well
- man vi and refresh your memory
While there are LOTS more, I switched from Vi to nedit several years ago, which I find has more features I can use on a regular basis more easily. Tabbed editing, incremental search bar, column select, copy and paste. sort selected lines, search and destroy within selection, whole doc or all open docs..
tear-off drop down menus..
and it supports syntax highlighting for all the languages I use.. (with pattern files I've used a long time over the years. VIM many now be equivalent, but It has to introduce a feature that Nedit doesn't and an easy way to migrate my pattern files before I switch again.
I like the Vim 5.6 Reference Guide, by Bram Moolenaar and Oleg Raisky.
You can directly print it in booklet form, easy to read, I always have it laying around.
It's a tad old, but what are 8 years in Vi's lifespan ?
:set ignorecase smartcase
Makes searching case-insensitive, unless your search includes a capital letter. Not the most indispensable perhaps, but I find myself setting this option any time I'm editing in a new place. It's in any vimrc file I own.
:%!xxd
View the contents of a buffer in hexadecimal. To revert:
:%!xxd -r
My biggest tip: ctrl+q saves the day when you accidentally hit ctrl+s to save the file you are working on
I have this in my vimrc
set number
set relativenumber
This gives me a line numbering system which makes j, k keys really productive.
I use vi very lightly, and I only use the following commands:
a - switch to insert mode (after the cursor)
esc - return to command mode
:wq - save and quit
:q - quit (no save, only without modification)
:q! - force quit (no save, also with modification)
x - delete one character (in command mode)
dd - delete the whole line (in command mode)
I know there are many many more, but those are enough to get you by.
One of my favourite commands is %G which takes to directly to the end of a file. Especially useful in log-files.
How to switch between modes (i to enter insert mode (one of many ways), esc to exit insert mode, colon for command mode) and how to save and exit. (:wq)
Another useful command is to search something: /
e.g. /Mon will search (and in case of vim highlight) any occurences of Mon in your file.
As a couple of other people have already mentioned, vimtutor is the way to go. It will teach you everything you need to know in vim. The one piece of general advice I would give you is to stay out of insert mode as much as possible. There is enormous power in the other modes, it just takes a little bit of practice to get used to it.
i - insert mode (escape to exit)
dd - delete line
shift-y - 'Yank' (copy) line
p - 'Put' (paste) line(s)
shift-v - Visual mode used to select text (tryin 'yanking' this text and 'putting' it somewhere.
ctrl-w n - create new window (you can open a file or start new file here)
ctrl-w v - split existing window vertically
ctrl-n (in insert mode) - autocomplete (if supported)
:! to run a shell command, usually with standard in as the file or a selection (shift-V)
Useful plugins to look at:
* Buffer Explorer - use \be to view files in the buffer (and select to re-open)
NB vi is not vim! vim is rapidly turning into the emacs of the new century. nvi is probably the closest thing to the original vi. Here's a nice hint: "xp" will exchange two characters (try it).
replace 'foo' with 'bar' everywhere in the file
:%s/foo/bar/gc
The real power is in the searching. Here are the essential commands:
/Steve will find the first instance of "Steve" in the text.
n will find the next "Steve" in the text.
:%s//Stephen/g will replace all those instances of "Steve" you just searched for with "Stephen".
Not to promote myself, but I wrote a blog post on this subject. It focuses on the critical parts of Vim for a beginner.
My favorites:
% find matching bracket/brace
* and # next/previous match
gg top of page
G end of the page
<Ctrl-v> Change to visual mode and select column
<Ctrl-a> increase current number by 1
<Ctrl-x> decrease current number by 1
Running macros