forked from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path2debugmain.ts
267 lines (224 loc) · 11.7 KB
/
2debugmain.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
import { Plugin, setIcon } from "obsidian";
import { RangeSetBuilder } from "@codemirror/rangeset";
import { EditorView, Decoration, DecorationSet, ViewUpdate, WidgetType, ViewPlugin } from "@codemirror/view";
import { EditorState, EditorSelection, TransactionSpec, Transaction } from "@codemirror/state";
import { syntaxTree, foldable } from "@codemirror/language";
import { tokenClassNodeProp } from "@codemirror/stream-parser";
import { foldEffect, unfoldEffect, foldedRanges } from "@codemirror/fold";
export default class AttributesPlugin extends Plugin {
async onload() {
const ext = this.buildAttributesViewPlugin();
this.registerEditorExtension(ext);
}
buildAttributesViewPlugin() {
// build the DOM element that we'll prepend to list elements
class FoldWidget extends WidgetType {
isFolded: boolean;
isHeader: boolean;
constructor(isFolded: boolean, isHeader: boolean = false) {
super();
this.isFolded = isFolded;
this.isHeader = isHeader;
}
eq(other: FoldWidget) {
return other.isFolded == this.isFolded;
}
toDOM() {
let el = document.createElement("div");
el.className = "cm-fold-widget collapse-indicator collapse-icon";
if (this.isFolded) el.addClass("is-collapsed");
this.isHeader ? el.addClass("heading-collapse-indicator") : el.addClass("list-collapse-indicator");
setIcon(el, "right-triangle", 8);
return el;
}
ignoreEvent() {
return false;
}
}
const viewPlugin = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
lineCache: {}; // TODO: Implement caching
tokenCache: {}; // TODO: Implement caching
constructor(view: EditorView) {
this.decorations = this.buildDecorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged) {
this.decorations = this.buildDecorations(update.view);
} else if (update.geometryChanged) {
// this logic is to update the fold widget icons since a fold
// does not trigger docChanged or viewportChanged
// there's probably a better way to do this
for (let tr of update.transactions) {
for (let effect of tr.effects) {
if (effect && effect.value) {
if (effect.is(foldEffect) || effect.is(unfoldEffect)) {
this.decorations = this.buildDecorations(update.view);
}
}
}
}
}
// console.timeEnd("build deco");
}
destroy() {}
buildDecorations(view: EditorView) {
const hashTagRegexp = /#(?:[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s])+/g;
let builder = new RangeSetBuilder<Decoration>();
// use view.visibleRanges rather than view.viewPort since visibleRanges will filter out folded and non visible ranges
for (let { from, to } of view.visibleRanges) {
try {
// syntaxTree gives us access to the tokens generated by the markdown parser
// here we iterate over the visible text and evaluate each token, sequentially.
const tree = syntaxTree(view.state);
tree.iterate({
from,
to,
enter: (type, from, to) => {
// To access the parsed tokens, we need to use a NodeProp.
// Obsidian exports their inline token NodeProp, tokenClassNodeProp, as part of their
// custom stream-parser package. See the readme for more details.
const tokenProps = type.prop(tokenClassNodeProp);
if (tokenProps) {
const props = new Set(tokenProps.split(" "));
const isTag = props.has("hashtag-end");
const isList = props.has("formatting-list");
const isHeader = props.has("formatting-header");
const isBarelink = props.has("hmd-barelink") && !props.has("formatting");
const htmllink=props.has("hmd-html-begin");
if(htmllink){
let mline = view.state.doc.lineAt(from);
console.log("==S====",view.state.doc,"===E===")
//mline.text.contains("")
let tline=mline.text.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, "$1");
//console.log(mline.text.match(/<img.*?>/g)?.join(" "))
// let deco = Decoration.line({
// attributes: { "data-tags": mline.text.replace("build_blog/image-20181112002650646.png", "app://local/D:/git/blog_source/_posts/build_blog/image-20181112002650646.png") },
// });
// let deco = Decoration.replace({
// attributes: { src: "app://local/D:/git/blog_source/_posts/build_blog/image-20181112002650646.png" },
// });
let deco =Decoration.mark({attributes:{style:'color: red;'}});
// let deco = Decoration.line({
// attributes: { "src": "dsafasdf" },
// });
console.log(deco)
builder.add(mline.from, mline.from, deco);
// console.log("====="+mline.text);
}
// if (htmllink) {
// let line = view.state.doc.lineAt(from);
// let deco = Decoration.line({
// attributes: { "data-tags": line.text.match("image-20181112002650646")?.join(" ").replace(/#/g, "") },
// });
// // TODO: Figure out a better way to fix the pos conflict when
// // a top level list item has a hashtag at the beginning of the line
// // The code below is a hack using internal class properties
// if ((<any>builder).lastFrom == line.from) {
// // if we don't do this, we get an error stating our rangeset is not sorted
// deco.startSide = (<any>builder).last.startSide + 1;
// }
// builder.add(line.from, line.from, deco);
// }
if (isList || isHeader) {
// add a fold icon, inline, next to every foldable list item
// TODO: fix the naive negative margin in styles.css
let range,
line = view.state.doc.lineAt(from);
//console.log("----"+line.text);
if ((range = foldable(view.state, line.from, line.to))) {
const isFolded = foldExists(view.state, range.from, range.to);
let deco = Decoration.widget({
widget: new FoldWidget(isFolded, isHeader),
});
builder.add(from, from, deco);
}
}
if (isTag) {
// This adds a data-tags attribute to the parent cm-line.
// The attribute value will be a list of all tags found on the line
// TODO: this currently recomputes the entire list of hashtags for a given
// line once for every hashtag found. it works but it could be better.
let line = view.state.doc.lineAt(from);
let deco = Decoration.line({
attributes: { "data-tags": line.text.match(hashTagRegexp)?.join(" ").replace(/#/g, "") },
});
// TODO: Figure out a better way to fix the pos conflict when
// a top level list item has a hashtag at the beginning of the line
// The code below is a hack using internal class properties
if ((<any>builder).lastFrom == line.from) {
// if we don't do this, we get an error stating our rangeset is not sorted
deco.startSide = (<any>builder).last.startSide + 1;
}
builder.add(line.from, line.from, deco);
}
if (isBarelink) {
// add the value of barelinks as an href on the inline element
// this will cause a nested span to be created
let deco = Decoration.mark({
attributes: { href: view.state.doc.sliceString(from, to) },
});
builder.add(from, to, deco);
}
}
},
});
} catch (err) {
// cm6 will silently unload extensions when they crash
// this try/catch will provide details when crashes occur
console.error("Custom CM6 view plugin failure", err);
// make to to throw because if you don't, you'll block
// the auto unload and destabilize the editor
throw err;
}
}
return builder.finish();
}
},
{
decorations: v => v.decorations,
eventHandlers: {
// create an event handler for our new fold widget
mousedown: (e, view) => {
// TODO: only act on left click
let target = (e.target as HTMLElement).closest(".cm-fold-widget");
if (target) {
const foldMarkerPos = view.posAtDOM(target);
const line = view.state.doc.lineAt(foldMarkerPos);
let range = foldable(view.state, line.from, line.to);
if (range) {
let curPos = view.state.selection.main.head;
let effect = foldExists(view.state, range.from, range.to) ? unfoldEffect : foldEffect;
let transaction: TransactionSpec = { effects: [effect.of(range), announceFold(view, range)] };
if (curPos > range.from && curPos < range.to) {
transaction.selection = EditorSelection.cursor(range.to);
}
view.dispatch(transaction);
return true;
}
}
},
},
}
);
return viewPlugin;
}
}
function foldExists(state: EditorState, from: number, to: number) {
// adapted from https://github.com/codemirror/fold/blob/36ca2ec57aa3907fb0d1c13669b51e98e379e583/src/fold.ts#L76
const folded = foldedRanges(state);
let found = false;
folded.between(from, from, (a, b) => {
if (a == from && b == to) found = true;
});
return found;
}
function announceFold(view: EditorView, range: { from: number; to: number }, fold = true) {
// copied from https://github.com/codemirror/fold/blob/36ca2ec57aa3907fb0d1c13669b51e98e379e583/src/fold.ts#L110
let lineFrom = view.state.doc.lineAt(range.from).number,
lineTo = view.state.doc.lineAt(range.to).number;
return EditorView.announce.of(
`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`
);
}