-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
67 lines (59 loc) · 1.58 KB
/
main.js
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
// WordCountMd - A plugin to count the NON-MARKDOWN words of selected text in the editor.
'use strict';
var obsidian = require('obsidian');
var state = require('@codemirror/state');
var view = require('@codemirror/view');
class WordCountMd extends obsidian.Plugin
{
onload()
{
WordCountMd .statusBar = this.addStatusBarItem();
this.createCMExtension();
}
createCMExtension()
{
const cmStateField = state.StateField.define(
{
create(state)
{
return view.Decoration.none;
},
update(effects, tr)
{
let text = "";
const selection = tr.newSelection.main;
if (selection.empty)
{
const textIter = tr.newDoc.iter();
while (!textIter.done)
{
text = text + textIter.next().value;
}
}
else
{
const textIter = tr.newDoc.iterRange(selection.from, selection.to);
while (!textIter.done)
{
text = text + textIter.next().value;
}
}
WordCountMd.updateStatusBar(text);
return effects;
},
provide: (f) => view.EditorView.decorations.from(f),
});
this.registerEditorExtension(cmStateField);
}
// word separators - space/tab, forward-slash, comma
static REGEX_SEPARATORS = "\\s\\/,";
// word - 0 or more non-separators, an alphanumeric, 0 or more non-separators
static REGEX_WORDS = new RegExp(`[^${this.REGEX_SEPARATORS}]*[a-zA-Z0-9][^${this.REGEX_SEPARATORS}]*`, "g");
static updateStatusBar(text)
{
const words = text?.match(this.REGEX_WORDS)?.length || 0;
const chars = text.length;
this.statusBar.setText(`${words} words ${chars} characters`);
}
}
module.exports = WordCountMd;