generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
86 lines (63 loc) · 2.57 KB
/
main.ts
File metadata and controls
86 lines (63 loc) · 2.57 KB
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
import { Editor, Plugin } from 'obsidian';
export default class TextProcessor extends Plugin {
statusBarTextElement: HTMLSpanElement;
async onload() {
console.log('Loaded plugin.');
this.statusBarTextElement = this.addStatusBarItem().createEl('span');
this.readActiveFileAndUpdateLineCount();
this.app.workspace.on('active-leaf-change', async () => { // this calls the enclosure when the active-leaf-change event is triggered
this.readActiveFileAndUpdateLineCount();
})
this.app.workspace.on('editor-change', editor => { // triggered when the editor is changed.
const content = editor.getDoc().getValue();
this.updateLineCount(content);
})
this.addCommand({
id: 'remove-line-breaks',
name: 'Remove Line Breaks',
editorCallback: (editor: Editor) => {
const selection = editor.getSelection();
const splitByParagraph = selection.split("\n")
let lineBreaksRemoved = "";
//console.log(splitByParagraph);
splitByParagraph.forEach((chunk, index) => {
const nextIndex = index + 1;
if (chunk !== "") { // Chunk contains text
if (index == 0) {
lineBreaksRemoved = chunk;
} else if (splitByParagraph[index-1] == "") {
lineBreaksRemoved = lineBreaksRemoved + chunk;
} else {
//TODO: check if the last character is a -, if it is, don't add a space.
lineBreaksRemoved = lineBreaksRemoved + " " + chunk;
}
} else { // Chunk does not contain text
if (index + 1 !== splitByParagraph.length && splitByParagraph[index+1] !== "") { // This is not the last chunk
lineBreaksRemoved = lineBreaksRemoved + "\n\n";
}
}
});
//const lineBreaksRemoved = selection.replace(/\n/g," ");
editor.replaceSelection(lineBreaksRemoved);
},
});
}
async onunload() {
console.log('Unloaded plugin.')
}
// -- FUNCTIONS --
private updateLineCount(fileContent?: string) {
const count = fileContent ? fileContent.split(/\r\n|\r|\n/).length : 0; // splits the file contents into an array using carriage returns and then counts the number of entities in the array
const linesWord = count === 1 ? "line" : "lines";
this.statusBarTextElement.textContent = `${count} ${linesWord}`;
}
private async readActiveFileAndUpdateLineCount() {
const file = this.app.workspace.getActiveFile();
if (file) {
const content = await this.app.vault.read(file); // this promises something, which means it accesses it asynchronously. This method thus needs to happen asynchronously.
this.updateLineCount(content);
} else {
this.updateLineCount(undefined);
}
}
}