From 5c4223b27dcf161d7b0f8c660d413425d9fefd0a Mon Sep 17 00:00:00 2001 From: jdhao Date: Sun, 27 Sep 2020 21:29:46 +0800 Subject: [PATCH] add mapping to move single or multiple lines --- autoload/utils.vim | 45 +++++++++++++++++++++++++++++++++++++++++++++ mappings.vim | 8 ++++++++ 2 files changed, 53 insertions(+) diff --git a/autoload/utils.vim b/autoload/utils.vim index 0f9ee19..44125ac 100644 --- a/autoload/utils.vim +++ b/autoload/utils.vim @@ -85,3 +85,48 @@ function! utils#ToggleCursorCol() abort echo 'cursorcolumn: ON' endif endfunction + +function! utils#SwitchLine(src_line_idx, direction) abort + if a:direction ==# 'up' + if a:src_line_idx == 1 + return + endif + move-2 + elseif a:direction ==# 'down' + if a:src_line_idx == line('$') + return + endif + move+1 + endif +endfunction + +function! utils#MoveSelection(direction) abort + " only do this if previous mode is visual line mode. Once we press some keys in + " visual line mode, we will leave this mode. So the output of `mode()` will be + " `n` instead of `V`. We can use `visualmode()` instead to check the previous + " mode, see also https://stackoverflow.com/a/61486601/6064933 + if visualmode() !=# 'V' + return + endif + + let l:start_line = line("'<") + let l:end_line = line("'>") + let l:num_line = l:end_line - l:start_line + 1 + + if a:direction ==# 'up' + if l:start_line == 1 + " we can also directly use `normal gv`, see https://stackoverflow.com/q/9724123/6064933 + normal gv + return + endif + silent execute printf('%s,%smove-2', l:start_line, l:end_line) + normal gv + elseif a:direction ==# 'down' + if l:end_line == line('$') + normal gv + return + endif + silent execute printf('%s,%smove+%s', l:start_line, l:end_line, l:num_line) + normal gv + endif +endfunction diff --git a/mappings.vim b/mappings.vim index 5c4a0a1..53f2ed7 100644 --- a/mappings.vim +++ b/mappings.vim @@ -167,4 +167,12 @@ nnoremap y :%y " Toggle cursor column nnoremap cl :call utils#ToggleCursorCol() + +" Move current line up and down +nnoremap call utils#SwitchLine(line('.'), 'up') +nnoremap call utils#SwitchLine(line('.'), 'down') + +" Move current visual-line selection up and down +xnoremap :call utils#MoveSelection('up') +xnoremap :call utils#MoveSelection('down') "}