Skip to main content

Overview

The Editor class provides a common interface for interacting with the Obsidian editor, abstracting away the differences between CodeMirror 5 and CodeMirror 6. This interface allows plugins to manipulate text, selections, and editor state in a version-independent way.
Available since version 0.11.11

Properties

The Editor class exposes all methods through its instance and doesn’t have public properties that need to be accessed directly.

Methods

getDoc()

Returns the document instance (the Editor itself).
returns
Editor
Returns this editor instance
const doc = editor.getDoc();

refresh()

Refreshes the editor display.
editor.refresh();

getValue()

Gets the entire content of the editor.
returns
string
The complete text content of the editor
const content = editor.getValue();
console.log(content);

setValue()

Sets the entire content of the editor.
content
string
required
The new content to set in the editor
editor.setValue('# New Document\n\nThis is new content.');

getLine()

Gets the text at a specific line (0-indexed).
line
number
required
The line number (0-indexed)
returns
string
The text content of the specified line
const firstLine = editor.getLine(0);
const secondLine = editor.getLine(1);

setLine()

Sets the text at a specific line.
n
number
required
The line number (0-indexed)
text
string
required
The new text for the line
editor.setLine(0, '# Updated Heading');

lineCount()

Gets the total number of lines in the document.
returns
number
The number of lines in the document
const totalLines = editor.lineCount();
console.log(`Document has ${totalLines} lines`);

lastLine()

Gets the index of the last line in the document.
returns
number
The index of the last line (0-indexed)
const lastLineIndex = editor.lastLine();
const lastLineText = editor.getLine(lastLineIndex);

getSelection()

Gets the currently selected text.
returns
string
The selected text
const selectedText = editor.getSelection();
console.log('Selected:', selectedText);

somethingSelected()

Checks if there is any text currently selected.
returns
boolean
True if text is selected, false otherwise
if (editor.somethingSelected()) {
  console.log('Text is selected');
}

getRange()

Gets the text between two positions.
from
EditorPosition
required
The starting position
to
EditorPosition
required
The ending position
returns
string
The text between the two positions
const text = editor.getRange(
  { line: 0, ch: 0 },
  { line: 2, ch: 10 }
);

replaceSelection()

Replaces the currently selected text.
replacement
string
required
The text to replace the selection with
origin
string
Optional origin identifier for the change
editor.replaceSelection('**bold text**');

replaceRange()

Replaces text in a specific range.
replacement
string
required
The replacement text
from
EditorPosition
required
The starting position
to
EditorPosition
The ending position (optional)
origin
string
Optional origin identifier for the change
editor.replaceRange(
  'new text',
  { line: 0, ch: 0 },
  { line: 0, ch: 8 }
);

getCursor()

Gets the current cursor position.
side
'from' | 'to' | 'head' | 'anchor'
Which side of the selection to get (optional)
returns
EditorPosition
The cursor position
const cursor = editor.getCursor();
console.log(`Line: ${cursor.line}, Column: ${cursor.ch}`);

listSelections()

Gets all current selections.
returns
EditorSelection[]
Array of all current selections
const selections = editor.listSelections();
selections.forEach(sel => {
  console.log('Selection:', sel.anchor, sel.head);
});

setCursor()

Sets the cursor position.
pos
EditorPosition | number
required
The position to set the cursor to, or a line number
ch
number
The column number (if pos is a line number)
// Set cursor to line 5, column 10
editor.setCursor({ line: 5, ch: 10 });

// Alternative syntax
editor.setCursor(5, 10);

setSelection()

Sets a selection between two positions.
anchor
EditorPosition
required
The anchor position (start of selection)
head
EditorPosition
The head position (end of selection, optional)
editor.setSelection(
  { line: 0, ch: 0 },
  { line: 2, ch: 5 }
);

setSelections()

Sets multiple selections at once.
ranges
EditorSelectionOrCaret[]
required
Array of selection ranges
main
number
Index of the main selection (optional)
Available since version 0.12.11
editor.setSelections([
  { anchor: { line: 0, ch: 0 }, head: { line: 0, ch: 5 } },
  { anchor: { line: 2, ch: 0 }, head: { line: 2, ch: 8 } }
]);

focus()

Gives focus to the editor.
editor.focus();

blur()

Removes focus from the editor.
editor.blur();

hasFocus()

Checks if the editor currently has focus.
returns
boolean
True if the editor has focus
if (editor.hasFocus()) {
  console.log('Editor is focused');
}

getScrollInfo()

Gets the current scroll position.
returns
{ top: number, left: number }
Object containing scroll position
const scroll = editor.getScrollInfo();
console.log(`Scroll: ${scroll.top}, ${scroll.left}`);

scrollTo()

Scrolls the editor to a specific position.
x
number | null
Horizontal scroll position (null to keep current)
y
number | null
Vertical scroll position (null to keep current)
// Scroll to top
editor.scrollTo(null, 0);

// Scroll to specific position
editor.scrollTo(0, 100);

scrollIntoView()

Scrolls the editor to make a specific range visible.
range
EditorRange
required
The range to scroll into view
center
boolean
Whether to center the range in the viewport (optional)
Available since version 0.13.0
editor.scrollIntoView({
  from: { line: 10, ch: 0 },
  to: { line: 10, ch: 10 }
}, true);

undo()

Undoes the last change.
editor.undo();

redo()

Redoes the last undone change.
editor.redo();

exec()

Executes a built-in editor command.
command
EditorCommandName
required
The command to execute
Available since version 0.12.2
Available commands:
  • goUp, goDown, goLeft, goRight
  • goStart, goEnd
  • goWordLeft, goWordRight
  • indentMore, indentLess
  • newlineAndIndent
  • swapLineUp, swapLineDown
  • deleteLine
  • toggleFold, foldAll, unfoldAll
editor.exec('indentMore');
editor.exec('toggleFold');

transaction()

Executes a transaction containing multiple changes.
tx
EditorTransaction
required
The transaction to execute
origin
string
Optional origin identifier
Available since version 0.13.0
editor.transaction({
  changes: [
    { text: 'new text', from: { line: 0, ch: 0 } }
  ]
});

wordAt()

Gets the word at a specific position.
pos
EditorPosition
required
The position to check
returns
EditorRange | null
The range of the word, or null if no word found
const cursor = editor.getCursor();
const wordRange = editor.wordAt(cursor);
if (wordRange) {
  const word = editor.getRange(wordRange.from, wordRange.to);
  console.log('Current word:', word);
}

posToOffset()

Converts an EditorPosition to a character offset.
pos
EditorPosition
required
The position to convert
returns
number
The character offset
const offset = editor.posToOffset({ line: 2, ch: 5 });
console.log('Offset:', offset);

offsetToPos()

Converts a character offset to an EditorPosition.
offset
number
required
The character offset to convert
returns
EditorPosition
The corresponding position
const pos = editor.offsetToPos(100);
console.log(`Line: ${pos.line}, Column: ${pos.ch}`);

processLines()

Processes lines in the document, reading and optionally modifying them.
read
(line: number, lineText: string) => T | null
required
Function to read/analyze each line
write
(line: number, lineText: string, value: T | null) => EditorChange | void
required
Function to optionally modify lines based on read results
ignoreEmpty
boolean
Whether to skip empty lines (optional)
Available since version 0.13.26
// Example: Add line numbers to non-empty lines
editor.processLines(
  (line, text) => text.length > 0 ? line : null,
  (line, text, lineNum) => {
    if (lineNum !== null) {
      return {
        text: `${lineNum + 1}. ${text}`,
        from: { line, ch: 0 },
        to: { line, ch: text.length }
      };
    }
  },
  true
);

EditorPosition

Represents a position in the editor.
interface EditorPosition {
  line: number;  // 0-indexed line number
  ch: number;    // 0-indexed character position
}

EditorRange

Represents a range in the editor.
interface EditorRange {
  from: EditorPosition;
  to: EditorPosition;
}

EditorSelection

Represents a selection in the editor.
interface EditorSelection {
  anchor: EditorPosition;
  head: EditorPosition;
}

Examples

Getting the Active Editor

const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
  const editor = activeView.editor;
  // Use editor methods here
}

Inserting Text at Cursor

const cursor = editor.getCursor();
editor.replaceRange('Inserted text', cursor);

Wrapping Selected Text

if (editor.somethingSelected()) {
  const selection = editor.getSelection();
  editor.replaceSelection(`**${selection}**`);
}

Working with Multiple Lines

const lineCount = editor.lineCount();
for (let i = 0; i < lineCount; i++) {
  const lineText = editor.getLine(i);
  if (lineText.startsWith('TODO:')) {
    console.log(`Found TODO on line ${i}: ${lineText}`);
  }
}

Build docs developers (and LLMs) love