How to move current line up or down in vim for vscode

Viewed 4450

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.

5 Answers

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.

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
],

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

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.

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"]
        }
    ]
Related