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

5

10

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.

Flapjack answered 29/2, 2020 at 9:36 Comment(0)
P
8

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
],
Pederasty answered 20/7, 2021 at 3:12 Comment(1)
To use Control key instead of Shift use "<C-j>" "<C-k>" instead of "J", "K" For me that is default vim behavior.Semester
E
5

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.

Escalate answered 17/8, 2020 at 4:44 Comment(0)
S
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.

Scumble answered 29/2, 2020 at 10:51 Comment(1)
I was afraid this was going to have to be the solution. Thanks for the response :)Flapjack
S
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

Stanfordstang answered 29/2, 2020 at 18:28 Comment(0)
D
1

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"]
        }
    ]
Damselfish answered 16/9, 2021 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.