Keep the cursor column while swapping buffers in vim - vim

In vim, if you swap buffers with :bn and :bp, the cursor stays on the same line, but not on the same column. Is there a way to keep it on the same column as well ?

:set nostartofline
from the help: "In case of buffer changing commands the cursor is placed at the column where it was the last time the buffer was edited."

Off the top of my head I don't think so. But Vim sets the mark " as the last position when exiting a buffer. So typing `" will get you back to that spot. You could try creating an auto-command to jump to that mark automatically on entering a buffer. Try something like
:au BufEnter * :normal `"

Related

move the text after the cursor to a new line

I am Vim newbie, and I'm using MacVim on OSX Snow Leopard. One of the most common actions I have to take is to move the cursor to a new line but also move the text after the cursor to the new line. I know that pressing 'o' in normal or visual mode moves the cursor to a new line and switches the mode to insert.
What I'd like to do is move the cursor to a new line, and move the text after the cursor to that new line as well, preferably staying in the normal mode? Is this possible? How can I accomplish this task?
If the cursor is on a <space> as in ([] marks the cursor):
lorem ipsum[ ]dolor sit amet
the simplest is to do r<CR>, that is "replace the current character with a linebreak".
Otherwise, use #knittl's solution.
So you want to move everything in the current line, which comes after the cursor to the next line? Read: insert a line break??
(move cursor)
i (or a)
<return>
<esc> (or ^C)
To map this sequence of keystrokes to a single key, follow #thb's suggestion and use the :map command:
:map <F2> i<CR><ESC>
:map <F2> i<CR>
This keeps vi in insert mode.
As I answered in this post, How do I insert a linebreak where the cursor is without entering into insert mode in Vim?.
Please try Control + j.
The code below achieves the same behavior as "normal" editors (for the lack of better terms on the top of my mind) except that you'd have to press "enter" twice instead of once.
I also wanted to get rid of the space if it's right before my current character.
There might be an easier way and I totally welcome edits :-)
" in ~/.vimrc or ~/.vimrc.after if you're using janus
nnoremap <cr><cr> :call ReturnToNewLine()<cr>
function ReturnToNewLine()
let previous_char = getline(".")[col(".")-2]
" if there's a space before our current position, get rid of it first
if previous_char == ' '
execute "normal! \<bs>\<esc>"
endif
execute "normal! i\<cr>\<esc>"
endfunction
This remaps pressing enter twice to going to insert mode, placing a carriage return and escaping.
The reason I'm using this mapping (enter twice) is because I was used to this functionality with other text editors by pressing a enter; also, typing enter twice is fast.
Another thing that I found useful in this context was allowing vim to move right after the last character (in case I wanted to move the last character to a new line). So I have the following in my ~/.vimrc as well.
set virtualedit=onemore
Note that I'm using nnoremap (normal mode non-recursive) instead of map (which is VERY dangerous) (check this out for more information on the differences http://learnvimscriptthehardway.stevelosh.com/chapters/05.html)
You need to map some keys to do a line break at the cursor,
I found the following mapping easy to use, just go to your vimrc and add this line:
:map <silent> bl i<CR><ESC>
to assign a line break at cursor to "bl" combo

Indenting entire file in Vim without leaving current cursor location

I already know that gg=G can indent the entire file on Vim. But this will make me go to the beginning of the file after indent. How can I indent the entire file and maintain the cursor at the same position?
See :h ''
This will get you back to the first char on the line you start on:
gg=G''
and this will get you back to the starting line and the starting column:
gg=G``
I assume the second version, with the backtick, is the one you want. In practice I usually just use the double apostrophe version, since the backtick is hard to access on my keyboard.
Add this to your .vimrc
function! Preserve(command)
" Preparation: save last search, and cursor position.
let _s=#/
let l = line(".")
let c = col(".")
" Do the business:
execute a:command
" Clean up: restore previous search history, and cursor position
let #/=_s
call cursor(l, c)
endfunction
nmap <leader>> :call Preserve("normal gg>G")<CR>
You can also use this on any other command you want, just change the argument to the preserve function. Idea taken from here: http://vimcasts.org/episodes/tidying-whitespace/
You can set a bookmark for the current position with the m command followed by a letter. Then after you run the indent command, you can go back to that bookmark with the ` (backtick) command followed by the same letter.
In a similar spirit to Alex's answer I use the following mapping in vimrc.
nnoremap g= :let b:PlugView=winsaveview()<CR>gg=G:call winrestview(b:PlugView) <CR>:echo "file indented"<CR>
by pressing g= in normal mode the whole buffer is indented, and the scroll/cursor position is retained.
Following on top of Herbert's solution, the reader can also use <C-o>
In vim script
exe "norm! gg=G\<C-o>"
Or mapping
:nnoremap <F10> gg=G\<C-o>

cursor not going to end of line in vim

I installed Ubuntu recently and fiddled around with profile preferences in terminal. Now when I edit in vim, the cursor doesn't go to the end of a line using navigation keys (In normal mode. '$' doesn't work either). However, it does show itself correctly in insert mode. This is merely a nuisance, but I'd rather be not having it. How to correct this?
Virtualedit permits the cursor to move past the end of line. Try :set ve+=all or :set ve+=onemore. For more information see:
:h ve. These settings can be made default by adding corresponding command without : to your ~/.vimrc file.
This is the correct behavior in vim. The cursor will only go to the last character unless in insert mode.
I added this to my vimrc and it seems to work.
set selection=exclusive
" allows cursor to go to the end of line with g$
set virtualedit+=onemore
noremap $ g$
" Remap VIM 1 to first non-blank character and 2 to the last non-blank character
nnoremap 1 ^
nnoremap 2 g$
" mapping for <End>
map <Esc>[4~ g$

Vim: Close All Buffers But This One

How can I close all buffers in Vim except the one I am currently editing?
I was able to do this pretty easily like this:
:%bd|e#
Try this
bufdo bd
bufdo runs command for all buffers
http://vim.wikia.com/wiki/Run_a_command_in_multiple_buffers
You could use this script from vim.org:
http://www.vim.org/scripts/script.php?script_id=1071
Just put it to your .vim/plugin directory and then use :BufOnly command to close all buffers but the active one. You could also map it elsewhere you like in your .vimrc.
Source on Github (via vim-scripts mirror): https://github.com/vim-scripts/BufOnly.vim/blob/master/plugin/BufOnly.vim
If you donĀ“t care the current one, is more simple to do something like (no script needing):
1,100bd
I do this
:w | %bd | e#
My favorite if I just want my current buffer open and close all others.
How it works: first write current buffer's changes, then close all open buffers, then reopen the buffer I was currently on. In Vim, the | chains the execution of commands together. If your buffer is up to date the above can be shortened to :%bd | e#
Building on juananruiz's answer.
Make a small change in the buffer you want to keep, then
:1,1000bd
The command bd (buffer delete) will not delete any buffers with unsaved changes. This way you can keep the current (changed) file in the buffer list.
Edit: Please notice that this will also delete your NERDTreeBuffer. You can get it back with :NERDTree
Note: As mentioned in the comments, this closes windows and not buffers.
By using
:on[ly][!]
and
:h only
I put this in my .vimrc file
nnoremap <leader>ca :w <bar> %bd <bar> e# <bar> bd# <CR>
then your leader + ca (close all) close all the buffers except the current one.
What it does is
:w - save current buffer
%bd - close all the buffers
e# - open last edited file
bd# - close the unnamed buffer
Here's what I do. So I like to keep my cursor position after removing all buffers and most of the solutions above just ignores this fact. I also think remapping the command is better than typing it so Here I use <leader>bd to remove all buffers and jump back to my original cursor position.
noremap <leader>bd :%bd\|e#\|bd#<cr>\|'"
%bd = delete all buffers.
e# = open the last buffer for editing (Which Is the buffer I'm working on).
bd# to delete the [No Name] buffer that gets created when you use %bd.
The pipe in between just does one command after another. You've gotta escape it though using \|
'" = keep my cursor position.
Closing all open buffers:
silent! execute "1,".bufnr("$")."bd"
Closing all open buffers except for the current one:
function! CloseAllBuffersButCurrent()
let curr = bufnr("%")
let last = bufnr("$")
if curr > 1 | silent! execute "1,".(curr-1)."bd" | endif
if curr < last | silent! execute (curr+1).",".last."bd" | endif
endfunction
Add this function to .vimrc and call it using :call CloseAllBuffersButCurrent().
Convenience map:
nmap <Leader>\c :call CloseAllBuffersButCurrent()<CR>
There's a plugin that does exactly this and a bit more!
Check out close-buffers.vim
so this is an old question but it helped me get some ideas for my project. in order to close all buffers but the one you are currently using, use;
map <leader>o :execute "%bd\|e#"<CR>
The answer with highest votes will reopen the buffer, it will lose the current line we are working on.
Close then reopen will induce a flush on screen
function! CloseOtherBuffer()
let l:bufnr = bufnr()
execute "only"
for buffer in getbufinfo()
if !buffer.listed
continue
endif
if buffer.bufnr == l:bufnr
continue
else
if buffer.changed
echo buffer.name . " has changed, save first"
continue
endif
let l:cmd = "bdelete " . buffer.bufnr
execute l:cmd
endif
endfor
endfunction
let mapleader = ','
nnoremap <leader>o :call CloseOtherBuffer()<CR>
Previous code will take effect when you are on the target buffer and press , + o. It will close all other buffers except current one.
It iterates all the buffers and close all the buffer number which is not equal to current buffer number.
:%bd then Ctrl-o
:%bd to delete all buffers
Ctrl-o to jump back to the last buffer, which would be the "This One" you were referring to.
I like 1,100bd (suggested by juananruiz) which seems to work for me.
I added a quit! to my mapping to give me
nnoremap <leader>bd :1,100bd<CR>
nnoremap <leader>bdq :1,100bd<CR>:q!<CR>
This kills all the buffers and shuts down Vim, which is what I was looking for mostly.
How about just:
ctrl-w o
(thanks to https://thoughtbot.com/blog/vim-splits-move-faster-and-more-naturally)
I combined Alejandro's comment with badteeth's comment:
command! Bonly silent execute "%bd|norm <C-O>"
The norm <C-O> jumps to the last position in the jump list, which means where the cursor was before the %bd.
I used silent instead of silent!. That way, if any open buffers are modified, Vim prints an error message so I know what happened. The modified buffers stay open in my tests.
Unrelated: this is my 500th answer!
nnoremap <leader>x :execute '%bdelete\|edit #\|normal `"'\|bdelete#<CR>
Close all buffers (side-effect creates new empty buffer)
Open last buffer
Jump to last edit position in buffer
Delete empty buffer

In Vim, can I format a whole file and end with the cursor where it started?

I set up this mapping in my .vimrc and it works great...
" Auto indent entire file
nmap <C-f> gg=G
imap <C-f> <ESC>gg=G
However, after the operation the cursor has moved to line 1, column 1.
Is there a way to do it so that if I'm in the middle of the file somewhere the cursor will remain where it is?
Sure, use marks (:help mark):
nmap <C-f> mtgg=G't
imap <C-f> <ESC><C-f>
Before executing gg=G, the current cursor position is saved to mark t. After the operation, 't jumps back to the mark.
Ctrl+O is good for walking back through the jump list. '' will move you back to the last line in the jump list (or `` to go back to the last line and column).
Unfortunately, there isn't an "entire buffer" text object, so gg=G requires moving back two places in the jump list.
Brian's solution above will work for a macro, but as a good tip, note that Ctrl+O will go to the previous cursor position in the jump list. So if you ever do an operation that moves away, you can step back to a previous position.
Why not use ma to mark the current position in buffer a, and after the transformation use ``a(i.e.backtick+a`) to return to that position ? Here's an article on using marks to move around.
As jamessan wrote, Ctrl+o jumps back to the last posistion in the jumplist. After calling gg=G, this has to be called twice.
Thus, you can use a mapping without marks:
map <silent> <C-f> gg=G<C-o><C-o>
imap <silent> <C-f> <Esc> gg=G<C-o><C-o>

Resources