-
Notifications
You must be signed in to change notification settings - Fork 13
/
exEditor.ts
98 lines (89 loc) · 2.17 KB
/
exEditor.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
import { Editor, EditorPosition } from 'obsidian';
import { REGEX } from './constants';
interface WordBoundary {
start: { line: number; ch: number };
end: { line: number; ch: number };
}
export interface Selected {
can: boolean;
text: string;
boundary: WordBoundary;
}
export class ExEditor {
public static getSelectedText(editor: Editor, debug: boolean): Selected {
if (debug) {
console.log(
`Link Embed: editor.somethingSelected() ${editor.somethingSelected()}`,
);
}
let cursor = editor.getCursor();
let wordBoundary: WordBoundary = {
start: cursor,
end: cursor,
};
if (!editor.somethingSelected()) {
wordBoundary = this.getWordBoundaries(editor, debug);
editor.setSelection(wordBoundary.start, wordBoundary.end);
}
if (editor.somethingSelected()) {
return {
can: true,
text: editor.getSelection(),
boundary: {
start: editor.getCursor('from'),
end: editor.getCursor('to'),
},
};
}
return {
can: false,
text: editor.getSelection(),
boundary: wordBoundary,
};
}
private static cursorWithinBoundaries(
cursor: EditorPosition,
match: RegExpMatchArray,
debug: boolean,
): boolean {
let startIndex = match.index;
let endIndex = match.index + match[0].length;
if (debug) {
console.log(
`Link Embed: cursorWithinBoundaries ${startIndex}, ${cursor.ch}, ${endIndex}`,
);
}
return startIndex <= cursor.ch && cursor.ch <= endIndex;
}
private static getWordBoundaries(
editor: Editor,
debug: boolean,
): WordBoundary {
let cursor = editor.getCursor();
let lineText = editor.getLine(cursor.line);
const urlRegex = new RegExp(REGEX.URL, 'g');
// Check if we're in a link
let linksInLine = lineText.matchAll(urlRegex);
if (debug) {
console.log('Link Embed: cursor', cursor, 'lineText', lineText);
}
for (let match of linksInLine) {
if (debug) {
console.log('Link Embed: match', match);
}
if (this.cursorWithinBoundaries(cursor, match, debug)) {
return {
start: { line: cursor.line, ch: match.index },
end: {
line: cursor.line,
ch: match.index + match[0].length,
},
};
}
}
return {
start: cursor,
end: cursor,
};
}
}