How do you invert the current selection?

If I have a document of 10 lines and I have a line selected.
How do I invert the selection so that instead, all the other lines are selected?

I searched and searched, could not find anything on this!

Any help would be appreciated.

Hey Louisa,

What you want is possible (with Javascript).

It seems important to you, so I made a feature…

**

HOW IT WORKS:

  1. click on the line you don’t want to copy
  2. Push “Control Y” (a new hotkey)

RESULT:

  • All lines above and below the active line are now copied to your clipboard. Spacing is preserved. Paste anywhere.

**

Here is an example, to show what it does:

1 - ORIGINAL TEXT (say you want to copy everything except “cut line”):

# header

good line
- list
  - list
good line
cut line
good line

2 - ACTION: (click on “cut line”, then hit “Control Y”)

3 - RESULT: COPIED TEXT (notice that “cut line” is gone)

# header

good line
- list
  - list
good line
good line

**

THE CODE - here is your code:

// copy all lines above and below active line
// hotkey => "control y"

document.onkeydown = function (e) {
  if (e.ctrlKey == true && e.key == "y") {
    // override default "control y" hotkey (if it exists)
    e.preventDefault(); 

    // get text (from lines above and below)
    var getInactiveLines = document.querySelectorAll(".cm-line:not(.cm-active)");

    // create the new string
    var newString = "";
    for (var i = 0; i < getInactiveLines.length; i++) {
      var lineText = getInactiveLines[i].innerText;

      // preserve blank lines
      if (lineText === "\n") {newString = newString + "\n";}

      // add text to the ultimate string
      else { newString = newString + "\n" + lineText;}
    }

    // remove zerowidthspaces
    var finalCopy = newString.replace(/\u200B/g, "");

    // copy text to your clipboard
    navigator.clipboard.writeText(finalCopy).then(
      function () {
        console.log("copied to clipboard");
      },
      function (err) {
        console.error("could not copy: ", err);
      }
    );
  }
};

**

And here is how to add that code to Obsidian:

  1. Add the plugin “Javascript Init” [Preferences > Community Plugins > Browse > Javascript Init]

  2. Open Preferences > Javascript Init (in left column)

  3. Now paste that code into the big box. Close Preferences.

  4. In the top menu, click View > Force Reload (this refreshes Obsidian)

DONE - Now “Control Y” will copy every line above and below the active line (the line with a flashing cursor).

**

NOTE: To keep any formatting in your “Control Y” copied text (like headers and lists), use Source Mode in your editor.

  • [Preferences > Editor > Default Editing Mode > Source Mode]

**

^ okay - that’s a long post, but it works.

(And you only have to set it up once).

Give it a try :butterfly:

If you have any questions, feel free to ask.

:tropical_fish:

1 Like