Pasting from the clipboard and automatically toggling ":set paste" - vim

When I paste things from the clipboard, they're normally (always) multilined, and in those cases (and those cases only), I'd like :set paste to be triggered, since otherwise the tabbing will increase with each line (you've all seen it!).
Though the problem with :set paste is that it doesn't behave well with set smartindent, causing the cursor to jump to the beginning of a new line instead of at the correct indent. So I'd like to enable it for this instance only.
I'm using Mac, sshing to a Debian machine with Vim, and thus pasting in Insert mode using cmd + v.

I don't use a mac, but I believe I have the prefix right here: <D-v> should mean cmd-v. For insert mode:
:imap <D-v> ^O:set paste<Enter>^R+^O:set nopaste<Enter>
or really, just do this:
:imap <D-V> ^O"+p
The ^O and ^R are literal control-O and control-R, which you can type with ^V^O (control-v control-o) and ^V^R (control-v control-r). Control-O in insert mode allows you to execute one command then return to insert mode; here you can use it to put from the clipboard register.
This worked for me when I tested them mapped to a different key, so you should be all set.
There's no need to map anything when not in insert mode; you can just use "+p.

I have the following in my .vimrc:
inoremap <S-Insert> <ESC>:setl paste<CR>gi<C-R>+<ESC>:setl nopaste<CR>gi
gi is to start insert mode in the same position as where insert mode was stopped last time in the current buffer.
Update:
Jefromi posted a better solution. I have tinkered it a bit
inoremap <S-Insert> <ESC>"+p`]a
It inserts clipboard text and places the cursor right after it.

You're right in that you should only enable 'paste' when you need it. It does more than just affect indenting. You can read everything that it affects in its documentation. A related option that is very useful to ease the use of 'paste' is 'pastetoggle'.
If you were using X-forwarding and a terminal that can properly communicate mouse actions, you could also take advantage of the 'mouse' option. With :set mouse=a, Vim is made aware of what the mouse is doing and therefore won't perform automatic indentation when it receives a multi-line paste via a middle-button mouse click.
Even without the mouse capability, X-forwarding could help because Vim will do the same thing when manually pasting from the clipboard or selection registers ("+ and "* respectively).

This ought to be solvable with a Vim script. (I hate Vim scripting, so it would have to be a much more serious infliction to cause me to solve it myself.) Even with iTerm2's "paste slowly" mode, the default is to break the data to be pasted into 16 byte chunks and send one every 0.125 seconds. Therefore, you should be able to programmatically detect a 16 byte chunk of "keystrokes" and do something about it.
In pseudocode that would look like:
if too_fast_too_be_human():
set('pastemode', True)
else
set('pastemode', False)
# where either
def too_fast_too_be_human
char_threshold = 16
return len(input_buffer) > char_threshold
# or
def too_fast_too_be_human
static byte_times = []
char_threshold = 16
time_threshold = 0.125
byte_times.append(now())
while(len(byte_times) > char_threshold):
byte_times.unshift()
return (byte_times[-1] - byte_times[0]) < time_threshold
There are weaknesses to that, but it would work for most cases.

We can paste (insert mode) without messing up indentation using
Ctrl-r Ctrl-o Register
Ctrl-r Ctrl-o +
Ctrl-r Ctrl-o *
Ctrl-r Ctrl-o 0
CTRL-R CTRL-O {0-9a-z"%#*+/:.-=} *i_CTRL-R_CTRL-O*
Insert the contents of a register literally and don't
auto-indent. Does the same as pasting with the mouse
"MiddleMouse". When the register is linewise this will
insert the text above the current line, like with `P`.
Does not replace characters!
The '.' register (last inserted text) is still inserted as
typed.

Related

Why does Vim always manage to clip off at least a couple of characters when copying and pasting?

Vim always manages to clip off at least of couple of characters when I copy something from a text file, such as a public rsa key for example.
Generally, I open a text file in my computer, highlight the text, copy it to my clipboard. I go into my terminal (with Vim already open) and then:
i (for insert)
ctrl+shift+v
Am I doing something wrong?
I've double checked, and triple checked, this, and I am absolutely sure that I highlighted all of the text that I needed to copy. Other times it works fine. There does not seem to be any consistency in regards to when it happens.
Anyone experience this?
This usually happens because something in the pasted text triggers a key mapping unexpectedly. This is what paste mode is for.
Do this before pasting:
:set paste
And turn it off after:
:set nopaste
This can be annoying to type frequently, so there is a way to map it to a key combination. I use ,p for this, and have this in my .vimrc:
set pastetoggle=,p
(Yes, I use an actual comma here, not <Leader>. That's because <Leader> won't work here, as this isn't technically a mapping.)
This is a toggle, so you can use it to turn the mode on and off. It works in both normal mode and insert mode.
You do want to turn it off after the paste. Since paste mode disables your insert mappings, you don't want to leave it on all the time.
You can read more about the paste option with :help 'paste.
The annoyance of toggling to and form paste mode can be avoided by using "+p or "*p. (You're putting the quoteplus register).
More often than not, I prefer "+P, since this leaves my cursor at the end of properly formatted put. see :help quoteplus for details. So the whole workflow is:
outside of vim: copy to clipboard
inside of vim: "+P

Undo a paste without undoing previous typing

In vim I frequently end up undoing more than I want to after a messed up paste from the system clipboard. Is there a better way?
To reproduce:
Open iTerm # or terminal
vi # open vim
i # enter insert mode
type some stuff
Cmd-V # paste the contents of the OS X clipboard
The paste is a mess because I haven't :set paste. So
Esc # enter command mode
u # undo
but that undoes my typing as well as my paste.
Is there a different undo I can use? Apart from remembering to :set paste before pasting is there a better way to do this in general?
This is not the answer you're looking for, but you really should stop using vim as a non-modal editor. If you want to paste then return to normal mode and use vim's paste commands.
Assuming that you have a vim version with clipboard access this should do the trick "+p. You can also facilitate this by setting your unnamed register to be the + (or *) register, such that pasting from clipboard becomes a simple p.
The following question has a great answer that includes all this information How to make vim paste from (and copy to) system's clipboard?.
I'm not sure there's anything you can do after the fact, but one solution is to hit Ctrl-G u in insert mode just before you paste. This breaks the undo block into two separate blocks - so the paste will be remembered as a separate undoable action.
Granted if you have to remember to do this, you might as well just use :set paste instead - but on the upside it's fewer keystrokes and you don't have to go to command mode first.
Take a look at this plugin, it can auto run :set paste! when you use Cmd-V(or Ctrl-V) to paste some text. And leave paste mode when you finished.
The following mappings create an additional undo point (via :help i_CTRL-G_u) before pasting in insert mode. This way, you can undo the paste separately.
inoremap <C-r> <C-g>u<C-r>
inoremap <C-v> <C-g>u<C-v>
Actually the solution is you have to go to command mode(e.g. Esc) first and re-enter the insert mode, but it only works if I type manually but it seems "randomly" stop working if I test it in ~/.vimrc. Google doesn't help at all.
I spends a lot of time try to fix this issue and I just figure out the reason in my case:
Don't map the paste key same with the terminal existing paste key
e.g. Ctrl+Shift+V will paste in my Konsole terminal, but if I assign this key <C-S-v> in ~/.vimrc, the "undo for only single paste instead of multiple pastes" will not working.
In my case, I have to use <C-v> instead of <C-S-v>:
inoremap <C-v> <Esc>"+pi<Esc>i<Right><Right>
Your case may difference, but the point is same: don't assign the same paste key conflicts with existing terminal emulator key.
I've 100% proved this conclusion by set my terminal paste key to Ctrl+V and now <C-v> stop working but <C-S-v> working.
Note also that the vim is too sensitive and strange. I figure out I have to use i and then 2 Right keys manually to make it works in the correct cursor position, that's means I have to put i and 2 Right keys in the ~/.vimrc too. Your case might difference, but the point is same, ensure the keys+order in ~/.vimrc 100% match with what you type manually.

Quickest way to paste block of text into the vi editor from an external source

For instance, copying a configuration section from a web page and then pasting it into a .conf file that you have open in vi.
Enter insert mode (Type i)
Type: Ctrl + Shift + v
Or if you use the system register, you can paste without being in insert mode:
"*p
This will paste the system's clipboard at the point of the cursor. No insert mode needed.
The real answer:
:set paste
Enter Insert Mode: hit i
Paste: Command + v or Control + v
ESC
:set nopaste
One thing to bear in mind: Sometimes Vim auto-indents text. This is mostly fine, but sometimes it messes up text that you paste into a document.
If your indentations are awry, remove the pasted text, type :set paste, paste the text in again, and when you're done, type :set nopaste.
The easiest way is just to copy the text and just right click where you want to paste it in Vim in INSERT mode.
If you are using gVim, hit Ctrl + R and then either * or + in insert mode. It will paste the last copied text.
Ctrl-V/ Apple-V? Just make sure you're in insert mode in vi (i)
Use your systems paste shortcut key while in Insert mode, or if your source is in another file, you can type :r <fileName>, and it will be pasted at the current location of your cursor.
The easiest way on *nix is by selecting it with the mouse and pasting it in Vim with a middle click, after having put vi in insert mode.
The middle click could be a both left-right key if you're using a touchpad.
The quickest way is to paste it using whatever paste key your system uses (e.g. ⌘-v for Macs, Ctrl-V for Windows, etc.) in insert mode.
Some terminals require you to use Shift-Ctrl-V. However you are able to paste onto the command-line is how you should paste into Vim. However, this can cause some problems with indentation, which is where :set paste comes in. The fastest way to get in and out of this is to set a pastetoggle (see :help pastetoggle). For example, I use
set pastetoggle=<leader>p
The reason to use a pastetoggle instead of a mapping is because if you set a mapping insert mode, it will read it literally when in paste mode. Thus if you :set paste, go into insert mode, and type in any imap the mapping will not be completed, but instead the literal characters will be inserted. With pastetoggle you can get around that since it's a built-in feature.
As others have said, if you're in insert mode, you can also use <C-r>*, but why? Your normal pasting flow is most likely better. Understanding the * register and <C-r> is an important skill however. You can read more about them at :help registers and :help i_CTRL-R. You could also use "*p, but if you're faster at typing that than your normal paste I'm impressed.
Of course you could map that to something else, but again... why? You should get used to quickly getting into insert mode with i, I, a, A, o, O, s, S, c, and C so that you can be precise.

Turning off auto indent when pasting text into vim

I am making the effort to learn Vim.
When I paste code into my document from the clipboard, I get extra spaces at the start of each new line:
line
line
line
I know you can turn off auto indent but I can't get it to work because I have some other settings conflicting or something (which look pretty obvious in my .vimrc but don't seem to matter when I take them out).
How do I turn off auto indenting when I paste code but still have vim auto indent when I am writing code? Here is my .vimrc file:
set expandtab
set tabstop=2
set shiftwidth=2
set autoindent
set smartindent
set bg=dark
set nowrap
Update: Better answer here: https://stackoverflow.com/a/38258720/62202
To turn off autoindent when you paste code, there's a special "paste" mode.
Type
:set paste
Then paste your code. Note that the text in the tooltip now says -- INSERT (paste) --.
After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.
:set nopaste
However, I always found that cumbersome. That's why I map <F3> such that it can switch between paste and nopaste modes while editing the text! I add this to .vimrc
set pastetoggle=<F3>
To avoid undesired effects while pasting, there is an option that needs to be set:
set paste
A useful command to have in your .vimrc is set pastetoggle=<F10> or some other button, to easily toggle between paste and nopaste.
I usually use :r! cat and then paste ( shift + insert ) the content, and CTRL+D.
No need to enable & disable, direct usage.
If you are working locally, you can paste from the system clipboard with the key sequence:
"+p
This is a proper vim command, so no need to worry about entering an insert mode or switching off autoindent first.
Of course if you are working remotely (console over SSH, for example) then this won't work and you should go the :set noai, insert mode, paste into console, leave insertmode, :set ai route as described elsewhere.
While setting the paste mode with paste/nopaste/pastetoggle is perfectly fine, you still have to manually enable paste mode before pasting and disable paste mode after pasting. Being the lazy person that I am, below is the best solution that I've found so far, which automatically toggles the paste mode when you paste.
Here's a little trick that uses terminal's bracketed paste mode to
automatically set/unset Vim's paste mode when you paste. Put following
in your .vimrc:
let &t_SI .= "\<Esc>[?2004h"
let &t_EI .= "\<Esc>[?2004l"
inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
function! XTermPasteBegin()
set pastetoggle=<Esc>[201~
set paste
return ""
endfunction
Now you can paste without explicitly turning paste mode on/off - it is
handled automatically for you.
Source: Coderwall
Note: This solution doesn't work in WSL (Windows 10 Subsystem for Linux). If anyone has a solution for WSL, please update this answer or add it in the comments.
Tmux If using tmux, then the declarations need to be double escaped. The code for this is also in Coderwall
Mac users can avoid auto formatting by reading directly from the pasteboard with:
:r !pbpaste
Here is a post by someone who figured out how to remap the paste event to automatically turn paste mode on and then back off. Works for me in tmux/iTerm on MacOSX.
I just put set clipboard=unnamed in my .vimrc. That makes the default paste buffer map to X's clipboard.
So, if I mark a bit of text in a terminal, I can simply press p to paste it in vim. Similarly, I can yank things in vim (e.g. YY to yank the current line into the buffer) and middle click in any window to paste it.
I don't know. I find it super convenient.
Add this to your ~/.vimrc and you will only have to press F2 before and after pasting:
set pastetoggle=<F2>
I am a Python user who sometimes copy and paste into Vim. (I switched from Mac to Windows WSL) and this was one of the glitches that bothered me.
If you touch a script.py and then vi script.py, Vi will detect it is a Python script and tried to be helpful, autoindent, paste with extra indents, etc. This won't happen if you don't tell it is a Python script.
However, if that is already happening to you, the default autoindent could be a nightmare when you paste already fully indented code (see the tilted ladder shape below).
I tried three options and here are the results
set paste # works perfect
set noai # still introduced extra whitespace
set noautoindent # still introduced extra whitespace
When working inside a terminal the vim-bracketed-paste vim plugin will automatically handle pastes without needing any keystrokes before or after the paste.
It works by detecting bracketed paste mode which is an escape sequence sent by "modern" x-term compatible terminals like iTerm2, gnome-terminal, and other terminals using libvte. As an added bonus it works also for tmux sessions. I am using it successfully with iTerm2 on a Mac connecting to a linux server and using tmux.
Another answer I did not see until now:
:se paste noai
Stick this in your ~/.vimrc and be happy:
" enables :Paste to just do what you want
command Paste execute 'set noai | insert | set ai'
Edit: on reflection, :r !cat is a far better approach since it's short, semantic, and requires no custom vimrc. Use that instead!
Another way to paste is via <C-r> in insert mode and dropping the contents of the register (here the global register). See: :h i_ctrl-r and h i_CTRL-R_CTRL-O.
From the vim help documentation:
Insert the contents of a register literally and don't auto-indent. Does the same as pasting with the mouse. Does not replace characters! The '.' register (last inserted text) is still inserted as typed.{not in Vi}
So to paste contents into vim without auto indent, use <C-r><C-o>* in most unix systems.
You can add a mapping in the your vimrc inoremap <C-r> <C-r><C-o> so you can paste the contents of the * register normally without the auto indent by using <C-r>*.
Note: this only works if vim is compiled with clipboard.
Although :pastetoggle or :paste and :nopaste should be working fine (if implemented - they are not always as we can see from the discussion) I highly recomment pasting using the direct approach "+p or "*p and reading with "+r or "*r:
Vim has acess to ten types of registers (:help registers) and the questioner is interested in quotestar and quoteplus from section
Selection and drop registers "*, "+ and "~
Use these registers for storing and retrieving the selected text for the GUI.
See quotestar and quoteplus. When the clipboard is not available or not
working, the unnamed register is used instead. For Unix systems the clipboard
is only available when the +xterm_clipboard feature is present. {not in Vi}
Note that there is only a distinction between "* and "+ for X11 systems.
:help x11-selection further clarifies the difference of * and +:
quoteplus quote+
There are three documented X selections: PRIMARY (which is expected to
represent the current visual selection - as in Vim's Visual mode), SECONDARY
(which is ill-defined) and CLIPBOARD (which is expected to be used for
cut, copy and paste operations).
Of these three, Vim uses PRIMARY when reading and writing the "* register
(hence when the X11 selections are available, Vim sets a default value for
'clipboard' of "autoselect"), and CLIPBOARD when reading and writing the "+
register. Vim does not access the SECONDARY selection.
Examples: (assuming the default option values)
Select an URL in Visual mode in Vim. Go to your browser and click the
middle mouse button in the URL text field. The selected text will be
inserted (hopefully!). Note: in Firefox you can set the
middlemouse.contentLoadURL preference to true in about:config, then the
selected URL will be used when pressing middle mouse button in most places in the window.
Select some text in your browser by dragging with the mouse. Go to Vim and
press the middle mouse button: The selected text is inserted.
Select some text in Vim and do "+y. Go to your browser, select some text in
a textfield by dragging with the mouse. Now use the right mouse button and
select "Paste" from the popup menu. The selected text is overwritten by the
text from Vim.
Note that the text in the "+ register remains available when making a Visual
selection, which makes other text available in the "* register. That allows
overwriting selected text.
This works for me ( case for + register, what i use like exchange buffer between aps ):
imap <silent> <S-Insert> <C-O>:set noai<CR><C-R>+<C-O>:set ai<CR>
From vim: ]p
From outside: "*]p or "+]p
This issue has already been answered, but I though I could also add my own solution:
If you simply want to disable auto-indent system wise, for every file type (basically, disable the auto-indent feature completely), you can do the following:
Backup the indent.vim file:
sudo mv /usr/share/vim/vim81/indent.vim /usr/share/vim/vim81/indent.vim.orig
Create a new empty indent.vim file:
sudo touch /usr/share/vim/vim81/indent.vim
If you are on a mac, macvim seems to handle it well without having to toggle paste.
brew install macvim --override-system-vim
Please read this article: Toggle auto-indenting for code paste
Some people like the visual feedback shown in the status line by the following alternative for your vimrc:
nnoremap <F2> :set invpaste paste?<CR>
set pastetoggle=<F2>
set showmode
The fastest way I’m aware of to quickly go to paste-insert mode for a one-shot paste is tpope’s unimpaired, which features yo and yO, presumably mnemonics for “you open”. They’re only documented in his vimdoc, as:
A toggle has not been provided for 'paste' because the typical use case of
wrapping of a solitary insertion is so wasteful: You toggle twice, but
you only paste once (YOPO). Instead, press yo or yO to invoke o or O with
'paste' already set. Leaving insert mode sets 'nopaste' automatically.
Native paste / bracketed paste is the best and simplest way since vim 8 (released in 2016). It even works over ssh! (Bracketed paste works on Linux and Mac, but not Windows Git Bash)
Make sure you have vim 8+ (you don't need the +clipboard or +xterm_clipboard options).
vim --version | head -1
Simply use the OS native paste command (e.g. ctrl+shift+V or cmd+V) in Normal Mode. Do not press i for Insert Mode.
Test
Copy (ctrl+shift+C or cmd+C) the output of this (2 lines with a tab indent) to the system clipboard:
echo -e '\ta\n\tb'
Launch a clean vim 8+ with autoindent:
vim -u NONE --noplugin -c 'set autoindent'
Paste from the system clipboard (ctrl+shift+V or cmd+V) in Normal Mode. Do not press i for Insert Mode. The a and b should be aligned with a single tab indent. You can even do this while ssh-ing to a remote machine (the remote machine will need vim 8+).
Now try the old way, which will autoindent the second line with an extra tab: Press i for Insert Mode. Then paste using ctrl+shift+V or cmd+V. The a and b are misaligned now.
Installing Vim 8
Ubuntu 18.04 - comes with Vim 8 by default.
Ubuntu 16.04 - install from a PPA.
sudo add-apt-repository ppa:jonathonf/vim
sudo apt update
sudo apt install vim
Mac: brew install vim
The following vim plugin handles that automatically through its "Bracketed Paste" mode: https://github.com/wincent/terminus
Sets up "Bracketed Paste" mode, which means you can forget about manually setting the 'paste' option and simply go ahead and paste in any mode.
Sadly I found the vim plugin mentioned not to be working with iTerm2 3.0.15 (to be fair I don't know if this broke on older versions) - but I found this hack instead.
Map command-p to do the paste and using iTerm2 vim keys. Obviously this only works for iTerm2.
How it works. I use "jk" to enter escape mode so you will also need:
:inoremap jk
in your .vimrc.
Then it just invokes P to enter paste mode, "+p to paste from the clipboard and then P to disable paste mode. hth.
If you use the vim above v8.2, you can check with :help tmux-integration.
If you experience issues when running Vim inside tmux, here are a few hints.
You can comment-out parts if something doesn't work (it may depend on the
terminal that tmux is running in):
if !has('gui_running') && &term =~ '^\%(screen\|tmux\)'
" Better mouse support, see :help 'ttymouse'
set ttymouse=sgr
" Enable true colors, see :help xterm-true-color
let &termguicolors = v:true
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
" Enable bracketed paste mode, see :help xterm-bracketed-paste
let &t_BE = "\<Esc>[?2004h"
let &t_BD = "\<Esc>[?2004l"
let &t_PS = "\<Esc>[200~"
let &t_PE = "\<Esc>[201~"
" Enable focus event tracking, see :help xterm-focus-event
let &t_fe = "\<Esc>[?1004h"
let &t_fd = "\<Esc>[?1004l"
" Enable modified arrow keys, see :help xterm-modifier-keys
execute "silent! set <xUp>=\<Esc>[#;*A"
execute "silent! set <xDown>=\<Esc>[#;*B"
execute "silent! set <xRight>=\<Esc>[#;*C"
execute "silent! set <xLeft>=\<Esc>[#;*D"
endif

Vim / vi Survival Guide

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

Resources