DEV Community

Cover image for Multi-cursor moves that replace a regex
JSLab
JSLab

Posted on

Multi-cursor moves that replace a regex

You paste ten lines from a spreadsheet and need them as a JavaScript array. You could write a regex. Or you could edit all ten lines at once, which is faster and you can see it working.

Every Monaco-based editor (VS Code included) has these. The shortcuts below are JSLab's; your editor's may differ, and its command palette will tell you.

Move 1: a pasted column into an array

You paste this:

Ada Lovelace
Alan Turing
Grace Hopper
Katherine Johnson
Enter fullscreen mode Exit fullscreen mode
  1. Select all four lines.
  2. Split Selection into Lines (⇧⌘L): now there's a cursor at the end of each line.
  3. Press Home: every cursor jumps to the start of its line. Type ".
  4. Press End: type ",.
"Ada Lovelace",
"Alan Turing",
"Grace Hopper",
"Katherine Johnson",
Enter fullscreen mode Exit fullscreen mode

Wrap it in const names = [ … ]; and you're done. Four lines or four hundred, it's the same four steps.

Move 2: rename by selecting the next match

const items = [4, 10, 25];
const price = items.map((price) => price * 1.2);
price;
Enter fullscreen mode Exit fullscreen mode

Put the caret in price and press ⌘D (Select Next Occurrence) once for each match you want. Type cost, and they all change.

Unlike find and replace, you see each match get picked, and you can stop before the one you don't want. Here, the arrow function's parameter is a different variable that happens to share the name. ⌘D lets you include it or skip it on purpose.

Move 3: column cursors

Add Cursor Below (⌃⇧↓) stacks cursors straight down, one per line. Good for adding the same thing at the same column, like a key prefix:

const env = {
  URL: "https://api.example.com",
  PORT: "8080",
  REGION: "eu",
};
Enter fullscreen mode Exit fullscreen mode

Cursor before URL, ⌃⇧↓ twice, type API_, and all three keys get the prefix.

Two more worth knowing

  • Expand Selection (⇧⌘Space) grows the selection to the next enclosing thing: word, string, argument list, block. Faster than dragging.
  • Duplicate Line (⇧⌘D) and Move Line Up / Down (⌃⌘↑ / ⌃⌘↓) rearrange code without cut and paste.

If you think in Vim

JSLab, a JavaScript & TypeScript scratchpad for macOS, has Vim Keys in Settings → Editor, and ⌘R still runs your code in every mode, so you never have to leave Normal mode to see a result.

In a scratchpad, multi-cursor matters more than in a project: you're constantly reshaping pasted data into something you can run. With Auto Run on, the result updates as soon as you stop typing, so you see the array form as you edit.

Every one of these is a JSLab command, so you can rebind it in Settings → Keybindings or find it by name with ⇧⌘P.

JSLab launches Nov 15. Editing shortcuts: https://js-lab.app/docs/reference/keyboard-shortcuts

Top comments (0)