-
Notifications
You must be signed in to change notification settings - Fork 0
/
textbuf.go
2741 lines (2507 loc) · 78.9 KB
/
textbuf.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 giv
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"github.com/goki/gi/gi"
"github.com/goki/gi/gist"
"github.com/goki/gi/giv/textbuf"
"github.com/goki/gi/histyle"
"github.com/goki/gi/units"
"github.com/goki/ki/indent"
"github.com/goki/ki/ints"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/ki/runes"
"github.com/goki/pi/complete"
"github.com/goki/pi/filecat"
"github.com/goki/pi/lex"
"github.com/goki/pi/pi"
"github.com/goki/pi/spell"
"github.com/goki/pi/token"
)
// TextBufMaxScopeLines is the maximum lines to search for a scope marker, e.g. '}'
var TextBufMaxScopeLines = 100
// TextBufDiffRevertLines 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..
var TextBufDiffRevertLines = 10000
// TextBufDiffRevertDiffs is max number of difference regions
// to apply for diff-based revert otherwise just reopens file
var TextBufDiffRevertDiffs = 20
// TextBufMarkupDelayMSec is the number of milliseconds to wait
// before starting a new background markup process, after
// text is entered in the line
var TextBufMarkupDelayMSec = 1000
// TextBuf is a buffer of text, which can be viewed by TextView(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 TextBuf struct {
ki.Node
Txt []byte `json:"-" xml:"text" desc:"the current value of the entire text being edited -- using []byte slice for greater efficiency"`
Autosave bool `desc:"if true, auto-save file after changes (in a separate routine)"`
Opts textbuf.Opts `desc:"options for how text editing / viewing works"`
Filename gi.FileName `json:"-" xml:"-" desc:"filename of file last loaded or saved"`
Info FileInfo `desc:"full info about file"`
PiState pi.FileStates `desc:"Pi parsing state info for file"`
Hi HiMarkup `desc:"syntax highlighting markup parameters (language, style, etc)"`
NLines int `json:"-" xml:"-" desc:"number of lines"`
LineIcons map[int]string `desc:"icons for given lines -- use SetLineIcon and DeleteLineIcon"`
LineColors map[int]gist.Color `desc:"special line number colors given lines -- use SetLineColor and DeleteLineColor"`
Icons map[string]*gi.Icon `json:"-" xml:"-" desc:"icons for each LineIcons being used"`
Lines [][]rune `json:"-" xml:"-" desc:"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!"`
LineBytes [][]byte `json:"-" xml:"-" desc:"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"`
Tags []lex.Line `json:"extra custom tagged regions for each line"`
HiTags []lex.Line `json:"syntax highlighting tags -- auto-generated"`
Markup [][]byte `json:"-" xml:"-" desc:"marked-up version of the edit text lines, after being run through the syntax highlighting process etc -- this is what is actually rendered"`
MarkupEdits []*textbuf.Edit `json:"-" xml:"-" desc:"edits that have been made since last full markup"`
ByteOffs []int `json:"-" xml:"-" desc:"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"`
TotalBytes int `json:"-" xml:"-" desc:"total bytes in document -- see ByteOffs for when it is updated"`
LinesMu sync.RWMutex `json:"-" xml:"-" desc:"mutex for updating lines"`
MarkupMu sync.RWMutex `json:"-" xml:"-" desc:"mutex for updating markup"`
MarkupDelayTimer *time.Timer `json:"-" xml:"-" desc:"markup delay timer"`
MarkupDelayMu sync.Mutex `json:"-" xml:"-" desc:"mutex for updating markup delay timer"`
TextBufSig ki.Signal `json:"-" xml:"-" view:"-" desc:"signal for buffer -- see TextBufSignals for the types"`
Views []*TextView `json:"-" xml:"-" desc:"the TextViews that are currently viewing this buffer"`
Undos textbuf.Undo `json:"-" xml:"-" desc:"undo manager"`
PosHistory []lex.Pos `json:"-" xml:"-" desc:"history of cursor positions -- can move back through them"`
Complete *gi.Complete `json:"-" xml:"-" desc:"functions and data for text completion"`
Spell *gi.Spell `json:"-" xml:"-" desc:"functions and data for spelling correction"`
CurView *TextView `json:"-" xml:"-" desc:"current textview -- e.g., the one that initiated Complete or Correct process -- update cursor position in this view -- is reset to nil after usage always"`
}
var KiT_TextBuf = kit.Types.AddType(&TextBuf{}, TextBufProps)
func (tb *TextBuf) Disconnect() {
tb.Node.Disconnect()
tb.TextBufSig.DisconnectAll()
tb.DeleteSpell()
tb.DeleteCompleter()
}
var TextBufProps = ki.Props{
"EnumType:Flag": KiT_TextBufFlags,
"CallMethods": ki.PropSlice{
{"SaveAs", ki.Props{
"Args": ki.PropSlice{
{"File Name", ki.Props{
"default-field": "Filename",
}},
},
}},
},
}
// TextBufSignals are signals that text buffer can send
type TextBufSignals int64
const (
// TextBufDone means that editing was completed and applied to Txt field
// -- data is Txt bytes
TextBufDone TextBufSignals = iota
// TextBufNew signals that entirely new text is present -- all views
// update -- data is Txt bytes.
TextBufNew
// TextBufInsert signals that some text was inserted -- data is
// textbuf.Edit describing change -- the TextBuf always reflects the
// current state *after* the edit.
TextBufInsert
// TextBufDelete signals that some text was deleted -- data is
// textbuf.Edit describing change -- the TextBuf always reflects the
// current state *after* the edit.
TextBufDelete
// TextBufMarkUpdt signals that the Markup text has been updated -- this
// signal is typically sent from a separate goroutine so should be used
// with a mutex
TextBufMarkUpdt
// TextBufClosed signals that the textbuf was closed
TextBufClosed
TextBufSignalsN
)
//go:generate stringer -type=TextBufSignals
// TextBufFlags extend NodeBase NodeFlags to hold TextBuf state
type TextBufFlags int
//go:generate stringer -type=TextBufFlags
var KiT_TextBufFlags = kit.Enums.AddEnumExt(gi.KiT_NodeFlags, TextBufFlagsN, kit.BitFlag, nil)
const (
// TextBufAutoSaving is used in atomically safe way to protect autosaving
TextBufAutoSaving TextBufFlags = TextBufFlags(gi.NodeFlagsN) + iota
// TextBufMarkingUp indicates current markup operation in progress -- don't redo
TextBufMarkingUp
// TextBufChanged indicates if the text has been changed (edited) relative to the
// original, since last save
TextBufChanged
// TextBufFileModOk have already asked about fact that file has changed since being
// opened, user is ok
TextBufFileModOk
TextBufFlagsN
)
// IsChanged indicates if the text has been changed (edited) relative to
// the original, since last save
func (tb *TextBuf) IsChanged() bool {
return tb.HasFlag(int(TextBufChanged))
}
// SetChanged marks buffer as changed
func (tb *TextBuf) SetChanged() {
tb.SetFlag(int(TextBufChanged))
}
// ClearChanged marks buffer as un-changed
func (tb *TextBuf) ClearChanged() {
tb.ClearFlag(int(TextBufChanged))
}
// SetText sets the text to given bytes
func (tb *TextBuf) SetText(txt []byte) {
tb.Defaults()
tb.Txt = txt
tb.BytesToLines()
tb.InitialMarkup()
tb.Refresh()
tb.ReMarkup()
}
// SetTextLines sets the text to given lines of bytes
// if cpy is true, make a copy of bytes -- otherwise use
func (tb *TextBuf) SetTextLines(lns [][]byte, cpy bool) {
tb.Defaults()
tb.LinesMu.Lock()
tb.NLines = len(lns)
tb.LinesMu.Unlock()
tb.New(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.Refresh()
tb.ReMarkup()
}
// EditDone finalizes any current editing, sends signal
func (tb *TextBuf) EditDone() {
tb.AutoSaveDelete()
tb.ClearChanged()
tb.LinesToBytes()
tb.TextBufSig.Emit(tb.This(), int64(TextBufDone), tb.Txt)
}
// 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 *TextBuf) Text() []byte {
tb.EditDone()
return tb.Txt
}
// NumLines is the concurrent-safe accessor to NLines
func (tb *TextBuf) NumLines() int {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
return tb.NLines
}
// IsValidLine returns true if given line is in range
func (tb *TextBuf) 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 *TextBuf) 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 *TextBuf) 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 *TextBuf) 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 *TextBuf) SetHiStyle(style gi.HiStyleName) {
tb.MarkupMu.Lock()
tb.Hi.SetHiStyle(style)
tb.MarkupMu.Unlock()
}
// Defaults sets default parameters if they haven't been yet --
// if Hi.Style is empty, then it considers it to not have been set
func (tb *TextBuf) Defaults() {
if tb.Hi.Style != "" {
return
}
tb.SetHiStyle(histyle.StyleDefault)
tb.Opts.EditorPrefs = gi.Prefs.Editor
}
// Refresh signals any views to refresh views
func (tb *TextBuf) Refresh() {
tb.TextBufSig.Emit(tb.This(), int64(TextBufNew), tb.Txt)
}
// SetInactive sets the buffer in an inactive state if inactive = true
// otherwise is in active state. Inactive = don't save Undos.
func (tb *TextBuf) SetInactive(inactive bool) {
tb.Undos.Off = inactive
}
// 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 *TextBuf) New(nlines int) {
tb.Defaults()
nlines = ints.MaxInt(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.Sup)
tb.Hi.Init(&tb.Info, &tb.PiState)
tb.MarkupMu.Unlock()
tb.LinesMu.Unlock()
tb.Refresh()
}
// Stat gets info about the file, including highlighting language
func (tb *TextBuf) Stat() error {
tb.ClearFlag(int(TextBufFileModOk))
err := tb.Info.InitFile(string(tb.Filename))
if err != nil {
return err
}
tb.ConfigSupported()
return nil
}
// ConfigSupported configures options based on the supported language info in GoPi
// returns true if supported
func (tb *TextBuf) ConfigSupported() bool {
if tb.Info.Sup != filecat.NoSupport {
if tb.Spell == nil {
tb.SetSpell()
}
if tb.Complete == nil {
tb.SetCompleter(&tb.PiState, CompletePi, CompleteEditPi, LookupPi)
}
return tb.Opts.ConfigSupported(tb.Info.Sup)
}
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 *TextBuf) FileModCheck() bool {
if tb.HasFlag(int(TextBufFileModOk)) {
return false
}
info, err := os.Stat(string(tb.Filename))
if err != nil {
return false
}
if info.ModTime() != time.Time(tb.Info.ModTime) {
vp := tb.ViewportFromView()
gi.ChoiceDialog(vp, gi.DlgOpts{Title: "File Changed on Disk: " + DirAndFile(string(tb.Filename)),
Prompt: 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)},
[]string{"Save As to diff File", "Revert from Disk", "Ignore and Proceed"},
tb.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
switch sig {
case 0:
CallMethod(tb, "SaveAs", vp)
case 1:
tb.Revert()
case 2:
tb.SetFlag(int(TextBufFileModOk))
}
})
return true
}
return false
}
// Open loads text from a file into the buffer
func (tb *TextBuf) Open(filename gi.FileName) error {
tb.Defaults()
err := tb.OpenFile(filename)
if err != nil {
vp := tb.ViewportFromView()
gi.PromptDialog(vp, gi.DlgOpts{Title: "File could not be Opened", Prompt: err.Error()}, gi.AddOk, gi.NoCancel, nil, nil)
log.Println(err)
return err
}
tb.SetName(string(filename))
tb.InitialMarkup()
tb.Refresh()
tb.ReMarkup()
return nil
}
// OpenFile just loads a file into the buffer -- doesn't do any markup or
// notification -- for temp bufs
func (tb *TextBuf) 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.Filename = filename
tb.Stat()
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 *TextBuf) Revert() bool {
tb.AutoSaveDelete() // justin case
if tb.Filename == "" {
return false
}
didDiff := false
if tb.NLines < TextBufDiffRevertLines {
ob := &TextBuf{}
ob.InitName(ob, "revert-tmp")
err := ob.OpenFile(tb.Filename)
if err != nil {
vp := tb.ViewportFromView()
if vp != nil { // only if viewing
gi.PromptDialog(vp, gi.DlgOpts{Title: "File could not be Re-Opened", Prompt: err.Error()}, gi.AddOk, gi.NoCancel, nil, nil)
}
log.Println(err)
return false
}
tb.Stat() // "own" the new file..
if ob.NLines < TextBufDiffRevertLines {
diffs := tb.DiffBufs(ob)
if len(diffs) < TextBufDiffRevertDiffs {
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.ClearChanged()
tb.AutoSaveDelete()
tb.Refresh()
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 *TextBuf) SaveAsFunc(filename gi.FileName, afterFunc func(canceled bool)) {
// todo: filemodcheck!
tb.EditDone()
if _, err := os.Stat(string(filename)); os.IsNotExist(err) {
tb.SaveFile(filename)
if afterFunc != nil {
afterFunc(false)
}
} else {
vp := tb.ViewportFromView()
gi.ChoiceDialog(vp, gi.DlgOpts{Title: "File Exists, Overwrite?",
Prompt: fmt.Sprintf("File already exists, overwrite? File: %v", filename)},
[]string{"Cancel", "Overwrite"},
tb.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
cancel := false
switch sig {
case 0:
cancel = true
case 1:
tb.SaveFile(filename)
}
if afterFunc != nil {
afterFunc(cancel)
}
})
}
}
// 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 *TextBuf) SaveAs(filename gi.FileName) {
tb.SaveAsFunc(filename, nil)
}
// SaveFile writes current buffer to file, with no prompting, etc
func (tb *TextBuf) SaveFile(filename gi.FileName) error {
err := ioutil.WriteFile(string(filename), tb.Txt, 0644)
if err != nil {
gi.PromptDialog(nil, gi.DlgOpts{Title: "Could not Save to File", Prompt: err.Error()}, gi.AddOk, gi.NoCancel, nil, nil)
log.Println(err)
} else {
tb.Filename = filename
tb.SetName(string(filename))
tb.Stat()
}
return err
}
// Save saves the current text into current Filename associated with this
// buffer
func (tb *TextBuf) Save() error {
if tb.Filename == "" {
return fmt.Errorf("giv.TextBuf: filename is empty for Save")
}
tb.EditDone()
info, err := os.Stat(string(tb.Filename))
if err == nil && info.ModTime() != time.Time(tb.Info.ModTime) {
vp := tb.ViewportFromView()
gi.ChoiceDialog(vp, gi.DlgOpts{Title: "File Changed on Disk",
Prompt: fmt.Sprintf("File has changed on disk since being opened or saved by you -- what do you want to do? File: %v", tb.Filename)},
[]string{"Save To Different File", "Open From Disk, Losing Changes", "Save File, Overwriting"},
tb.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
switch sig {
case 0:
CallMethod(tb, "SaveAs", vp)
case 1:
tb.Revert()
case 2:
tb.SaveFile(tb.Filename)
}
})
}
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 *TextBuf) Close(afterFun func(canceled bool)) bool {
if tb.IsChanged() {
vp := tb.ViewportFromView()
if tb.Filename != "" {
gi.ChoiceDialog(vp, gi.DlgOpts{Title: "Close Without Saving?",
Prompt: fmt.Sprintf("Do you want to save your changes to file: %v?", tb.Filename)},
[]string{"Save", "Close Without Saving", "Cancel"},
tb.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
switch sig {
case 0:
tb.Save()
tb.Close(afterFun) // 2nd time through won't prompt
case 1:
tb.ClearChanged()
tb.AutoSaveDelete()
tb.Close(afterFun)
case 2:
if afterFun != nil {
afterFun(true)
}
}
})
} else {
gi.ChoiceDialog(vp, gi.DlgOpts{Title: "Close Without Saving?",
Prompt: "Do you want to save your changes (no filename for this buffer yet)? If so, Cancel and then do Save As"},
[]string{"Close Without Saving", "Cancel"},
tb.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
switch sig {
case 0:
tb.ClearChanged()
tb.AutoSaveDelete()
tb.Close(afterFun)
case 1:
if afterFun != nil {
afterFun(true)
}
}
})
}
return false // awaiting decisions..
}
tb.TextBufSig.Emit(tb.This(), int64(TextBufClosed), nil)
// for _, tve := range tb.Views {
// tve.SetBuf(nil) // automatically disconnects signals, views
// }
tb.New(1)
tb.Filename = ""
tb.ClearChanged()
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 -- good idea to turn autosave off
// for anything that does a block of updates
func (tb *TextBuf) AutoSaveOff() bool {
asv := tb.Autosave
tb.Autosave = false
return asv
}
// AutoSaveRestore restores prior Autosave setting, from AutoSaveOff()
func (tb *TextBuf) AutoSaveRestore(asv bool) {
tb.Autosave = asv
}
// AutoSaveFilename returns the autosave filename
func (tb *TextBuf) AutoSaveFilename() string {
path, fn := filepath.Split(string(tb.Filename))
if fn == "" {
fn = "new_file_" + tb.Nm
}
asfn := filepath.Join(path, "#"+fn+"#")
return asfn
}
// AutoSave does the autosave -- safe to call in a separate goroutine
func (tb *TextBuf) AutoSave() error {
if tb.HasFlag(int(TextBufAutoSaving)) {
return nil
}
tb.SetFlag(int(TextBufAutoSaving))
asfn := tb.AutoSaveFilename()
b := tb.LinesToBytesCopy()
err := ioutil.WriteFile(asfn, b, 0644)
if err != nil {
log.Printf("giv.TextBuf: Could not AutoSave file: %v, error: %v\n", asfn, err)
}
tb.ClearFlag(int(TextBufAutoSaving))
return err
}
// AutoSaveDelete deletes any existing autosave file
func (tb *TextBuf) 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 *TextBuf) 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 *TextBuf) 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 *TextBuf) 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 *TextBuf) 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 *TextBuf) 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("TextBuf AppendTextMarkup: markup text less than appended text: is: %v, should be: %v\n", len(msplt), sz)
el = ints.MinInt(st+len(msplt)-1, el)
}
for ln := st; ln <= el; ln++ {
tb.Markup[ln] = msplt[ln-st]
}
if signal {
tb.TextBufSig.Emit(tb.This(), int64(TextBufInsert), 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 *TextBuf) 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.TextBufSig.Emit(tb.This(), int64(TextBufInsert), tbe)
}
return tbe
}
/////////////////////////////////////////////////////////////////////////////
// Views
// AddView adds a viewer of this buffer -- connects our signals to the viewer
func (tb *TextBuf) AddView(vw *TextView) {
tb.Views = append(tb.Views, vw)
tb.TextBufSig.Connect(vw.This(), TextViewBufSigRecv)
}
// DeleteView removes given viewer from our buffer
func (tb *TextBuf) DeleteView(vw *TextView) {
for i, tve := range tb.Views {
if tve == vw {
tb.Views = append(tb.Views[:i], tb.Views[i+1:]...)
break
}
}
tb.TextBufSig.Disconnect(vw.This())
}
// ViewportFromView returns Viewport from textview, if avail
func (tb *TextBuf) ViewportFromView() *gi.Viewport2D {
if len(tb.Views) > 0 {
return tb.Views[0].Viewport
}
return nil
}
// AutoscrollViews ensures that views are always viewing the end of the buffer
func (tb *TextBuf) AutoScrollViews() {
for _, tv := range tb.Views {
if tv != nil && tv.This() != nil {
tv.CursorPos = tb.EndPos()
tv.ScrollCursorInView()
}
}
}
// RefreshViews does a refresh draw on all views
func (tb *TextBuf) RefreshViews() {
for _, tv := range tb.Views {
if tv != nil && tv.This() != nil {
tv.Refresh()
}
}
}
// BatchUpdateStart call this when starting a batch of updates to the buffer --
// it blocks the window updates for views until all the updates are done,
// and calls AutoSaveOff. Calls UpdateStart on Buf too.
// Returns buf updt, win updt and autosave restore state.
// Must call BatchUpdateEnd at end with the result of this call.
func (tb *TextBuf) BatchUpdateStart() (bufUpdt, winUpdt, autoSave bool) {
tb.Undos.NewGroup()
bufUpdt = tb.UpdateStart()
autoSave = tb.AutoSaveOff()
winUpdt = false
vp := tb.ViewportFromView()
if vp == nil {
return
}
winUpdt = vp.TopUpdateStart()
return
}
// BatchUpdateEnd call to complete BatchUpdateStart
func (tb *TextBuf) BatchUpdateEnd(bufUpdt, winUpdt, autoSave bool) {
tb.AutoSaveRestore(autoSave)
if winUpdt {
vp := tb.ViewportFromView()
if vp != nil {
vp.TopUpdateEnd(winUpdt)
}
}
tb.UpdateEnd(bufUpdt) // nobody listening probably, but flag avail for testing
}
// AddFileNode adds the FileNode to the list or receivers of changes to buffer
func (tb *TextBuf) AddFileNode(fn *FileNode) {
tb.TextBufSig.Connect(fn.This(), FileNodeBufSigRecv)
}
/////////////////////////////////////////////////////////////////////////////
// Accessing Text
// SetByteOffs sets the byte offsets for each line into the raw text
func (tb *TextBuf) 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 *TextBuf) 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 *TextBuf) LinesToBytesCopy() []byte {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
txt := bytes.Join(tb.LineBytes, []byte("\n"))
txt = append(txt, '\n')
return txt
}
// BytesToLines converts current Txt bytes into lines, and initializes markup
// with raw text
func (tb *TextBuf) BytesToLines() {
if len(tb.Txt) == 0 {
tb.New(1)
return
}
tb.LinesMu.Lock()
lns := bytes.Split(tb.Txt, []byte("\n"))
tb.NLines = len(lns)
if len(lns[tb.NLines-1]) == 0 { // lines have lf at end typically
tb.NLines--
lns = lns[:tb.NLines]
}
tb.LinesMu.Unlock()
tb.New(tb.NLines)
tb.LinesMu.Lock()
bo := 0
for ln, txt := range lns {
tb.ByteOffs[ln] = bo
tb.Lines[ln] = bytes.Runes(txt)
tb.LineBytes[ln] = make([]byte, len(txt))
copy(tb.LineBytes[ln], txt)
tb.Markup[ln] = HTMLEscapeRunes(tb.Lines[ln])
bo += len(txt) + 1 // lf
}
tb.TotalBytes = bo
tb.LinesMu.Unlock()
}
// Strings returns the current text as []string array.
// If addNewLn is true, each string line has a \n appended at end.
func (tb *TextBuf) Strings(addNewLn bool) []string {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
str := make([]string, tb.NLines)
for i, l := range tb.Lines {
str[i] = string(l)
if addNewLn {
str[i] += "\n"
}
}
return str
}
// Search looks for a string (no regexp) within buffer,
// with given case-sensitivity, returning number of occurrences
// and specific match position list. column positions are in runes.
func (tb *TextBuf) Search(find []byte, ignoreCase, lexItems bool) (int, []textbuf.Match) {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if lexItems {
tb.MarkupMu.RLock()
defer tb.MarkupMu.RUnlock()
return textbuf.SearchLexItems(tb.Lines, tb.HiTags, find, ignoreCase)
} else {
return textbuf.SearchRuneLines(tb.Lines, find, ignoreCase)
}
}
// SearchRegexp looks for a string (regexp) within buffer,
// returning number of occurrences and specific match position list.
// Column positions are in runes.
func (tb *TextBuf) SearchRegexp(re *regexp.Regexp) (int, []textbuf.Match) {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
return textbuf.SearchByteLinesRegexp(tb.LineBytes, re)
}
// BraceMatch finds the brace, bracket, or parens that is the partner
// of the one passed to function.
func (tb *TextBuf) BraceMatch(r rune, st lex.Pos) (en lex.Pos, found bool) {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
tb.MarkupMu.RLock()
defer tb.MarkupMu.RUnlock()
return lex.BraceMatch(tb.Lines, tb.HiTags, r, st, TextBufMaxScopeLines)
}
/////////////////////////////////////////////////////////////////////////////
// Edits