VIM - How can I put my current position in jumplist? - vim

I am wondering about a improvement for vim that I can jump back for where I was the last time I stopped to move around for like 3 seconds. Then I can scroll around and have a kick shortcut to jump back where I was with the same old CTRL+o.
Vim put a lot of movements in the :jumps list and I wondering that half of that is useless in any moment for me, so how could I do that ?
In any another words I'm trying to make the jumplist more sensible.
ps: Netbeans and VS has a similar behavior.

To have the current position automatically added to the jump list, you can utilize the CursorHold event:
:autocmd CursorHold * normal! m'
Navigation is with the default <C-o> / <C-i>.

It's common to use the m and ' commands to jump around. For instance, you can type mx, go off and do some things, and then do 'x to jump back to where you were when you did mx. This works for every letter of the alphabet (i.e. ma, mb,... mz). Uppercase marks (mA, mB,...) will also remember the filename so you can jump between files. There are a number of other special marks you can set for various purposes.
The "previous context mark" is called '. It is set automatically when you jump around, and can also be manually set with m'. Jump to it with ''. The m' command also manually adds a jump to the jumplist. '' is roughly equivalent to Ctrl+O, but doesn't take a count.
If you replace the apostrophes in these commands with backticks, Vim will jump to the specific column rather than just the line. In practice, apostrophe is easier to type and often close enough.

You can set a mark in the ' register. The keystrokes would be m'
I found this in vim's documentation :help jumplist.
You can explicitly add a jump by setting the ' mark with "m'".

Related

How to keep my own CR in Vim with automatic format?

I used set fo+=a in Vim to enable automatic format when typing.
With that set, the <CR> I pressed will be erased when I continue to type, if the length of current line is less than lw, and that is not what I want.
What I want is:
Still able to add a <CR> automatically if the line is longer than lw.
When I type a <CR> manually when the line length is less than lw, I don't want that <CR> erased when I continue to type.
Thanks.
You can't. The format option "a" is designed to reformat your paragraph every time your paragraph is changed, so there's no way for you to keep any single line breaks inside your paragraph, regarding the definition of "paragraph" in VIM.
If you only need to be able to wrap long lines while typing, you don't need option "a". Option "t" is already quite sufficient for your case.
t Auto-wrap text using textwidth
If you are fine with using trailing spaces to indicate that a paragraph continues (by default it only ends on an empty line) then you can also do
set fo+=w
. Then to keep vim from joining lines all you need is to end it with something other then a space.
Note: this is not going to change the meaning of the paragraph for motion commands (in fact, there is nothing that can do change it).

Change delimiters for navigating word-wise

When programming/writing I heavily use word-wise commands, for example "move to the left/right by one word", "delete next/last word" by pressing Ctrl (+left,backspace...).
The problem I have is, when the text I am editing contains symbols which will not be recognized as words, therefore ctrl + right will jump over a sequence of symbols AND a regular word after that.
Ideally I want to be able to set the delimiting characters for word-wise operations to space, tab, newline and opening and closing brackets - maybe also arithmetic operators (similar to how Eclipse handles it).
I am using Linux. Do you know any way how to change my settings system-wide or alternatively for xterm and (g)vim individually to achieve this?
Most likely, system-wide won't work. VIM is easy, you can set the characters that define the identifier using the iskeyword setting. In your case, there is too much in it, and you need to remove the ones you do need, or redefine it by adding the ones you do want. eg: :set isk=9,32,50-51
This will set keyword detection to spaces, tabs and parentheses.
However, in VIM you can jump based on word and WORDs, where the first is defined by the abovementioned iskeyword setting, while the latter will jump over all non-blank characters. Maybe, that's the motion you want. You can read more about this in the help (:help w).
Instead of holding down the control key and pressing the left/right cursor keys, why not use Vim's normal mode word motion commands?
w/W - move to start of next word/WORD
e/E - move to end of next word/WORD
b/B - move to beginning of previous word/WORD
ge/gE - move to end of previous word/WORD
You can read up on the difference between a word and a WORD by running :help word.

Simple Vim commands you wish you'd known earlier [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm learning new commands in Vim all the time, but I'm sure everyone learns something new once in a while. I just recently learned about this:
zz, zt, zb - position cursor at middle, top, or bottom of screen
What are some other useful or elegant commands you wish you'd learned ages ago?
I really wish I'd known that you can use Ctrl+C instead of Esc to switch out of insert mode. That's been a real productivity boost for me.
The most recent "wow" trick that I learnt is a method of doing complicated search-and-replace. Quite often in the past, I've had a really complicated regexp to do substitutions on and it's not worked. There is a better way:
:set incsearch " I have this in .vimrc
/my complicated regexp " Highlighted as you enter characters
:%s//replace with this/ " You don't have to type it again
The "trick" here (for want of a better word) is the way that you can use the search to create the regexp (and 'incsearch' highlights it as you enter characters) and then use an empty pattern in the substitution: the empty pattern defaults to the last search pattern.
Example:
/blue\(\d\+\)
:%s//red\1/
Equivalent to:
:%s/blue\(\d\+\)/red\1/
See:
:help 'incsearch'
:help :substitute
I created this reference of my most used command for a friend of mine:
select v
select row(s) SHIFT + v
select blocks (columns) CTRL + v
indent selected text >
unindent selected text <
list buffers :ls
open buffer :bN (N = buffer number)
print :hardcopy
open a file :e /path/to/file.txt
:e C:\Path\To\File.txt
sort selected rows :sort
search for word under cursor *
open file under cursor gf
(absolute path or relative)
format selected code =
select contents of entire file ggVG
convert selected text to uppercase U
convert selected text to lowercase u
invert case of selected text ~
convert tabs to spaces :retab
start recording a macro qX (X = key to assign macro to)
stop recording a macro q
playback macro #X (X = key macro was assigned to)
replay previously played macro * ##
auto-complete a word you are typing ** CTRL + n
bookmark current place in file mX (X = key to assign bookmark to)
jump to bookmark `X (X = key bookmark was assigned to
` = back tick/tilde key)
show all bookmarks :marks
delete a bookmark :delm X (X = key bookmark to delete)
delete all bookmarks :delm!
split screen horizontally :split
split screen vertically :vsplit
navigating split screens CTRL + w + j = move down a screen
CTRL + w + k = move up a screen
CTRL + w + h = move left a screen
CTRL + w + l = move right a screen
close all other split screens :only
* - As with other commands in vi, you can playback a macro any number of times.
The following command would playback the macro assigned to the key `w' 100
times: 100#w
** - Vim uses words that exist in your current buffer and any other buffer you may have open for auto-complete suggestions.
gi switches to insertion mode, placing the cursor at the same location it was previously.
:q!
I wish I knew that before I started vi for the first time.
^X-F completes using filenames from the current directory. No more copying/pasting from the terminal or painful double checking.
^X-P completes using words in the current file
:set scrollbind forces one buffer to scroll alongside another. e.g. split your window into two vertical panes. Load one file in each (perhaps different versions of the same file). Do :set scrollbind in each. Now when you scroll in one, both panes will scroll together. Ideal for comparing files.
You can use a whole set of commands to change text inside brackets / parentheses / quotation marks/ tags. It's super useful to avoid having to find the start and finish of the group. Try ci(, ci{, ci<, ci", ci', ct depending on what kind of object you want to change. And the ca(, ca{, ... variants delete the brackets / quotation marks as well.
Easy to remember: change inside a bracketed statement / change a bracketed statement.
The asterisk key, *, will search for the word under the cursor.
[+Tab will take you to the definition of a C function that's under your cursor. (It doesn't always work, though.)
Don't press Esc ever. See this answer to learn why. As mentioned above, Ctrl + C is a better alternative. I strongly suggest mapping your Caps Lock key to escape.
If you're editing a Ctags compatible language, using a tags file and :ta, Ctrl + ], etc. is a great way to navigate the code, even across multiple files. Also, Ctrl + N and Ctrl + P completion using the tags file is a great way to cut down on keystrokes.
If you're editing a line that is wrapped because it's wider than your buffer, you can move up/down using gk and gj.
Try to focus on effective use of the motion commands before you learn bad habits. Things like using 'dt' or 'd3w' instead of pressing x a bunch of times. Basically, any time that you find yourself pressing the same key repeatedly, there's probably a better/faster/more concise way of accomplishing the same thing.
Some of my latest additions to my Vim brainstore:
^wi: Jump to the tag under the cursor by splitting the window.
cib/ciB: Change the text inside the current set of parenthesis () or braces {}, respectively.
:set listchars=tab:>-,trail:_ list: Show tabs/trailing spaces visually different from other spaces. It helps a lot with Python coding.
ZZ (works like :wq)
And about the cursor position: I found that a cursor which always stays in the middle of screen is cool -
set scrolloff=9999
gv starts visual mode and automatically selects what you previously had selected.
:shell to launch a shell console from Vim. Useful when for example you want to test a script without quitting Vim. Simply hit ^d when you done with the shell console, and then you come back to Vim and your edited file.
This always cheers me up:
:help 42
vimcryption
vim -x filename.txt
You will be asked for a passphrase, edit and save. Now whenever you open the file in vi again you will have to enter the password to view.
Build and debug your code from within Vim!
Configuration
Not much, really. You need a Makefile in the current directory.
To Compile
While you're in Vim, type :make to invoke a shell and build your program. Don't worry when the output scrolls by; just press Enter when it's finished to return to Vim.
The Magic
Back within Vim, you have the following commands at your disposal:
:cl lists the errors, warnings, and other messages.
:cc displays the current error/warning message at the bottom of the screen and jumps to the offending line in your code.
:cc n jumps to the nth message.
:cn advances to the next message.
:cp jumps to the previous message.
There are more; if you're interested, type :help :cc from within Vim.
Press % when the cursor is on a quote, parenthesis, bracket, or brace to find its match.
^P and ^N
Complete previous (^P) or next (^N) text.
^O and ^I
Go to previous (^O - "O" for old) location or to the next (^I - "I" just near to "O").
When you perform searches, edit files, etc., you can navigate through these "jumps" forward and back.
Marks
Press ma (m- mark, a - name of mark). Later to return to the position, type `a.
^r^w to paste the word under the cursor in command mode.
It is really useful when using grep or replace commands.
Until [character] (t). It is useful for any command which accepts a range. My favorite is ct; or ct) which deletes everything up to the trailing semicolon / closing parentheses and then places you in insert mode.
Also, G and gg are useful (Go to bottom and top respectively).
^y will copy the character above the cursor.
Typing a line number followed by gg will take you to that line.
I wish I'd known basic visual block mode stuff earlier. Even if you don't use Vim for anything else, it can be a big time saver to open up a file in Vim just for some block operations. I'm quite sure I wasted a ton of time doing this kind of thing manually.
Examples I've found particularly useful, when, say, refactoring lists of symbolic constant names consistently:
Enter Visual Block mode (Ctrl + Q for me on Windows instead of Ctrl + V)
Move the cursor to highlight the desired block.
Then, I whatever text and press Esc to have the text inserted in front of the block on every line.
Use A instead of I to have the text inserted after the block on every line.
Also - simply toggling the case of a visual selection with ~ can be a big time saver.
And simply deleting columns, too, with d of course.
q<letter> - records a macro.
and
#<same-letter> - plays it back.
These are by far the most useful commands in Vim since you can have the computer do a whole lot of work for you, and you don't even have to write a program or anything.
Opening multiple files using tabs
:tabe filepath
Navigating between open files
gt and gT or :tabn and :tabp
Save the open session so that you can get back to your list of open files later
:mksession session_file_name.vim
Open a created session
vim -S session_file_name.vim
Close all files at once
:qa
Another command I learned recently
autocmd
It allows you to run a command on an event, so you could for example run the command make when you save a file using something like:
:autocmd BufWritePost *.cpp :make
qx will start recording keystrokes. You can do pretty much any editing task and Vim remembers it. Hit q again when you're finished, and press #x to replay your keystrokes. This is great for repetitive edits which are too complex to write a mapping for. You can have many recordings by using a character other than x.
I would have to say that one of my favorites is putting the help window in a new tab:
:tab help <help_topic>
This opens up help in a new tab and, as somebody that loves Vim tabs, this is ridiculously useful.
:x #(Save and Quit a File)
Same as :wq or ZZ
cw
Change word - deletes the word under the cursor and puts you in insert mode to type a new one. Of course this works with other movement keys, so you can do things like c$ to change to the end of the line.
f + character
Finds the next occurrence of the character on the current line. So you can do vft to select all the text up to the next "t" on the current line. It's another movement key, so it works with other commands too.
:b [any portion of a buffer name] to switch buffers. So if you have two buffers, "somefile1.txt", and "someotherfile2.txt", you can switch to the second with simply ":b 2.t<enter>". It also supports tab completion, although it's not required.
Speaking of tab completion, the setting :set wildmode=full wildmenu is also very helpful. It enables complete tab completion for command-mode, as well as a very helpful ncurses-style menu of all the possible matches when using it.

Vim keep cursor location while scrolling

Is there a way to keep the cusror location off-screen in Vim / gVim while scrolling? Similar to many Windows editors.
I know about marks, and do use them. I also know the '.' mark (last edit location), But looking for other ideas.
I'm asking this because sometimes i want to keep the cursor at some location, scroll to another place using the mouse-wheel, and then just press an arow key or something to get me back to that location.
No. vim is a console application, so it doesn't really make sense to have the cursour off-screen (it's possible, but would just be confusing)
An alternative solution, to paraphrase posts from this thread from comp.editors:
Ctrl+o goes to the previous cursor location, Ctrl+i goes to the next (like undo/redo for motions)
Marks seem like the other solution..
Also, use marks. Marks are named by letters. For instance typing ma remembers
the current location under mark a. To jump to the line containing mark a,
type 'a. To the exact location use `a.
Lower-case-letter marks are per-file. Upper-case-letter marks are global;
`A will switch to the file containing mark A, to the exact location.
Basically ma, move around, then `a to jump back.
Another option which Paul suggested,
gi command switches Vim to Insert mode and places cursor in the same position as where Insert mode was stopped last time.
Why don't you split the window, look at what you wanted to look at, and then close the split?
:split
or
:vsplit (if you want to split vertically)
The only similar behavior that I've found in Vim:
zt or zENTER "scroll the screen down as far as possible without moving the cursor"
zb "scroll as far up as possible".
Ctrl+E "scroll one line down, if possible"
Ctrl+Y"scroll one line up, if possible"
Sometimes you can avoid jumping to marks before entering text — gi command switches Vim to Insert mode and places cursor in the same position as where Insert mode was stopped last time.
Google says that the cursor (and therefore current line) must be visible in Vi, so you'll have to use marks.
Also very useful are the '' (2x single quotes) and `` (2x back quotes).
The former jumps back to the line you were prior to the last jump (for instance, a page down).
The latter jumps back to the line and column you were prior to the last jump.

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