SilentVoid13 / Templater

A template plugin for obsidian
https://silentvoid13.github.io/Templater
GNU Affero General Public License v3.0
3.2k stars 194 forks source link

Get current line #237

Open JeppeKlitgaard opened 3 years ago

JeppeKlitgaard commented 3 years ago

I would like to implement a "copy-line up/down" hotkey like the one I use in VSCode (CTRL + ALT + DOWN copies the current line(s) down).

It might be slightly niche, but perhaps Templater could implement an internal function to get the current line(s).

The signature would be something like:

tp.file.cursor_lines() -> [lines, start_char, stop_char]

Where:

Examples

image

would return: [["- Sweep voltage from positive to negative and find _stopping voltage_ where the current of electrons stops"], 4, 4]


image

would return: [["- Sweep voltage from positive to negative and find _stopping voltage_ where the current of electrons stops"], 4, 7]


image

would return:

[
    [
     "- Sweep voltage from positive to negative and find _stopping voltage_ where the current of electrons stops",
     "- Freeing an electron requires overcoming _the work function_"
    ],
    4, 3
]
JeppeKlitgaard commented 3 years ago

I realised that this can actually be done using the exposed Obsidian API, though this functionality would probably be nice to have directly in Templater nonetheless.

SilentVoid13 commented 3 years ago

Hey @JeppeKlitgaard that's a good idea, could you share what you already coded so I can understand your implementation better? From what I see getCursor only returns the EditorPosition, but not the full line of the cursor.

hiocean commented 3 years ago

Hey @JeppeKlitgaard that's a good idea, could you share what you already coded so I can understand your implementation better? From what I see getCursor only returns the EditorPosition, but not the full line of the cursor.

any update?

iwconfig commented 2 years ago

Pass getCursor().line to getLine to get the full text line at the cursor position.

Here's something I came up with

const doc = this.app.workspace.activeLeaf.view.sourceMode.cmEditor.doc
const cursorPos = doc.getCursor()
const lineText = doc.getLine(cursorPos.line).trim()
const regex = /^(?<pre>[-+*\d\.\s]*\[[x|\s]*\]\s*)(?<text>.*)$/i
const match = regex.exec(lineText)
if (match) {
    const ch = match.groups.pre.length
    doc.setCursor(cursorPos.line, ch)
}

if the current line starts with or similar to "- [ ] ", it sets the cursor position right after this substring.

      👇
- [x] │make pancakes
      👆
bloaryth commented 1 year ago

Note that cmdEditor is depreciated. So I came up with the following:

const editor = this.app.workspace.activeEditor.editor;
const line = editor.getCursor().line;
const input = editor.getLine(line).trim();
editor.setLine(line, "");