Joe Casadonte
Joe Casadonte

Reputation: 16859

How to move selected text vertically with keyboard in VS Code

I can move a whole line up or down with alt+up and alt+down, respectively. I can move selected text left or right with Move Caret Left or Move Caret Right, respectively (which are unbound by default, at least on the Mac). Is there a way to move selected text (not a whole line) up or down, using the keyboard?

Upvotes: 5

Views: 3566

Answers (1)

Mark
Mark

Reputation: 180785

Here is as best as I good get - you'll need to write an extension I think to improve on it - but it might work for you. Using a macro extension like multi-command

Settings.json:

"multiCommand.commands": [
  {
    "command": "multiCommand.moveCopyUp",
    "sequence": [
      "undo",
      "cursorUp",
      "editor.action.clipboardPasteAction",
    ]
  },
  {
    "command": "multiCommand.copyAndMoveSelectionUp",
    "sequence": [
      "editor.action.clipboardCutAction",        
      "cursorUp",
      "editor.action.clipboardPasteAction",
    ]
  },
  {
    "command": "multiCommand.copyAndMoveSelectionDown",
    "sequence": [
      "editor.action.clipboardCutAction",        
      "cursorWordStartLeftSelect",        
      "cursorDown",
      "editor.action.clipboardPasteAction",
    ]
  },
  {
    "command": "multiCommand.moveCopyDown",
    "sequence": [
      "undo",
      "cursorWordStartLeftSelect",        
      "cursorDown",
      "editor.action.clipboardPasteAction",
    ]
  }
]

And keybindings.json:

 {
  "key": "alt+u",
  "command": "multiCommand.moveCopyUp",
  "when": "!editorHasSelection && textInputFocus && !editorReadOnly"
},

{
  "key": "alt+u",
  "command": "multiCommand.copyAndMoveSelectionUp",
  "when": "editorHasSelection && textInputFocus && !editorReadOnly"
},

{
  "key": "alt+d",
  "command": "multiCommand.copyAndMoveSelectionDown",
  "when": "editorHasSelection && textInputFocus && !editorReadOnly"
},

{
  "key": "alt+d",
  "command": "multiCommand.moveCopyDown",
  "when": "!editorHasSelection && textInputFocus && !editorReadOnly"
},

or whatever keybindings you chose. This presumes you want to cut the selection you want to move (if not let me know and I may be able to modify this to suit leaving the initial instance of selected text where it was).

This does require that you have an actual selection before invoking a move up/down command. And that text will be cut to the clipboard and ultimately pasted into the line up/down. The moved text will move strictly straight up/down, not going to the next end of word for instance - although that could be added I think.

This will work with the move caret left/right commands if those are done first. Otherwise the selected range is lost when it is pasted - it could be stored in an extension though. Here is a demo (the demo gif unfortunately shows a line being skipped - it doesn't do that in reality) :

demo of moving selections

Upvotes: 3

Related Questions