generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
utils.ts
346 lines (313 loc) · 8.73 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import {
Editor,
EditorPosition,
EditorSelection,
EditorSelectionOrCaret,
} from 'obsidian';
import { DIRECTION } from './constants';
import { CustomSelectionHandler } from './custom-selection-handlers';
type EditorActionCallback = (
editor: Editor,
selection: EditorSelection,
args: string,
) => EditorSelectionOrCaret;
type MultipleSelectionOptions = {
// Additional information to be passed to the EditorActionCallback
args?: string;
// Perform further processing of new selections before they are set
customSelectionHandler?: CustomSelectionHandler;
// Whether the action should be repeated for cursors on the same line
repeatSameLineActions?: boolean;
};
export const defaultMultipleSelectionOptions = { repeatSameLineActions: true };
export const withMultipleSelections = (
editor: Editor,
callback: EditorActionCallback,
options: MultipleSelectionOptions = defaultMultipleSelectionOptions,
) => {
// @ts-expect-error: Obsidian's Editor interface does not explicitly
// include the CodeMirror cm object, but it is there when using the
// legacy editor
const { cm } = editor;
const selections = editor.listSelections();
let selectionIndexesToProcess: number[];
let newSelections: EditorSelectionOrCaret[] = [];
if (!options.repeatSameLineActions) {
const seenLines: number[] = [];
selectionIndexesToProcess = selections.reduce(
(indexes, currSelection, currIndex) => {
const currentLine = currSelection.head.line;
if (!seenLines.includes(currentLine)) {
seenLines.push(currentLine);
indexes.push(currIndex);
}
return indexes;
},
[],
);
}
const applyCallbackOnSelections = () => {
for (let i = 0; i < selections.length; i++) {
// Controlled by repeatSameLineActions
if (selectionIndexesToProcess && !selectionIndexesToProcess.includes(i)) {
continue;
}
// Can't reuse selections variable as positions may change on each iteration
const selection = editor.listSelections()[i];
// Selections may disappear (e.g. running delete line for two cursors on the same line)
if (selection) {
const newSelection = callback(editor, selection, options.args);
newSelections.push(newSelection);
}
}
if (options.customSelectionHandler) {
newSelections = options.customSelectionHandler(newSelections);
}
editor.setSelections(newSelections);
};
if (cm && cm.operation) {
// Group all the updates into one atomic operation (so undo/redo work as expected)
cm.operation(applyCallbackOnSelections);
} else {
// Safe fallback if cm doesn't exist (so undo/redo will step through each change)
console.debug('cm object not found, operations will not be buffered');
applyCallbackOnSelections();
}
};
export const getLineStartPos = (line: number): EditorPosition => ({
line,
ch: 0,
});
export const getLineEndPos = (
line: number,
editor: Editor,
): EditorPosition => ({
line,
ch: editor.getLine(line).length,
});
export const getSelectionBoundaries = (selection: EditorSelection) => {
let { anchor: from, head: to } = selection;
// in case user selects upwards
if (from.line > to.line) {
[from, to] = [to, from];
}
// in case user selects backwards on the same line
if (from.line === to.line && from.ch > to.ch) {
[from, to] = [to, from];
}
return { from, to };
};
export const getLeadingWhitespace = (lineContent: string) => {
const indentation = lineContent.match(/^\s+/);
return indentation ? indentation[0] : '';
};
// Match any character from any language: https://www.regular-expressions.info/unicode.html
const isLetterCharacter = (char: string) => /\p{L}\p{M}*/u.test(char);
export const wordRangeAtPos = (
pos: EditorPosition,
lineContent: string,
): { anchor: EditorPosition; head: EditorPosition } => {
let start = pos.ch;
let end = pos.ch;
while (start > 0 && isLetterCharacter(lineContent.charAt(start - 1))) {
start--;
}
while (
end < lineContent.length &&
isLetterCharacter(lineContent.charAt(end))
) {
end++;
}
return {
anchor: {
line: pos.line,
ch: start,
},
head: {
line: pos.line,
ch: end,
},
};
};
export type CheckCharacter = (char: string) => boolean;
export const findPosOfNextCharacter = ({
editor,
startPos,
checkCharacter,
searchDirection,
}: {
editor: Editor;
startPos: EditorPosition;
checkCharacter: CheckCharacter;
searchDirection: DIRECTION;
}) => {
let { line, ch } = startPos;
let lineContent = editor.getLine(line);
let matchFound = false;
let matchedChar: string;
if (searchDirection === DIRECTION.BACKWARD) {
while (line >= 0) {
// ch will initially be 0 if searching from start of line
const char = lineContent.charAt(Math.max(ch - 1, 0));
matchFound = checkCharacter(char);
if (matchFound) {
matchedChar = char;
break;
}
ch--;
// inclusive because (ch - 1) means the first character will already
// have been checked
if (ch <= 0) {
line--;
if (line >= 0) {
lineContent = editor.getLine(line);
ch = lineContent.length;
}
}
}
} else {
while (line < editor.lineCount()) {
const char = lineContent.charAt(ch);
matchFound = checkCharacter(char);
if (matchFound) {
matchedChar = char;
break;
}
ch++;
if (ch >= lineContent.length) {
line++;
lineContent = editor.getLine(line);
ch = 0;
}
}
}
return matchFound
? {
match: matchedChar,
pos: {
line,
ch,
},
}
: null;
};
export const hasSameSelectionContent = (
editor: Editor,
selections: EditorSelection[],
) =>
new Set(
selections.map((selection) => {
const { from, to } = getSelectionBoundaries(selection);
return editor.getRange(from, to);
}),
).size === 1;
export const getSearchText = ({
editor,
allSelections,
autoExpand,
}: {
editor: Editor;
allSelections: EditorSelection[];
autoExpand: boolean;
}) => {
// Don't search if multiple selection contents are not identical
const singleSearchText = hasSameSelectionContent(editor, allSelections);
const firstSelection = allSelections[0];
const { from, to } = getSelectionBoundaries(firstSelection);
let searchText = editor.getRange(from, to);
if (searchText.length === 0 && autoExpand) {
const wordRange = wordRangeAtPos(from, editor.getLine(from.line));
searchText = editor.getRange(wordRange.anchor, wordRange.head);
}
return {
searchText,
singleSearchText,
};
};
export const findAllMatches = ({
searchText,
searchWithinWords,
documentContent,
}: {
searchText: string;
searchWithinWords: boolean;
documentContent: string;
}) => {
const searchExpression = new RegExp(
searchWithinWords ? searchText : `\\b${searchText}\\b`,
'g',
);
return Array.from(documentContent.matchAll(searchExpression));
};
export const findNextMatchPosition = ({
editor,
latestMatchPos,
searchText,
searchWithinWords,
documentContent,
}: {
editor: Editor;
latestMatchPos: EditorPosition;
searchText: string;
searchWithinWords: boolean;
documentContent: string;
}) => {
const latestMatchOffset = editor.posToOffset(latestMatchPos);
const matches = findAllMatches({
searchText,
searchWithinWords,
documentContent,
});
let nextMatch: EditorSelection | null = null;
for (const match of matches) {
if (match.index > latestMatchOffset) {
nextMatch = {
anchor: editor.offsetToPos(match.index),
head: editor.offsetToPos(match.index + searchText.length),
};
break;
}
}
// Circle back to search from the top
if (!nextMatch) {
const selectionIndexes = editor.listSelections().map((selection) => {
const { from } = getSelectionBoundaries(selection);
return editor.posToOffset(from);
});
for (const match of matches) {
if (!selectionIndexes.includes(match.index)) {
nextMatch = {
anchor: editor.offsetToPos(match.index),
head: editor.offsetToPos(match.index + searchText.length),
};
break;
}
}
}
return nextMatch;
};
export const findAllMatchPositions = ({
editor,
searchText,
searchWithinWords,
documentContent,
}: {
editor: Editor;
searchText: string;
searchWithinWords: boolean;
documentContent: string;
}) => {
const matches = findAllMatches({
searchText,
searchWithinWords,
documentContent,
});
const matchPositions = [];
for (const match of matches) {
matchPositions.push({
anchor: editor.offsetToPos(match.index),
head: editor.offsetToPos(match.index + searchText.length),
});
}
return matchPositions;
};