vim how to break new line without entering Insert mode - vim

I have a few lines of codes that are too that I would like to break into 2 lines at certain location.
So instead of moving to the position then presse I to insert mode then Enter to break line then finally ESc back.
Is there way I can do it easier in normal mode only?
Many thanks.

You can define some simple mapping for it:
" <C-Enter> Insert single / [count] newline.
nnoremap <C-CR> i<CR><Esc>
Note that <C-CR> probably only works in GVIM, not in a terminal; choose a different key if necessary.
Here's an additional mapping that keeps the cursor on the original line:
" <C-S-Enter> Append single / [count] newline.
function! s:AppendCRSetPos()
keepjumps call setpos("''", getpos('.'))
return ''
endfunction
nnoremap <expr> <SID>(AppendCRSetPos) <SID>AppendCRSetPos()
nnoremap <script> <C-S-CR> <SID>(AppendCRSetPos)i<CR><Esc>g``

I have the following in my .vimrc
nnoremap S i<cr><esc>^mwgk:silent! s/\v +$//<cr>:noh<cr>`w
Which will split the line on pressing capital S.
Hope this helps

There is a vim key for that:
r<Enter>

Related

Function to Comment Multiple Lines Vimrc

So I currently like this solution to commenting multiple lines in vim:
Press CTRL-v (to go into Visual Block mode)
Select the lines you want to comment
Press Shift-i (to go into Insert mode)
Type whatever comment characters your language uses
Press ESC ESC (pressing the escape key twice makes the results appear faster)
But I would like some help mapping these steps into my vimrc file.
I currently use the following to comment lines out:
vnoremap ;/ <C-v>0I// <ESC>
For those who want an explanation of what the command does:
You basically type ;/ when you're in Visual mode to use this (Visual, Visual Line, and Visual Block mode all work since the <C-v> part forces you into Visual Block mode, which is correct).
The 0I part will put you in Insert mode at the beginning of the line.
The // <ESC> part will insert the comment characters // and put you back into Normal mode.
The part I need help with is uncommenting the lines. How do I write a function in my vimrc that will basically let me toggle the // characters?
Ideally, the solution would involve the following:
Selecting the lines
Pressing ;/
If there are NO // characters then it will insert them
If there ARE // characters then it will remove them
Put this in your .vimrc file:
vnoremap <silent> ;/ :call ToggleComment()<cr>
function! ToggleComment()
if matchstr(getline(line(".")),'^\s*\/\/.*$') == ''
:execute "s:^://:"
else
:execute "s:^\s*//::"
endif
endfunction
check the Commentary plugin. It allows to have one binding for all languages.
Pretty easy with python script
function! Comment()
python3 << EOF
import vim
r = vim.current.range
line = vim.current.buffer[r.start]
if line.startswith('// '):
vim.current.buffer[r.start] = vim.current.buffer[r.start].replace('// ', '')
else:
vim.current.buffer[r.start] = '// ' + vim.current.buffer[r.start]
EOF
endfunction
" ctrl slash
noremap <C-_> :call Comment()<CR>

Vim - line break/comment remapping

I've added the following line un my .vimrc to add a line break when I press enter in normal mode:
"" insert line break in normal mode on Enter
nmap <S-Enter> O<Esc>
nmap <CR> o<Esc>
This works fine except when I want to comment the current line in normal mode by pressing cmd+/ where it comments the current line and add a line break which is also commented.
How can I fix this?
Many thanks
The comments together give the answer; here's the summary:
You see the default formatting behavior when inserting a new line after a commented one. It's caused by the o value in 'formatoptions'. You could modify your mapping to
set formatoptions-=o
But there are alternative approaches for inserting a new empty line:
nnoremap <silent> <S-Enter> :put! _<CR>
nnoremap <silent> <CR> :put _<CR>
(PS: You should use :noremap; it makes the mapping immune to remapping and recursion.)
Also, there are plugins that provide this (and several related mappings):
unimpaired.vim - Pairs of handy bracket mappings
my LineJuggler plugin

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>

Move to the beginning of line while in Insert mode

I know that I can use either:
Home in insert mode
Esc + i to exit insert mode and enter it again, effectively going to the beginning of line.
But neither satisfies me. In first case I have to tilt my head to hit Home, because I can't blindly hit it. In second case my left arm has to leave the home row to hit Esc, which is annoying too.
Any thoughts?
Ctrl+O whilst in insert mode puts you in command mode for one key press only. Therefore Ctrl+O then Shift+I should accomplish what you're looking for.
You could enter insert mode using I (capital i).
It will put the cursor at the beginning of the line.
Similarly you can use A to add something at the end of the line.
Though, it does not really solve the problem of moving while already being in Insert mode.
I have just checked help on Insert mode, there is no key combination in insert mode to move at the beginning of the line.
Other idea :
Remap a new command only in insert mode
inoremap <C-i> <Home>
I've got Ctrl+a and Ctrl+e mapped to beginning and end of line, respectively. This matches the behavior of most bash command lines. Works well for me.
inoremap <C-e> <Esc>A
inoremap <C-a> <Esc>I
If you are using MacOS Terminal go to Preferences...>Settings>Keyboard and map the end key to Ctrl-O$ (it is displayed as \017$) and then use fn+left to simulate the end key. Do the same for the home key. Escape sequence \033[H also works for home.
Your best course of action is to remap the action to a different key (see How to remap <Ctrl-Home> to go to first line in file? for ideas)
I'd think of how often I use this "feature" and map it to a keystroke accordinly
You can map the keys to this:
inoremap II <Esc>I
ref: http://vim.wikia.com/wiki/Quick_command_in_insert_mode
A shortcut that has worked for me (both muscle memory and intuitiveness) is to map __ (which is a double _) to "insert at start of current line".
Rationale:
_ already goes to the start of line
in vim, doubling anything is a very common way of doing that "to this line"
double _ doesn't conflict with any motions (you're already at the start of line)
your hand is already in the right place if you went to the beginning of the line and now want to insert.
vimscript:
"insert at start of current line by typing in __ (two underscores)
function DoubleUnderscore()
if v:count == 0 && getcurpos()[2] == 1
:silent call feedkeys('I', 'n')
else
:silent call feedkeys('^', v:count + 'n')
endif
endfunction
nnoremap <silent> _ :call DoubleUnderscore()<CR>
It's this complicated because the easy alternative nnoremap __ _I causes vim to delay on pressing _ to distinguish between _ and __.
ctrl+o then 0
| |
letter number
i use this command to go to end of line without leaving insert mode
inoremap jl <esc><S-a>
Similarly to go to beginning of line will be:
inoremap jl <esc><S-i>

Resources