-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.go
More file actions
550 lines (479 loc) · 13 KB
/
common.go
File metadata and controls
550 lines (479 loc) · 13 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package main
import (
"database/sql"
"fmt"
"os"
"regexp"
"strings"
"time"
)
type Location int
const (
BL Location = iota //Bottom Left
BR
TL
TR
)
type Position struct {
rowNum int
start int
end int
}
/*
type Window interface {
drawText()
drawFrame()
drawStatusBar()
}
*/
// dbConfig holds application configuration loaded from config.json.
// Sensitive credentials can be overridden via environment variables:
// - VIMANGO_PG_PASSWORD: overrides postgres.password
// - VIMANGO_PG_SSL_MODE: overrides postgres.ssl_mode (disable, require, verify-ca, verify-full)
// - VIMANGO_PG_SSL_CA_CERT: overrides postgres.ssl_ca_cert (path to CA certificate)
// - VIMANGO_CLAUDE_API_KEY: overrides claude.api_key
type dbConfig struct {
Postgres struct {
Host string `json:"host"`
Port string `json:"port"`
User string `json:"user"`
Password string `json:"password"` // Can be overridden by VIMANGO_PG_PASSWORD env var
DB string `json:"db"`
Test string `json:"test"`
SSLMode string `json:"ssl_mode"` // disable, require, verify-ca, verify-full (overridden by VIMANGO_PG_SSL_MODE)
SSLCACert string `json:"ssl_ca_cert"` // Path to CA certificate (overridden by VIMANGO_PG_SSL_CA_CERT)
} `json:"postgres"`
Sqlite3 struct {
DB string `json:"db"`
FTS_DB string `json:"fts_db"`
} `json:"sqlite3"`
Options struct {
Type string `json:"type"`
Title string `json:"title"`
} `json:"options"`
Chroma struct {
Style string `json:"style"`
} `json:"chroma"`
Claude struct {
ApiKey string `json:"api_key"` // Can be overridden by VIMANGO_CLAUDE_API_KEY env var
} `json:"claude"`
Glamour struct {
Style string `json:"style"`
} `json:"glamour"`
}
// Preferences holds user UI preferences that persist across sessions
type Preferences struct {
ImageScale int `json:"image_scale"` // Image width in columns (10-100)
EdPct int `json:"ed_pct"` // Editor percentage (1-99)
ImageCacheMaxWidth int `json:"image_cache_max_width"` // Max pixel width for cached images (default 800)
}
// validateGlamourStyle checks if a glamour style file exists and returns an error if not.
// This should be called at application startup.
func validateGlamourStyle() error {
// Try config value first
if app.Config != nil && app.Config.Glamour.Style != "" {
if _, err := os.Stat(app.Config.Glamour.Style); err == nil {
return nil // Found configured style
}
}
// Try default.json
if _, err := os.Stat("default.json"); err == nil {
return nil // Found default style
}
// Neither file exists
configuredStyle := "not specified"
if app.Config != nil && app.Config.Glamour.Style != "" {
configuredStyle = app.Config.Glamour.Style
}
return fmt.Errorf("glamour style files not found:\n Configured style: %s\n Fallback style: default.json\nPlease ensure at least one of these files exists", configuredStyle)
}
// getGlamourStylePath returns the path to the glamour style file with fallback logic:
// 1. Try configured style from config.json
// 2. Try default.json
// This function assumes validateGlamourStyle() has already been called at startup.
func getGlamourStylePath() string {
// Try config value first
if app.Config != nil && app.Config.Glamour.Style != "" {
if _, err := os.Stat(app.Config.Glamour.Style); err == nil {
return app.Config.Glamour.Style
}
}
// Try default.json
if _, err := os.Stat("default.json"); err == nil {
return "default.json"
}
// This should not happen if validateGlamourStyle() was called at startup
// Return empty string as last resort
return ""
}
var z0 = struct{}{}
var Languages = map[string]string{
"golang": "go",
"go": "go",
"cpp": "cpp",
"c++": "cpp",
"python": "python",
}
var sortColumns = map[string]struct{}{
"added": z0,
"modified": z0,
"priority": z0,
}
var termcodes = map[int]string{
ARROW_UP: "<up>",
ARROW_DOWN: "<down>",
ARROW_RIGHT: "<right>",
ARROW_LEFT: "<left>",
BACKSPACE: "<bs>", //? also works "\x08"
HOME_KEY: "<home>",
DEL_KEY: "<del>",
PAGE_UP: "<pageup>",
PAGE_DOWN: "<pagedown>",
}
var Lsps = map[string]string{
"go": "gopls",
"cpp": "clangd",
"py": "python-language-server",
}
type Mode int
const (
NORMAL Mode = iota // just seeing this after an escape
NORMAL_BUSY // Replace and almost any other keystroke in normal
INSERT
COMMAND_LINE // only in organizer mode
EX_COMMAND // only in editor mode
VISUAL_LINE // only editor mode
VISUAL
VISUAL_BLOCK // only editor mode
SEARCH // only editor mode
//FIND // only organizer mode
PREVIEW // only editor mode - for previewing markdown
VIEW_LOG // only in editor mode - for debug viewing of vim message hx
SPELLING // this mode recognizes 'z='
NAVIGATE_NOTICE // only in organizer mode
HELP // organizer and editor mode
CONTAINER // overlay for choosing folder/context
LINKS // only in organizer mode
PENDING
OTHER // Just in case
)
var modeMap = map[int]Mode{
1: NORMAL, // seems to be only after an escape
2: VISUAL, //VISUAL_MODE,
4: PENDING,
8: SEARCH, // Also COMMAND
16: INSERT,
257: NORMAL_BUSY, // just about any keystroke when in NORMAL mode
}
// v -> 118; V -> 86; ctrl-v -> 22
var visualModeMap = map[int]Mode{
22: VISUAL_BLOCK,
86: VISUAL_LINE,
118: VISUAL,
}
const (
TZ_OFFSET = 4
LINKED_NOTE_HEIGHT = 20
TOP_MARGIN = 1
MAX = 500
TIME_COL_WIDTH = 18
IMAGE_MARKER_WIDTH = 2
IMAGE_MARKER_AGE_GAP = 1
LEFT_MARGIN = 1
LEFT_MARGIN_OFFSET = 4
BASE_DATE string = "1970-01-01 00:00"
RESET string = "\x1b[0m"
BOLD string = "\x1b[1m"
// IMAGE_MARKER_SYMBOL is printed next to the age column when a note has image links
IMAGE_MARKER_SYMBOL = "\uf03e"
maxUint = ^uint(0)
maxInt = int(maxUint >> 1)
)
func ctrlKey(b byte) int {
return int(b & 0x1f)
}
func truncate(s string, length int) string {
if len(s) > length {
return s[:length] + "..."
} else {
return s
}
}
func tc(s string, l int, b bool) string {
if len(s) > l {
e := ""
if b {
e = "..."
}
return s[:l] + e
} else {
return s
}
}
var googleDriveRegex = regexp.MustCompile(`!\[([^\]]*)\]\((https://drive\.google\.com/file/d/[^)]+)\)`)
var googleDriveShortRegex = regexp.MustCompile(`!\[([^\]]*)\]\((gdrive:[a-zA-Z0-9_-]+)\)`)
type Row struct {
id int
tid int
title string
ftsTitle string
star bool
deleted bool
archived bool
hasImage bool
//modified string
sort string
// below not in db
dirty bool
marked bool
}
func containsGoogleDriveImage(note string) bool {
return googleDriveRegex.MatchString(note) || googleDriveShortRegex.MatchString(note)
}
// ConvertGoogleDriveURLsToShort converts all Google Drive URLs in markdown to gdrive:ID format
// Returns the converted markdown and the count of URLs converted
func ConvertGoogleDriveURLsToShort(markdown string) (string, int) {
re := regexp.MustCompile(`!\[([^\]]*)\]\((https://drive\.google\.com/file/d/([a-zA-Z0-9_-]+)[^)]*)\)`)
count := 0
result := re.ReplaceAllStringFunc(markdown, func(match string) string {
submatches := re.FindStringSubmatch(match)
if len(submatches) >= 4 {
altText := submatches[1]
fileID := submatches[3]
count++
return fmt.Sprintf("", altText, fileID)
}
return match
})
return result, count
}
type AltRow struct {
id int
title string
star bool
}
// used in synchronize and getEntryInfo
type NewEntry struct {
id int
tid int
title string
folder_tid int
context_tid int
folder_uuid string
context_uuid string
star bool
note sql.NullString //string
added string
archived bool
deleted bool
modified string
}
type Entry struct {
id int
tid int
title string
folder_tid int
context_tid int
folder_uuid string
context_uuid string
star bool
note sql.NullString //string
added sql.NullString
completed sql.NullString
deleted bool
modified string
}
type serverEntry struct {
id int
title string
folder_id int
context_id int
star bool
note sql.NullString //string
added sql.NullString //string
completed sql.NullString //sql.NullTime since sqlite doesn't have datetime type
deleted bool
modified string
}
type Container struct {
id int
tid int
uuid string // Primary identifier for containers
title string
star bool
deleted bool
modified string
count int
}
// type outlineKey int
const (
BACKSPACE = iota + 127
ARROW_LEFT = iota + 999 //would have to be < 127 to be chars
ARROW_RIGHT
ARROW_UP
ARROW_DOWN
DEL_KEY
HOME_KEY
END_KEY
PAGE_UP
PAGE_DOWN
NOP
SHIFT_TAB
)
func (m Mode) String() string {
return [...]string{
"NORMAL",
"NORMAL BUSY",
"INSERT",
"COMMAND LINE",
"EX COMMAND",
"VISUAL LINE",
"VISUAL",
"VISUAL BLOCK",
"SEARCH",
//"FIND",
"PREVIEW",
"VIEW LOG",
"SPELLING",
"NAVIGATE_NOTICE",
"HELP",
"CONTAINER",
"LINKS",
"PENDING",
"OTHER",
}[m]
}
type View int
const (
TASK View = iota
CONTEXT
FOLDER
KEYWORD
//SYNC_LOG_VIEW
)
func (v View) String() string {
return [...]string{
"task",
"context",
"folder",
"keyword",
}[v]
}
// type TaskView int
const (
BY_CONTEXT = iota
BY_FOLDER
BY_KEYWORD
BY_JOIN
BY_RECENT
BY_FIND
)
const leader = " "
func getStringInBetween(str string, start string, end string) string {
k, v, ok := strings.Cut(str, start)
if !ok {
return ""
}
k, v, ok = strings.Cut(v, start)
if !ok {
return ""
}
return k
}
func extractFilePath(input string) string {
// Normalize line breaks
normalized := strings.ReplaceAll(input, "\n", "")
// Split by the arrow
parts := strings.Split(normalized, "→")
if len(parts) < 2 {
return ""
}
location := strings.Split(parts[1], "|")
// Get everything after the arrow
if len(location) < 2 {
return ""
} else {
return location[1]
}
}
func extractFilePath_(input string) string {
// Normalize line breaks
normalized := strings.ReplaceAll(input, "\n", "")
// Split by the arrow
parts := strings.Split(normalized, "→")
if len(parts) < 2 {
return ""
}
// Get everything after the arrow
afterArrow := strings.TrimSpace(parts[1])
// Strip ANSI escape codes
ansiEscapeRegex := regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`)
cleanedText := ansiEscapeRegex.ReplaceAllString(afterArrow, "")
// Enhanced regex for complex paths and URLs
// This handles:
// 1. URLs with multiple path segments
// 2. Wikipedia-style URLs with dimensions in the path
// 3. Traditional file paths and simple URLs
pathRegex := regexp.MustCompile(`((?:https?://)[^\s]+?/[^\s]+?\.(jpg|jpeg|png|gif|bmp|tiff|webp)(?:/[^\s]+?\.(jpg|jpeg|png|gif|bmp|tiff|webp))?(?:\?[^\s]*)?|(?:/|[A-Za-z]:\\|[A-Za-z0-9_\-\.]+/)[^\s]+?\.(jpg|jpeg|png|gif|bmp|tiff|webp)(?:\?[^\s]*)?)`)
match := pathRegex.FindString(cleanedText)
// If no match yet, try a more permissive regex focused on URLs
if match == "" {
urlRegex := regexp.MustCompile(`https?://[^\s]+?\.(jpg|jpeg|png|gif|bmp|tiff|webp)(?:/[^\s]*?)?`)
match = urlRegex.FindString(cleanedText)
}
return match
}
func extractFilePath__(input string) string {
// First, normalize line breaks to handle word wrapping
normalized := strings.ReplaceAll(input, "\n", "")
// Split by the arrow
parts := strings.Split(normalized, "→")
if len(parts) < 2 {
return ""
}
// Get everything after the arrow
afterArrow := strings.TrimSpace(parts[1])
// Strip ANSI escape codes that might be surrounding the path
// ANSI escape codes typically start with ESC[ (represented as \x1b[ or \033[)
// and end with a letter (m is common for color codes)
ansiEscapeRegex := regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`)
cleanedText := ansiEscapeRegex.ReplaceAllString(afterArrow, "")
// Match URLs and file paths
pathRegex := regexp.MustCompile(`((?:https?://|/|[A-Za-z]:\\|[A-Za-z0-9_\-\.]+/)[^\s]+?(?:\.(jpg|jpeg|png|gif|bmp|tiff|webp)(?:[\?#][^\s]*)?))`)
match := pathRegex.FindString(cleanedText)
return match
}
func timeDelta(t string) string {
var t0 time.Time
if strings.Contains(t, "T") {
t0, _ = time.Parse("2006-01-02T15:04:05Z", t)
} else {
t0, _ = time.Parse("2006-01-02 15:04:05", t)
}
diff := time.Since(t0)
diff = diff / 1000000000
if diff <= 120 {
return fmt.Sprintf("%d seconds ago", diff)
} else if diff <= 60*120 {
return fmt.Sprintf("%d minutes ago", diff/60) // <120 minutes we report minute
} else if diff <= 48*60*60 {
return fmt.Sprintf("%d hours ago", diff/3600) // <48 hours report hours
} else if diff <= 24*60*60*60 {
return fmt.Sprintf("%d days ago", diff/3600/24) // <60 days report days
} else if diff <= 24*30*24*60*60 {
return fmt.Sprintf("%d months ago", diff/3600/24/30) // <24 months rep
} else {
return fmt.Sprintf("%d years ago", diff/3600/24/30/12)
}
}
/*
type BufLinesEvent struct {
Buffer nvim.Buffer
//Changetick int64
Changetick interface{} //int64
FirstLine interface{} //int64
LastLine interface{} //int64
LineData string
IsMultipart bool
}
*/