forked from mrjackphil/obsidian-text-expand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.ts
92 lines (75 loc) · 2.43 KB
/
helpers.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
export interface ExpanderQuery {
start: number
end: number
template: string
query: string
}
export function formatContent(content: string): string[] {
return content.split('\n')
}
export function getAllExpandersQuery(content: string[]): ExpanderQuery[] {
let accum: ExpanderQuery[] = []
for (var i = 0; i < content.length; i++) {
const line = content[i]
if (line === '```expander') {
for (var e = 0; e < content.length - i; e++) {
const nextline = content[i + e]
if (nextline === '```') {
accum.push(
{
start: i,
end: i + e,
query: content[i + 1],
template: e > 2 ? content.slice(i + 2, i + e).join('\n') : ''
}
)
break
}
}
}
}
return accum
}
export function getClosestQuery(queries: ExpanderQuery[], lineNumber: number): ExpanderQuery | undefined {
if (queries.length === 0) {
return undefined
}
return queries.reduce((a, b) => {
return Math.abs(b.start - lineNumber) < Math.abs(a.start - lineNumber) ? b : a;
});
}
export function getLastLineToReplace(content: string[], query: ExpanderQuery, endline: string) {
const lineFrom = query.end
for (var i = lineFrom + 1; i < content.length; i++) {
if (content[i] === endline) {
return i
}
}
return lineFrom + 1
}
export function trimContent(s: string) {
const removeEmptyLines = (s: string): string => {
const lines = s.split('\n').map(e => e.trim())
if (lines.length < 2) {
return s
}
if (lines.indexOf('') === 0) {
return removeEmptyLines(lines.slice(1).join('\n'))
}
return s
}
const removeFrontMatter = (s: string, lookEnding: boolean = false): string => {
const lines = s.split('\n')
if (lookEnding && lines.indexOf('---') === 0) {
return lines.slice(1).join('\n')
}
if (lookEnding) {
return removeFrontMatter(lines.slice(1).join('\n'), true)
}
if (lines.indexOf('---') === 0) {
return removeFrontMatter(lines.slice(1).join('\n'), true)
}
return s
}
return removeFrontMatter(removeEmptyLines(s))
}