forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.ts
More file actions
193 lines (170 loc) · 5.46 KB
/
Copy pathformat.ts
File metadata and controls
193 lines (170 loc) · 5.46 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
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
import type { EditorView } from '@codemirror/view'
import { redo, undo } from '@codemirror/commands'
interface ToggleFormatOptions {
prefix: string
suffix: string
check?: (selected: string) => boolean
afterInsertCursorOffset?: number
}
/**
* 切换格式(加粗、斜体、删除线等)
*/
export function toggleFormat(
view: EditorView,
{
prefix,
suffix,
check,
afterInsertCursorOffset = 0,
}: ToggleFormatOptions,
): void {
const selection = view.state.selection.main
const selected = view.state.doc.sliceString(selection.from, selection.to)
const isFormatted = check?.(selected) ?? false
let newText: string
if (isFormatted) {
// Remove formatting (e.g. **abc** -> abc)
newText = selected.slice(prefix.length, selected.length - suffix.length)
view.dispatch(view.state.replaceSelection(newText))
}
else {
// Apply formatting
newText = `${prefix}${selected}${suffix}`
view.dispatch(view.state.replaceSelection(newText))
// Optional cursor shift (e.g. for `]()` links)
if (afterInsertCursorOffset !== 0) {
const newSelection = view.state.selection.main
const newPos = newSelection.head + afterInsertCursorOffset
view.dispatch({ selection: { anchor: newPos } })
}
}
}
/**
* 应用标题级别
*/
export function applyHeading(view: EditorView, level: number) {
const ranges = view.state.selection.ranges
const changes: Array<{ from: number, to: number, insert: string }> = []
const headingPrefix = `${`#`.repeat(level)} `
ranges.forEach((range) => {
const fromLine = view.state.doc.lineAt(range.from)
const toLine = view.state.doc.lineAt(range.to)
for (let lineNum = fromLine.number; lineNum <= toLine.number; lineNum++) {
const line = view.state.doc.line(lineNum)
const text = view.state.doc.sliceString(line.from, line.to)
// 去掉已有的 # 前缀(1~6 个)+ 空格
const cleaned = text.replace(/^#{1,6}\s+/, ``).trimStart()
const heading = headingPrefix + cleaned
changes.push({
from: line.from,
to: line.to,
insert: heading,
})
}
})
if (changes.length > 0) {
const firstLine = view.state.doc.lineAt(ranges[0].from)
// 计算光标应该在的位置:行首 + 标题前缀长度(如 "# " = 2)
const newCursorPos = firstLine.from + headingPrefix.length
view.dispatch({
changes,
selection: { anchor: newCursorPos },
})
}
}
/**
* 便捷格式化函数
*/
export function formatBold(view: EditorView) {
toggleFormat(view, {
prefix: `**`,
suffix: `**`,
check: s => s.startsWith(`**`) && s.endsWith(`**`),
afterInsertCursorOffset: -2,
})
}
export function formatItalic(view: EditorView) {
toggleFormat(view, {
prefix: `*`,
suffix: `*`,
check: s => s.startsWith(`*`) && s.endsWith(`*`),
afterInsertCursorOffset: -1,
})
}
export function formatStrikethrough(view: EditorView) {
toggleFormat(view, {
prefix: `~~`,
suffix: `~~`,
check: s => s.startsWith(`~~`) && s.endsWith(`~~`),
afterInsertCursorOffset: -2,
})
}
export function formatLink(view: EditorView) {
toggleFormat(view, {
prefix: `[`,
suffix: `]()`,
check: s => s.startsWith(`[`) && s.endsWith(`]()`),
afterInsertCursorOffset: -1,
})
}
export function formatCode(view: EditorView) {
toggleFormat(view, {
prefix: `\``,
suffix: `\``,
check: s => s.startsWith(`\``) && s.endsWith(`\``),
afterInsertCursorOffset: -1,
})
}
/**
* 设置文字颜色
*/
export function formatColor(view: EditorView, color: string) {
const selection = view.state.selection.main
const selected = view.state.doc.sliceString(selection.from, selection.to)
const spanRegex = /^\s*<span\s+style="color:\s*([^"\s][^"]*)"\s*>([\s\S]*)<\/span>\s*$/i
const match = selected.match(spanRegex)
if (match) {
const content = match[2]
const insert = `<span style="color: ${color}">${content}</span>`
view.dispatch({
changes: { from: selection.from, to: selection.to, insert },
selection: { anchor: selection.from, head: selection.from + insert.length },
})
}
else {
const insert = `<span style="color: ${color}">${selected}</span>`
view.dispatch({
changes: { from: selection.from, to: selection.to, insert },
selection: { anchor: selection.from, head: selection.from + insert.length },
})
}
}
export function formatUnorderedList(view: EditorView) {
const selection = view.state.selection.main
const selected = view.state.doc.sliceString(selection.from, selection.to)
const lines = selected.split(`\n`)
const isList = lines.every(line => line.trim().startsWith(`- `))
const updated = isList
? lines.map(line => line.replace(/^- +/, ``)).join(`\n`)
: lines.map(line => `- ${line}`).join(`\n`)
view.dispatch(view.state.replaceSelection(updated))
}
export function formatOrderedList(view: EditorView) {
const selection = view.state.selection.main
const selected = view.state.doc.sliceString(selection.from, selection.to)
const lines = selected.split(`\n`)
const isList = lines.every(line => /^\d+\.\s/.test(line.trim()))
const updated = isList
? lines.map(line => line.replace(/^\d+\.\s+/, ``)).join(`\n`)
: lines.map((line, i) => `${i + 1}. ${line}`).join(`\n`)
view.dispatch(view.state.replaceSelection(updated))
}
/**
* 撤销/重做
*/
export function undoAction(view: EditorView): boolean {
return undo(view)
}
export function redoAction(view: EditorView): boolean {
return redo(view)
}