-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbookmarkCategoryEdit.go
More file actions
79 lines (76 loc) · 2.22 KB
/
bookmarkCategoryEdit.go
File metadata and controls
79 lines (76 loc) · 2.22 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
package gobookmarks
import (
"fmt"
"strings"
)
// ExtractCategoryByIndex returns the category text for the nth category (0 based)
func ExtractCategoryByIndex(bookmarks string, index int) (string, error) {
lines := strings.Split(bookmarks, "\n")
currentIndex := -1
start := -1
end := -1
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(strings.ToLower(trimmed), "category:") {
currentIndex++
if currentIndex == index {
start = i
for j := i + 1; j <= len(lines); j++ {
if j == len(lines) {
end = j
break
}
t := strings.TrimSpace(lines[j])
lower := strings.ToLower(t)
if strings.HasPrefix(lower, "category:") || strings.EqualFold(lower, "column") || strings.HasPrefix(lower, "page") || strings.HasPrefix(lower, "tab:") || strings.EqualFold(lower, "tab") || t == "--" {
end = j
break
}
}
break
}
}
}
if start == -1 || end == -1 {
return "", fmt.Errorf("category index %d not found", index)
}
return strings.Join(lines[start:end], "\n"), nil
}
// ReplaceCategoryByIndex replaces the nth category with newText
func ReplaceCategoryByIndex(bookmarks string, index int, newText string) (string, error) {
lines := strings.Split(bookmarks, "\n")
currentIndex := -1
start := -1
end := -1
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(strings.ToLower(trimmed), "category:") {
currentIndex++
if currentIndex == index {
start = i
for j := i + 1; j <= len(lines); j++ {
if j == len(lines) {
end = j
break
}
t := strings.TrimSpace(lines[j])
lower := strings.ToLower(t)
if strings.HasPrefix(lower, "category:") || strings.EqualFold(lower, "column") || strings.HasPrefix(lower, "page") || strings.HasPrefix(lower, "tab:") || strings.EqualFold(lower, "tab") || t == "--" {
end = j
break
}
}
break
}
}
}
if start == -1 || end == -1 {
return "", fmt.Errorf("category index %d not found", index)
}
var result []string
result = append(result, lines[:start]...)
newLines := strings.Split(newText, "\n")
result = append(result, newLines...)
result = append(result, lines[end:]...)
return strings.Join(result, "\n"), nil
}