9

Using VS Code, how can I move the current line I am on (or the current selection) up or down using Vim keybindings? When using the editor as normal, I can achieve this using 'alt + up/down'.

I am using the vscodevim extension.

Kent
  • 189,393
  • 32
  • 233
  • 301
Hayden
  • 241
  • 3
  • 6

5 Answers5

5

adding the following to the settings.json. It uses J and K to move the line down/up in the normal mode.

"vim.normalModeKeyBindingsNonRecursive": [
    {
        "before": ["J"],
        "commands": ["editor.action.moveLinesDownAction"]
    }, // moveLineDown
    {
        "before": ["K"],
        "commands": ["editor.action.moveLinesUpAction"]
    } // moveLineUp
],
ahswch
  • 61
  • 1
  • 2
  • 1
    To use `Control` key instead of `Shift` use `""` `""` instead of `"J"`, `"K"` For me that is default vim behavior. – djsmentya Sep 03 '21 at 13:45
4

I have found adding the following to the keybindings.json works. It remaps the keys back to the native Visual Studio Code move lines commands. In this example I am using Command-Alt-Up/Down, but in theory you could use change the mappings to just Alt-Up/Down as you asked.

    {
        "key": "cmd+alt+up",
        "command": "editor.action.moveLinesUpAction",
        "when": "editorTextFocus && !editorReadOnly"
    },
    {
        "key": "cmd+alt+down",
        "command": "editor.action.moveLinesDownAction",
        "when": "editorTextFocus && !editorReadOnly"
    },

I will add that when there are multiple lines selected in visual mode it seems to select below it when moving up and I am not sure why. escape or just moving the cursor clears that extra selection.

studgeek
  • 14,272
  • 6
  • 84
  • 96
2

In vim there is no direct mapping for that, but what you can do is:

  • Place your cursor on the line you want to move.
  • Delete the line using: dd
  • Then go to the line right before where you want to place it.
  • Press p to past your deleted line.

That should do the trick.

Sander Vanhove
  • 995
  • 4
  • 11
2

I think that this is what you want

add this to your .vimrc

" Move lines up and down
nnoremap <C-Down> :m .+1<CR>==
nnoremap <C-Up> :m .-2<CR>==
inoremap <C-Down> <Esc>:m .+1<CR>==gi
inoremap <C-Up> <Esc>:m .-2<CR>==gi
vnoremap <C-Down> :m '>+1<CR>gv=gv
vnoremap <C-Up> :m '<-2<CR>gv=gv

source : https://vim.fandom.com/wiki/Moving_lines_up_or_down

Yohann
  • 98
  • 2
  • 6
0

Works for me after adding this in setting.json

   "vim.normalModeKeyBindingsNonRecursive": [
        {
            "before": ["ctrl+j"],
            "commands": ["editor.action.moveLinesDownAction"]
        },
        {
            "before": ["ctrl+k"],
            "commands": ["editor.action.moveLinesUpAction"]
        }
    ]
tzatalin
  • 404
  • 4
  • 7