generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown.ts
89 lines (77 loc) · 2.32 KB
/
markdown.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
export class Todo {
// e.g: ' - [x] hello'
// prefix: ' - [ '
// check: 'x'
// suffix: '] '
// body: hello
constructor(
public lineIndex: number,
private prefix: string,
public checked: boolean,
private suffix: string,
public body: string) { }
public toMarkdown(): string {
return `${this.prefix}${this.checked ? 'x' : ' '}${this.suffix}${this.body}`;
}
}
export type TodoEdit = {
checked?: boolean,
body?: string,
}
export class MarkdownDocument {
private static readonly todoRegexp = /^(?<prefix>\s*\- \[)(?<check>.)(?<suffix>\]\s+)(?<body>.*)$/;
private lines: Array<string>;
constructor(public file: string, content: string) {
this.lines = content.split("\n");
}
public getTodos(): Array<Todo> {
const todos: Array<Todo> = [];
this.lines.forEach((line, lineIndex) => {
const todo = this.parseTodo(lineIndex, line);
if (todo) {
todos.push(todo);
}
});
return todos;
}
public getTodo(lineIndex: number): Todo | null {
return this.parseTodo(lineIndex, this.lines[lineIndex]);
}
private parseTodo(lineIndex: number, line: string): Todo | null {
const match = MarkdownDocument.todoRegexp.exec(line);
if (match) {
return new Todo(
lineIndex,
match.groups.prefix,
match.groups.check === 'x',
match.groups.suffix,
match.groups.body);
}
return null;
}
public modifyTodo(lineIndex: number, edit: TodoEdit) {
const line = this.lines[lineIndex];
const todo = this.parseTodo(lineIndex, line);
if (todo === null) {
throw `Not a TODO line`;
}
if (edit.body !== undefined) {
todo.body = edit.body;
}
if (edit.checked !== undefined) {
todo.checked = edit.checked;
}
const newLine = todo.toMarkdown();
this.lines[lineIndex] = newLine;
console.info(
"Modify TODO: file=%s, index=%d, oldLine=%s, newLine=%s",
this.file,
lineIndex,
line,
newLine
);
}
public toMarkdown(): string {
return this.lines.join('\n');
}
}