-
Notifications
You must be signed in to change notification settings - Fork 0
/
buf.go
2818 lines (2555 loc) · 76.9 KB
/
buf.go
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018, The GoKi Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package texteditor
import (
"bytes"
"fmt"
"image/color"
"io/ioutil"
"log"
"log/slog"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"goki.dev/enums"
"goki.dev/fi"
"goki.dev/gi/v2/gi"
"goki.dev/gi/v2/texteditor/histyle"
"goki.dev/gi/v2/texteditor/textbuf"
"goki.dev/girl/styles"
"goki.dev/glop/dirs"
"goki.dev/glop/indent"
"goki.dev/glop/runes"
"goki.dev/goosi/events"
"goki.dev/grr"
"goki.dev/icons"
"goki.dev/pi/v2/complete"
"goki.dev/pi/v2/lex"
"goki.dev/pi/v2/pi"
"goki.dev/pi/v2/token"
"goki.dev/spell"
)
var (
// BufMaxScopeLines is the maximum lines to search for a scope marker, e.g. '}'
BufMaxScopeLines = 100
// BufDiffRevertLines is max number of lines to use the
// diff-based revert, which results in faster reverts but only
// if the file isn't too big..
BufDiffRevertLines = 10000
// BufDiffRevertDiffs is max number of difference regions
// to apply for diff-based revert otherwise just reopens file
BufDiffRevertDiffs = 20
// BufMarkupDelayMSec is the number of milliseconds to wait
// before starting a new background markup process, after
// text is entered in the line
BufMarkupDelayMSec = 1000
)
// Buf is a buffer of text, which can be viewed by View(s).
// It holds the raw text lines (in original string and rune formats,
// and marked-up from syntax highlighting), and sends signals for making
// edits to the text and coordinating those edits across multiple views.
// Views always only view a single buffer, so they directly call methods
// on the buffer to drive updates, which are then broadcast.
// It also has methods for loading and saving buffers to files.
// Unlike GUI Widgets, its methods are generally signaling, without an
// explicit Action suffix.
// Internally, the buffer represents new lines using \n = LF, but saving
// and loading can deal with Windows/DOS CRLF format.
type Buf struct {
// filename of file last loaded or saved
Filename gi.FileName `json:"-" xml:"-"`
// Flags are key state flags
Flags BufFlags
// the current value of the entire text being edited -- using byte slice for greater efficiency
Txt []byte `json:"-" xml:"text"`
// if true, auto-save file after changes (in a separate routine)
Autosave bool
// options for how text editing / viewing works
Opts textbuf.Opts
// full info about file
Info fi.FileInfo
// Pi parsing state info for file
PiState pi.FileStates
// syntax highlighting markup parameters (language, style, etc)
Hi HiMarkup
// number of lines
NLines int `json:"-" xml:"-"`
// icons for given lines -- use SetLineIcon and DeleteLineIcon
LineIcons map[int]icons.Icon
// special line number colors given lines -- use SetLineColor and DeleteLineColor
LineColors map[int]color.RGBA
// icons for each LineIcons being used
Icons map[icons.Icon]*gi.Icon `json:"-" xml:"-"`
// the live lines of text being edited, with latest modifications -- encoded as runes per line, which is necessary for one-to-one rune / glyph rendering correspondence -- all TextPos positions etc are in *rune* indexes, not byte indexes!
Lines [][]rune `json:"-" xml:"-"`
// the live lines of text being edited, with latest modifications -- encoded in bytes per line translated from Lines, and used for input to markup -- essential to use Lines and not LineBytes when dealing with TextPos positions, which are in runes
LineBytes [][]byte `json:"-" xml:"-"`
Tags []lex.Line `json:"extra custom tagged regions for each line"`
HiTags []lex.Line `json:"syntax highlighting tags -- auto-generated"`
// marked-up version of the edit text lines, after being run through the syntax highlighting process etc -- this is what is actually rendered
Markup [][]byte `json:"-" xml:"-"`
// edits that have been made since last full markup
MarkupEdits []*textbuf.Edit `json:"-" xml:"-"`
// offsets for start of each line in Txt byte slice -- this is NOT updated with edits -- call SetByteOffs to set it when needed -- used for re-generating the Txt in LinesToBytes, and set on initial open in BytesToLines
ByteOffs []int `json:"-" xml:"-"`
// total bytes in document -- see ByteOffs for when it is updated
TotalBytes int `json:"-" xml:"-"`
// mutex for updating lines
LinesMu sync.RWMutex `json:"-" xml:"-"`
// mutex for updating markup
MarkupMu sync.RWMutex `json:"-" xml:"-"`
// markup delay timer
MarkupDelayTimer *time.Timer `json:"-" xml:"-"`
// mutex for updating markup delay timer
MarkupDelayMu sync.Mutex `json:"-" xml:"-"`
// the Views that are currently viewing this buffer
Views []*Editor `json:"-" xml:"-"`
// undo manager
Undos textbuf.Undo `json:"-" xml:"-"`
// history of cursor positions -- can move back through them
PosHistory []lex.Pos `json:"-" xml:"-"`
// functions and data for text completion
Complete *gi.Complete `json:"-" xml:"-"`
// functions and data for spelling correction
Spell *gi.Spell `json:"-" xml:"-"`
// current text editor -- e.g., the one that initiated Complete or Correct process -- update cursor position in this view -- is reset to nil after usage always
CurView *Editor `json:"-" xml:"-"`
// supports standard goosi events sending: Change is sent for BufDone, BufInsert, BufDelete
Listeners events.Listeners
}
func NewBuf() *Buf {
tb := &Buf{}
tb.SetHiStyle(histyle.StyleDefault)
tb.Opts.EditorPrefs = gi.Prefs.Editor
return tb
}
func (tb *Buf) FlagType() enums.BitFlagSetter {
return (*BufFlags)(&tb.Flags)
}
// BufSignals are signals that text buffer can send to View
type BufSignals int32 //enums:enum
const (
// BufDone means that editing was completed and applied to Txt field
// -- data is Txt bytes
BufDone BufSignals = iota
// BufNew signals that entirely new text is present.
// All views should do full layout update.
BufNew
// BufMods signals that potentially diffuse modifications
// have been made. Views should do a Layout and Render.
BufMods
// BufInsert signals that some text was inserted.
// data is textbuf.Edit describing change.
// The Buf always reflects the current state *after* the edit.
BufInsert
// BufDelete signals that some text was deleted.
// data is textbuf.Edit describing change.
// The Buf always reflects the current state *after* the edit.
BufDelete
// BufMarkUpdt signals that the Markup text has been updated
// This signal is typically sent from a separate goroutine,
// so should be used with a mutex
BufMarkUpdt
// BufClosed signals that the textbuf was closed.
BufClosed
)
// SignalViews sends the given signal and optional edit info
// to all the Views for this Buf
func (tb *Buf) SignalViews(sig BufSignals, edit *textbuf.Edit) {
for _, vw := range tb.Views {
vw.BufSignal(sig, edit)
}
if sig == BufDone {
e := &events.Base{Typ: events.Change}
e.Init()
tb.Listeners.Call(e)
} else if sig == BufInsert || sig == BufDelete {
e := &events.Base{Typ: events.Input}
e.Init()
tb.Listeners.Call(e)
}
}
// OnChange adds an event listener function for the [events.Change] event
func (tb *Buf) OnChange(fun func(e events.Event)) {
tb.Listeners.Add(events.Change, fun)
}
// OnInput adds an event listener function for the [events.Input] event
func (tb *Buf) OnInput(fun func(e events.Event)) {
tb.Listeners.Add(events.Input, fun)
}
// BufFlags hold key Buf state
type BufFlags gi.WidgetFlags //enums:bitflag -trim-prefix Buf
const (
// BufAutoSaving is used in atomically safe way to protect autosaving
BufAutoSaving BufFlags = BufFlags(gi.WidgetFlagsN) + iota
// BufMarkingUp indicates current markup operation in progress -- don't redo
BufMarkingUp
// BufChanged indicates if the text has been changed (edited) relative to the
// original, since last EditDone
BufChanged
// BufNotSaved indicates if the text has been changed (edited) relative to the
// original, since last Save
BufNotSaved
// BufFileModOk have already asked about fact that file has changed since being
// opened, user is ok
BufFileModOk
)
// Is returns true if given flag is set
func (tb *Buf) Is(flag enums.BitFlag) bool {
return tb.Flags.HasFlag(flag)
}
// SetFlag sets value of given flag(s)
func (tb *Buf) SetFlag(on bool, flag ...enums.BitFlag) {
tb.Flags.SetFlag(on, flag...)
}
// ClearChanged marks buffer as un-changed
func (tb *Buf) ClearChanged() {
tb.SetFlag(false, BufChanged)
}
// ClearNotSaved resets the BufNotSaved flag, and also calls ClearChanged
func (tb *Buf) ClearNotSaved() {
tb.ClearChanged()
tb.SetFlag(false, BufNotSaved)
}
// IsChanged indicates if the text has been changed (edited) relative to
// the original, since last EditDone
func (tb *Buf) IsChanged() bool {
return tb.Is(BufChanged)
}
// IsNotSaved indicates if the text has been changed (edited) relative to
// the original, since last Save
func (tb *Buf) IsNotSaved() bool {
return tb.Is(BufNotSaved)
}
// SetChanged marks buffer as changed
func (tb *Buf) SetChanged() {
tb.SetFlag(true, BufChanged)
tb.SetFlag(true, BufNotSaved)
}
// SetText sets the text to given bytes
func (tb *Buf) SetText(txt []byte) *Buf {
tb.Txt = txt
tb.BytesToLines()
tb.InitialMarkup()
tb.SignalViews(BufNew, nil)
tb.ReMarkup()
return tb
}
func (tb *Buf) Update() {
tb.SignalMods()
}
// SetTextLines sets the text to given lines of bytes
// if cpy is true, make a copy of bytes -- otherwise use
func (tb *Buf) SetTextLines(lns [][]byte, cpy bool) {
tb.LinesMu.Lock()
tb.NLines = len(lns)
tb.LinesMu.Unlock()
tb.NewBuf(tb.NLines)
tb.LinesMu.Lock()
bo := 0
for ln, txt := range lns {
tb.ByteOffs[ln] = bo
tb.Lines[ln] = bytes.Runes(txt)
if cpy {
tb.LineBytes[ln] = make([]byte, len(txt))
copy(tb.LineBytes[ln], txt)
} else {
tb.LineBytes[ln] = txt
}
tb.Markup[ln] = HTMLEscapeRunes(tb.Lines[ln])
bo += len(txt) + 1 // lf
}
tb.TotalBytes = bo
tb.LinesMu.Unlock()
tb.LinesToBytes()
tb.InitialMarkup()
tb.SignalViews(BufNew, nil)
tb.ReMarkup()
}
// EditDone finalizes any current editing, sends signal
func (tb *Buf) EditDone() {
tb.AutoSaveDelete()
tb.ClearChanged()
tb.LinesToBytes()
tb.SignalViews(BufDone, nil)
}
// Text returns the current text as a []byte array, applying all current
// changes -- calls EditDone and will generate that signal if there have been
// changes
func (tb *Buf) Text() []byte {
tb.EditDone()
return tb.Txt
}
// NumLines is the concurrent-safe accessor to NLines
func (tb *Buf) NumLines() int {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
return tb.NLines
}
// IsValidLine returns true if given line is in range
func (tb *Buf) IsValidLine(ln int) bool {
if ln < 0 {
return false
}
nln := tb.NumLines()
if ln >= nln {
return false
}
return true
}
// Line is the concurrent-safe accessor to specific Line of Lines runes
func (tb *Buf) Line(ln int) []rune {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if ln >= tb.NLines || ln < 0 {
return nil
}
return tb.Lines[ln]
}
// LineLen is the concurrent-safe accessor to length of specific Line of Lines runes
func (tb *Buf) LineLen(ln int) int {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if ln >= tb.NLines || ln < 0 {
return 0
}
return len(tb.Lines[ln])
}
// BytesLine is the concurrent-safe accessor to specific Line of LineBytes
func (tb *Buf) BytesLine(ln int) []byte {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if ln >= tb.NLines || ln < 0 {
return nil
}
return tb.LineBytes[ln]
}
// SetHiStyle sets the highlighting style -- needs to be protected by mutex
func (tb *Buf) SetHiStyle(style gi.HiStyleName) *Buf {
tb.MarkupMu.Lock()
tb.Hi.SetHiStyle(style)
tb.MarkupMu.Unlock()
return tb
}
// SignalMods sends the BufMods signal for misc, potentially
// widespread modifications to buffer.
func (tb *Buf) SignalMods() {
tb.SignalViews(BufMods, nil)
}
// SetReadOnly sets the buffer in a ReadOnly state if readonly = true
// otherwise is in editable state.
func (tb *Buf) SetReadOnly(readonly bool) *Buf {
tb.Undos.Off = readonly
return tb
}
func (tb *Buf) SetFilename(fn string) *Buf {
tb.Filename = gi.FileName(fn)
tb.Stat()
tb.Hi.Init(&tb.Info, &tb.PiState)
return tb
}
// todo: use https://github.com/andybalholm/crlf to deal with cr/lf etc --
// internally just use lf = \n
// New initializes a new buffer with n blank lines
func (tb *Buf) NewBuf(nlines int) {
nlines = max(nlines, 1)
tb.LinesMu.Lock()
tb.MarkupMu.Lock()
tb.Undos.Reset()
tb.Lines = make([][]rune, nlines)
tb.LineBytes = make([][]byte, nlines)
tb.Tags = make([]lex.Line, nlines)
tb.HiTags = make([]lex.Line, nlines)
tb.Markup = make([][]byte, nlines)
if cap(tb.ByteOffs) >= nlines {
tb.ByteOffs = tb.ByteOffs[:nlines]
} else {
tb.ByteOffs = make([]int, nlines)
}
if nlines == 1 { // this is used for a new blank doc
tb.ByteOffs[0] = 0 // by definition
tb.Lines[0] = []rune("")
tb.LineBytes[0] = []byte("")
tb.Markup[0] = []byte("")
}
tb.NLines = nlines
tb.PiState.SetSrc(string(tb.Filename), "", tb.Info.Known)
tb.Hi.Init(&tb.Info, &tb.PiState)
tb.MarkupMu.Unlock()
tb.LinesMu.Unlock()
tb.SignalViews(BufNew, nil)
}
// Stat gets info about the file, including highlighting language
func (tb *Buf) Stat() error {
tb.SetFlag(false, BufFileModOk)
err := tb.Info.InitFile(string(tb.Filename))
if err != nil {
return err
}
tb.ConfigKnown()
return nil
}
// ConfigKnown configures options based on the supported language info in GoPi
// returns true if supported
func (tb *Buf) ConfigKnown() bool {
if tb.Info.Known != fi.Unknown {
if tb.Spell == nil {
tb.SetSpell()
}
if tb.Complete == nil {
tb.SetCompleter(&tb.PiState, CompletePi, CompleteEditPi, LookupPi)
}
return tb.Opts.ConfigKnown(tb.Info.Known)
}
return false
}
// FileModCheck checks if the underlying file has been modified since last
// Stat (open, save) -- if haven't yet prompted, user is prompted to ensure
// that this is OK. returns true if file was modified
func (tb *Buf) FileModCheck() bool {
if tb.Is(BufFileModOk) {
return false
}
info, err := os.Stat(string(tb.Filename))
if err != nil {
return false
}
if info.ModTime() != time.Time(tb.Info.ModTime) {
sc := tb.SceneFromView()
d := gi.NewBody().AddTitle("File changed on disk: " + dirs.DirAndFile(string(tb.Filename))).
AddText(fmt.Sprintf("File has changed on disk since being opened or saved by you; what do you want to do? If you <code>Revert from Disk</code>, you will lose any existing edits in open buffer. If you <code>Ignore and Proceed</code>, the next save will overwrite the changed file on disk, losing any changes there. File: %v", tb.Filename))
d.AddBottomBar(func(pw gi.Widget) {
gi.NewButton(pw).SetText("Save as to different file").OnClick(func(e events.Event) {
d.Close()
// TODO(kai/dialog): add this back -- can't call giv from here!
gi.TheViewIFace.CallFunc(sc, tb.SaveAs)
})
gi.NewButton(pw).SetText("Revert from disk").OnClick(func(e events.Event) {
d.Close()
tb.Revert()
})
gi.NewButton(pw).SetText("Ignore and proceed").OnClick(func(e events.Event) {
d.Close()
tb.SetFlag(true, BufFileModOk)
})
})
d.NewDialog(sc).Run()
return true
}
return false
}
// Open loads text from a file into the buffer
func (tb *Buf) Open(filename gi.FileName) error {
err := tb.OpenFile(filename)
if err != nil {
// vp := tb.SceneFromView()
// TODO(kai/snack)
// gi.PromptDialog(nil, gi.DlgOpts{Title: "File could not be Opened", Prompt: err.Error(), Ok: true, Cancel: false}, nil)
slog.Error(err.Error())
return err
}
tb.InitialMarkup()
tb.SignalViews(BufNew, nil)
tb.ReMarkup()
return nil
}
// OpenFile just loads a file into the buffer -- doesn't do any markup or
// notification -- for temp bufs
func (tb *Buf) OpenFile(filename gi.FileName) error {
fp, err := os.Open(string(filename))
if err != nil {
return err
}
tb.Txt, err = ioutil.ReadAll(fp)
fp.Close()
tb.SetFilename(string(filename))
tb.BytesToLines()
return nil
}
// Revert re-opens text from current file, if filename set -- returns false if
// not -- uses an optimized diff-based update to preserve existing formatting
// -- very fast if not very different
func (tb *Buf) Revert() bool {
tb.AutoSaveDelete() // justin case
if tb.Filename == "" {
return false
}
didDiff := false
if tb.NLines < BufDiffRevertLines {
ob := NewBuf()
err := ob.OpenFile(tb.Filename)
if err != nil {
sc := tb.SceneFromView()
if sc != nil { // only if viewing
// TODO(kai/snack)
// gi.PromptDialog(vp, gi.DlgOpts{Title: "File could not be Re-Opened", Prompt: err.Error(), Ok: true, Cancel: false}, nil)
}
slog.Error(err.Error())
return false
}
tb.Stat() // "own" the new file..
if ob.NLines < BufDiffRevertLines {
diffs := tb.DiffBufs(ob)
if len(diffs) < BufDiffRevertDiffs {
tb.PatchFromBuf(ob, diffs, true) // true = send sigs for each update -- better than full, assuming changes are minor
didDiff = true
}
}
}
if !didDiff {
tb.OpenFile(tb.Filename)
}
tb.ClearNotSaved()
tb.AutoSaveDelete()
tb.SignalViews(BufNew, nil)
tb.ReMarkup()
return true
}
// SaveAsFunc saves the current text into given file.
// Does an EditDone first to save edits and checks for an existing file.
// If it does exist then prompts to overwrite or not.
// If afterFunc is non-nil, then it is called with the status of the user action.
func (tb *Buf) SaveAsFunc(filename gi.FileName, afterFunc func(canceled bool)) {
// todo: filemodcheck!
tb.EditDone()
if !grr.Log1(dirs.FileExists(string(filename))) {
tb.SaveFile(filename)
if afterFunc != nil {
afterFunc(false)
}
} else {
sc := tb.SceneFromView()
d := gi.NewBody().AddTitle("File Exists, Overwrite?").
AddText(fmt.Sprintf("File already exists, overwrite? File: %v", filename))
d.AddBottomBar(func(pw gi.Widget) {
d.AddCancel(pw).OnClick(func(e events.Event) {
if afterFunc != nil {
afterFunc(true)
}
})
d.AddOk(pw).OnClick(func(e events.Event) {
tb.SaveFile(filename)
if afterFunc != nil {
afterFunc(false)
}
})
})
d.NewDialog(sc).Run()
}
}
// SaveAs saves the current text into given file -- does an EditDone first to save edits
// and checks for an existing file -- if it does exist then prompts to overwrite or not.
func (tb *Buf) SaveAs(filename gi.FileName) {
tb.SaveAsFunc(filename, nil)
}
// SaveFile writes current buffer to file, with no prompting, etc
func (tb *Buf) SaveFile(filename gi.FileName) error {
err := os.WriteFile(string(filename), tb.Txt, 0644)
if err != nil {
gi.ErrorSnackbar(tb.SceneFromView(), err)
slog.Error(err.Error())
} else {
tb.ClearNotSaved()
tb.Filename = filename
tb.Stat()
}
return err
}
// Save saves the current text into current Filename associated with this
// buffer
func (tb *Buf) Save() error {
if tb.Filename == "" {
return fmt.Errorf("giv.Buf: filename is empty for Save")
}
tb.EditDone()
info, err := os.Stat(string(tb.Filename))
if err == nil && info.ModTime() != time.Time(tb.Info.ModTime) {
sc := tb.SceneFromView()
d := gi.NewBody().AddTitle("File Changed on Disk").
AddText(fmt.Sprintf("File has changed on disk since being opened or saved by you -- what do you want to do? File: %v", tb.Filename))
d.AddBottomBar(func(pw gi.Widget) {
gi.NewButton(pw).SetText("Save to different file").OnClick(func(e events.Event) {
d.Close()
// CallMethod(tb, "SaveAs", vp) // todo: don't have
})
gi.NewButton(pw).SetText("Open from disk, losing changes").OnClick(func(e events.Event) {
d.Close()
tb.Revert()
})
gi.NewButton(pw).SetText("Save file, overwriting").OnClick(func(e events.Event) {
d.Close()
tb.SaveFile(tb.Filename)
})
})
d.NewDialog(sc).Run()
}
return tb.SaveFile(tb.Filename)
}
// Close closes the buffer -- prompts to save if changes, and disconnects from views
// if afterFun is non-nil, then it is called with the status of the user action
func (tb *Buf) Close(afterFun func(canceled bool)) bool {
if tb.IsChanged() {
sc := tb.SceneFromView()
if tb.Filename != "" {
d := gi.NewBody().AddTitle("Close without saving?").
AddText(fmt.Sprintf("Do you want to save your changes to file: %v?", tb.Filename))
d.AddBottomBar(func(pw gi.Widget) {
gi.NewButton(pw).SetText("Cancel").OnClick(func(e events.Event) {
d.Close()
if afterFun != nil {
afterFun(true)
}
})
gi.NewButton(pw).SetText("Close without saving").OnClick(func(e events.Event) {
d.Close()
tb.ClearNotSaved()
tb.AutoSaveDelete()
tb.Close(afterFun)
})
gi.NewButton(pw).SetText("Save").OnClick(func(e events.Event) {
tb.Save()
tb.Close(afterFun) // 2nd time through won't prompt
})
})
d.NewDialog(sc).Run()
} else {
d := gi.NewBody().AddTitle("Close without saving?").
AddText("Do you want to save your changes (no filename for this buffer yet)? If so, Cancel and then do Save As")
d.AddBottomBar(func(pw gi.Widget) {
d.AddCancel(pw).OnClick(func(e events.Event) {
if afterFun != nil {
afterFun(true)
}
})
d.AddOk(pw).SetText("Close without saving").OnClick(func(e events.Event) {
tb.ClearNotSaved()
tb.AutoSaveDelete()
tb.Close(afterFun)
})
})
d.NewDialog(sc).Run()
}
return false // awaiting decisions..
}
tb.SignalViews(BufClosed, nil)
tb.NewBuf(1)
tb.Filename = ""
tb.ClearNotSaved()
if afterFun != nil {
afterFun(false)
}
return true
}
////////////////////////////////////////////////////////////////////////////////////////
// AutoSave
// AutoSaveOff turns off autosave and returns the
// prior state of Autosave flag.
// Call AutoSaveRestore with rval when done.
// See BatchUpdate methods for auto-use of this.
func (tb *Buf) AutoSaveOff() bool {
asv := tb.Autosave
tb.Autosave = false
return asv
}
// AutoSaveRestore restores prior Autosave setting,
// from AutoSaveOff
func (tb *Buf) AutoSaveRestore(asv bool) {
tb.Autosave = asv
}
// AutoSaveFilename returns the autosave filename
func (tb *Buf) AutoSaveFilename() string {
path, fn := filepath.Split(string(tb.Filename))
if fn == "" {
fn = "new_file"
}
asfn := filepath.Join(path, "#"+fn+"#")
return asfn
}
// AutoSave does the autosave -- safe to call in a separate goroutine
func (tb *Buf) AutoSave() error {
if tb.Is(BufAutoSaving) {
return nil
}
tb.SetFlag(true, BufAutoSaving)
asfn := tb.AutoSaveFilename()
b := tb.LinesToBytesCopy()
err := os.WriteFile(asfn, b, 0644)
if err != nil {
log.Printf("giv.Buf: Could not AutoSave file: %v, error: %v\n", asfn, err)
}
tb.SetFlag(false, BufAutoSaving)
return err
}
// AutoSaveDelete deletes any existing autosave file
func (tb *Buf) AutoSaveDelete() {
asfn := tb.AutoSaveFilename()
os.Remove(asfn)
}
// AutoSaveCheck checks if an autosave file exists -- logic for dealing with
// it is left to larger app -- call this before opening a file
func (tb *Buf) AutoSaveCheck() bool {
asfn := tb.AutoSaveFilename()
if _, err := os.Stat(asfn); os.IsNotExist(err) {
return false // does not exist
}
return true
}
/////////////////////////////////////////////////////////////////////////////
// Appending Lines
// EndPos returns the ending position at end of buffer
func (tb *Buf) EndPos() lex.Pos {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if tb.NLines == 0 {
return lex.PosZero
}
ed := lex.Pos{tb.NLines - 1, len(tb.Lines[tb.NLines-1])}
return ed
}
// AppendText appends new text to end of buffer, using insert, returns edit
func (tb *Buf) AppendText(text []byte, signal bool) *textbuf.Edit {
if len(text) == 0 {
return &textbuf.Edit{}
}
ed := tb.EndPos()
return tb.InsertText(ed, text, signal)
}
// AppendTextLine appends one line of new text to end of buffer, using insert,
// and appending a LF at the end of the line if it doesn't already have one.
// Returns the edit region.
func (tb *Buf) AppendTextLine(text []byte, signal bool) *textbuf.Edit {
ed := tb.EndPos()
sz := len(text)
addLF := false
if sz > 0 {
if text[sz-1] != '\n' {
addLF = true
}
} else {
addLF = true
}
efft := text
if addLF {
tcpy := make([]byte, sz+1)
copy(tcpy, text)
tcpy[sz] = '\n'
efft = tcpy
}
tbe := tb.InsertText(ed, efft, signal)
return tbe
}
// AppendTextMarkup appends new text to end of buffer, using insert, returns
// edit, and uses supplied markup to render it
func (tb *Buf) AppendTextMarkup(text []byte, markup []byte, signal bool) *textbuf.Edit {
if len(text) == 0 {
return &textbuf.Edit{}
}
ed := tb.EndPos()
tbe := tb.InsertText(ed, text, false) // no sig -- we do later
st := tbe.Reg.Start.Ln
el := tbe.Reg.End.Ln
sz := (el - st) + 1
msplt := bytes.Split(markup, []byte("\n"))
if len(msplt) < sz {
log.Printf("Buf AppendTextMarkup: markup text less than appended text: is: %v, should be: %v\n", len(msplt), sz)
el = min(st+len(msplt)-1, el)
}
for ln := st; ln <= el; ln++ {
tb.Markup[ln] = msplt[ln-st]
}
if signal {
tb.SignalViews(BufInsert, tbe)
}
return tbe
}
// AppendTextLineMarkup appends one line of new text to end of buffer, using
// insert, and appending a LF at the end of the line if it doesn't already
// have one. user-supplied markup is used. Returns the edit region.
func (tb *Buf) AppendTextLineMarkup(text []byte, markup []byte, signal bool) *textbuf.Edit {
ed := tb.EndPos()
sz := len(text)
addLF := false
if sz > 0 {
if text[sz-1] != '\n' {
addLF = true
}
} else {
addLF = true
}
efft := text
if addLF {
tcpy := make([]byte, sz+1)
copy(tcpy, text)
tcpy[sz] = '\n'
efft = tcpy
}
tbe := tb.InsertText(ed, efft, false)
tb.Markup[tbe.Reg.Start.Ln] = markup
if signal {
tb.SignalViews(BufInsert, tbe)
}
return tbe
}
/////////////////////////////////////////////////////////////////////////////
// Views
// AddView adds a viewer of this buffer -- connects our signals to the viewer
func (tb *Buf) AddView(vw *Editor) {
tb.Views = append(tb.Views, vw)
// tb.BufSig.Connect(vw.This(), ViewBufSigRecv)
}
// DeleteView removes given viewer from our buffer
func (tb *Buf) DeleteView(vw *Editor) {
tb.MarkupMu.Lock()
tb.LinesMu.Lock()
defer func() {
tb.LinesMu.Unlock()
tb.MarkupMu.Unlock()
}()
for i, ede := range tb.Views {
if ede == vw {
tb.Views = append(tb.Views[:i], tb.Views[i+1:]...)
break
}
}
}
// SceneFromView returns Scene from text editor, if avail
func (tb *Buf) SceneFromView() *gi.Scene {
if len(tb.Views) > 0 {
return tb.Views[0].Sc
}
return nil
}
// AutoscrollViews ensures that views are always viewing the end of the buffer
func (tb *Buf) AutoScrollViews() {
for _, ed := range tb.Views {
if ed != nil && ed.This() != nil {
ed.CursorPos = tb.EndPos()
ed.ScrollCursorInView()
}
}
}
// BatchUpdateStart call this when starting a batch of updates.
// It calls AutoSaveOff and returns the prior state of that flag
// which must be restored using BatchUpdateEnd.
func (tb *Buf) BatchUpdateStart() (autoSave bool) {
tb.Undos.NewGroup()
autoSave = tb.AutoSaveOff()
return
}
// BatchUpdateEnd call to complete BatchUpdateStart
func (tb *Buf) BatchUpdateEnd(autoSave bool) {
tb.AutoSaveRestore(autoSave)
}
/////////////////////////////////////////////////////////////////////////////
// Accessing Text
// SetByteOffs sets the byte offsets for each line into the raw text
func (tb *Buf) SetByteOffs() {
bo := 0
for ln, txt := range tb.LineBytes {
tb.ByteOffs[ln] = bo
bo += len(txt) + 1 // lf
}
tb.TotalBytes = bo
}
// LinesToBytes converts current Lines back to the Txt slice of bytes.
func (tb *Buf) LinesToBytes() {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if tb.NLines == 0 {
if tb.Txt != nil {
tb.Txt = tb.Txt[:0]
}
return
}
txt := bytes.Join(tb.LineBytes, []byte("\n"))
txt = append(txt, '\n')
tb.Txt = txt
}
// LinesToBytesCopy converts current Lines into a separate text byte copy --
// e.g., for autosave or other "offline" uses of the text -- doesn't affect
// byte offsets etc
func (tb *Buf) LinesToBytesCopy() []byte {
tb.LinesMu.RLock()