63 lines
1.7 KiB
TypeScript
63 lines
1.7 KiB
TypeScript
import { App, Editor, EditorRange, EditorTransaction, MarkdownFileInfo, MarkdownView } from 'obsidian'
|
|
import BindThemPlugin from './main'
|
|
import { selectionToLine, selectionToRange } from './Utils'
|
|
|
|
/**
|
|
* SelectionHelper provides commands for manipulating text selections
|
|
*/
|
|
export class SelectionHelper {
|
|
public app: App
|
|
private plugin: BindThemPlugin
|
|
|
|
constructor(app: App, plugin: BindThemPlugin) {
|
|
this.app = app
|
|
this.plugin = plugin
|
|
}
|
|
|
|
/**
|
|
* Select the current line(s)
|
|
*/
|
|
public selectLine(editor: Editor, view: MarkdownView | MarkdownFileInfo): void {
|
|
const selections = editor.listSelections()
|
|
|
|
const newSelectionRanges: Array<EditorRange> = []
|
|
for (const selection of selections) {
|
|
const newSelection = selectionToLine(editor, selection)
|
|
newSelectionRanges.push(selectionToRange(newSelection))
|
|
}
|
|
|
|
const transaction: EditorTransaction = {
|
|
selections: newSelectionRanges,
|
|
}
|
|
|
|
editor.transaction(transaction, 'SelectionHelper_Line')
|
|
}
|
|
|
|
/**
|
|
* Select the current word(s)
|
|
*/
|
|
public selectWord(editor: Editor, view: MarkdownView | MarkdownFileInfo): void {
|
|
const selections = editor.listSelections()
|
|
|
|
const newSelections: Array<EditorRange> = []
|
|
for (const selection of selections) {
|
|
const range = selectionToRange(selection)
|
|
|
|
const wordStart = editor.wordAt(range.from)?.from ?? range.from
|
|
const wordEnd = editor.wordAt(range.to)?.to ?? range.from
|
|
|
|
const newSelection: EditorRange = {
|
|
from: { line: wordStart.line, ch: wordStart.ch },
|
|
to: { line: wordEnd.line, ch: wordEnd.ch },
|
|
}
|
|
|
|
newSelections.push(newSelection)
|
|
}
|
|
|
|
const transaction: EditorTransaction = {
|
|
selections: newSelections,
|
|
}
|
|
|
|
editor.transaction(transaction, 'SelectionHelper_Word')
|
|
}
|
|
} |