aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorjdhao <jdhao@hotmail.com>2020-09-27 21:29:46 +0800
committerjdhao <jdhao@hotmail.com>2020-09-27 21:29:46 +0800
commit5c4223b27dcf161d7b0f8c660d413425d9fefd0a (patch)
tree7a792d5a5994ee96332517abaed00f4cc0902e14
parent2d843076955b5978a9a6ce4ec1f647bdb1133275 (diff)
add mapping to move single or multiple lines
-rw-r--r--autoload/utils.vim45
-rw-r--r--mappings.vim8
2 files changed, 53 insertions, 0 deletions
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 <silent> <leader>y :%y<CR>
" Toggle cursor column
nnoremap <silent> <leader>cl :call utils#ToggleCursorCol()<CR>
+
+" Move current line up and down
+nnoremap <silent> <A-k> <Cmd>call utils#SwitchLine(line('.'), 'up')<CR>
+nnoremap <silent> <A-j> <Cmd>call utils#SwitchLine(line('.'), 'down')<CR>
+
+" Move current visual-line selection up and down
+xnoremap <silent> <A-k> :<C-U>call utils#MoveSelection('up')<CR>
+xnoremap <silent> <A-j> :<C-U>call utils#MoveSelection('down')<CR>
"}