-
Notifications
You must be signed in to change notification settings - Fork 0
/
textbuf.go
2524 lines (2306 loc) · 72.4 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"
"strings"
"sync"
"time"
"github.com/goki/gi/complete"
"github.com/goki/gi/filecat"
"github.com/goki/gi/gi"
"github.com/goki/gi/histyle"
"github.com/goki/gi/spell"
"github.com/goki/ki"
"github.com/goki/ki/indent"
"github.com/goki/ki/ints"
"github.com/goki/ki/kit"
"github.com/goki/ki/nptime"
"github.com/goki/ki/runes"
"github.com/goki/pi/lex"
"github.com/goki/pi/pi"
"github.com/goki/pi/token"
"github.com/pmezard/go-difflib/difflib"
)
// TextBufOpts contains options for TextBufs -- contains everything necessary to
// conditionalize editing of a given text file
type TextBufOpts struct {
SpaceIndent bool `desc:"use spaces, not tabs, for indentation -- tab-size property in TextStyle has the tab size, used for either tabs or spaces"`
TabSize int `desc:"size of a tab, in chars -- also determines indent level for space indent"`
AutoIndent bool `desc:"auto-indent on newline (enter) or tab"`
LineNos bool `desc:"show line numbers at left end of editor"`
Completion bool `desc:"use the completion system to suggest options while typing"`
SpellCorrect bool `desc:"use spell checking to suggest corrections while typing"`
EmacsUndo bool `desc:"use emacs-style undo, where after a non-undo command, all the current undo actions are added to the undo stack, such that a subsequent undo is actually a redo"`
DepthColor bool `desc:"colorize the background according to nesting depth"`
CommentLn string `desc:"character(s) that start a single-line comment -- if empty then multi-line comment syntax will be used"`
CommentSt string `desc:"character(s) that start a multi-line comment or one that requires both start and end"`
CommentEd string `desc:"character(s) that end a multi-line comment or one that requires both start and end"`
}
// MaxScopeLines is the maximum lines to search for a scope marker, e.g. '}'
var MaxScopeLines = 100
// CommentStrs returns the comment start and end strings, using line-based CommentLn first if set
// and falling back on multi-line / general purpose start / end syntax
func (tb *TextBufOpts) CommentStrs() (comst, comed string) {
comst = tb.CommentLn
if comst == "" {
comst = tb.CommentSt
comed = tb.CommentEd
}
return
}
// IndentChar returns the indent character based on SpaceIndent option
func (tb *TextBufOpts) IndentChar() indent.Char {
if tb.SpaceIndent {
return indent.Space
}
return indent.Tab
}
// ConfigSupported configures options based on the supported language info in GoPi
// returns true if supported
func (tb *TextBufOpts) ConfigSupported(sup filecat.Supported) bool {
if sup == filecat.NoSupport {
return false
}
lp, ok := pi.StdLangProps[sup]
if !ok {
return false
}
tb.CommentLn = lp.CommentLn
tb.CommentSt = lp.CommentSt
tb.CommentEd = lp.CommentEd
for _, flg := range lp.Flags {
switch flg {
case pi.IndentSpace:
tb.SpaceIndent = true
case pi.IndentTab:
tb.SpaceIndent = false
}
}
return true
}
// 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 TextBufOpts `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.FileState `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"`
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"`
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"`
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 []*TextBufEdit `json:"-" xml:"-" desc:"undo stack of edits"`
UndoUndos []*TextBufEdit `json:"-" xml:"-" desc:"undo stack of *undo* edits -- added to "`
UndoPos int `json:"-" xml:"-" desc:"undo position"`
PosHistory []TextPos `json:"-" xml:"-" desc:"history of cursor positions -- can move back through them"`
Complete *gi.Complete `json:"-" xml:"-" desc:"functions and data for text completion"`
SpellCorrect *gi.SpellCorrect `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)
var TextBufProps = ki.Props{
"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
// TextBufEdit describing change -- the TextBuf always reflects the
// current state *after* the edit.
TextBufInsert
// TextBufDelete signals that some text was deleted -- data is
// TextBufEdit 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
TextBufSignalsN
)
//go:generate stringer -type=TextBufSignals
// these extend NodeBase NodeFlags to hold TextBuf state
const (
// TextBufAutoSaving is used in atomically safe way to protect autosaving
TextBufAutoSaving gi.NodeFlags = 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
)
// 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.Refresh()
}
// EditDone finalizes any current editing, sends signal
func (tb *TextBuf) EditDone() {
if tb.IsChanged() {
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 histyle.StyleName) {
tb.MarkupMu.Lock()
tb.Hi.Style = 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.AutoIndent = true
tb.Opts.TabSize = 4
}
// Refresh signals any views to refresh views
func (tb *TextBuf) Refresh() {
tb.TextBufSig.Emit(tb.This(), int64(TextBufNew), tb.Txt)
}
// 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.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(&tb.Lines, 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.SpellCorrect == nil {
tb.SetSpellCorrect(tb, SpellCorrectEdit)
}
if tb.Complete == nil {
tb.SetCompleter(&tb.PiState, pi.Complete, pi.CompleteEdit)
}
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",
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", "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()}, true, false, nil, nil)
log.Println(err)
return err
}
tb.SetName(string(filename)) // todo: modify in any way?
// markup the first 100 lines
mxhi := ints.MinInt(100, tb.NLines-1)
tb.MarkupLinesLock(0, mxhi)
// update views
tb.TextBufSig.Emit(tb.This(), int64(TextBufNew), tb.Txt)
// do slow full update in background
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
}
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()}, true, false, nil, nil)
}
log.Println(err)
return false
}
tb.Stat() // "own" the new file..
diffs := tb.DiffBufs(ob)
tb.PatchFromBuf(ob, diffs, true) // true = send sigs for each update -- better than full, assuming changes are minor
tb.ClearChanged()
tb.AutoSaveDelete()
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()}, true, false, nil, nil)
log.Println(err)
} else {
tb.Filename = filename
tb.SetName(string(filename)) // todo: modify in any way?
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..
}
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() TextPos {
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
if tb.NLines == 0 {
return TextPosZero
}
ed := TextPos{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, saveUndo, signal bool) *TextBufEdit {
if len(text) == 0 {
return &TextBufEdit{}
}
ed := tb.EndPos()
return tb.InsertText(ed, text, saveUndo, 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, saveUndo, signal bool) *TextBufEdit {
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, saveUndo, 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, saveUndo, signal bool) *TextBufEdit {
if len(text) == 0 {
return &TextBufEdit{}
}
ed := tb.EndPos()
tbe := tb.InsertText(ed, text, saveUndo, 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, saveUndo, signal bool) *TextBufEdit {
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, saveUndo, 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) {
bufUpdt = tb.UpdateStart()
autoSave = tb.AutoSaveOff()
winUpdt = false
vp := tb.ViewportFromView()
if vp == nil || vp.Win == nil {
return
}
winUpdt = vp.Win.UpdateStart()
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.Win != nil {
vp.Win.UpdateEnd(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() {
if tb.NLines == 0 {
if tb.Txt != nil {
tb.Txt = tb.Txt[:0]
}
return
}
tb.Txt = tb.LinesToBytesCopy()
// the following does not work because LineBytes is just pointers into txt!
// tb.SetByteOffs()
// totsz := tb.TotalBytes
// if cap(tb.Txt) < totsz {
// tb.Txt = make([]byte, totsz)
// } else {
// tb.Txt = tb.Txt[:totsz]
// }
// for ln := range tb.Lines {
// bo := tb.ByteOffs[ln]
// lsz := len(tb.LineBytes[ln])
// copy(tb.Txt[bo:bo+lsz], tb.LineBytes[ln])
// tb.Txt[bo+lsz] = '\n'
// }
}
// 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] = tb.LineBytes[ln]
bo += len(txt) + 1 // lf
}
tb.TotalBytes = bo
tb.LinesMu.Unlock()
}
/////////////////////////////////////////////////////////////////////////////
// Search
// FileSearchMatch records one match for search within file
type FileSearchMatch struct {
Reg TextRegion `desc:"region surrounding the match"`
Text []byte `desc:"text surrounding the match, at most FileSearchContext on either side (within a single line)"`
}
// FileSearchContext is how much text to include on either side of the search match
var FileSearchContext = 30
var mst = []byte("<mark>")
var mstsz = len(mst)
var med = []byte("</mark>")
var medsz = len(med)
// NewFileSearchMatch returns a new FileSearchMatch entry for given rune line with match starting
// at st and ending before ed, on given line
func NewFileSearchMatch(rn []rune, st, ed, ln int) FileSearchMatch {
sz := len(rn)
reg := NewTextRegion(ln, st, ln, ed)
cist := ints.MaxInt(st-FileSearchContext, 0)
cied := ints.MinInt(ed+FileSearchContext, sz)
sctx := []byte(string(rn[cist:st]))
fstr := []byte(string(rn[st:ed]))
ectx := []byte(string(rn[ed:cied]))
tlen := mstsz + medsz + len(sctx) + len(fstr) + len(ectx)
txt := make([]byte, tlen)
copy(txt, sctx)
ti := st - cist
copy(txt[ti:], mst)
ti += mstsz
copy(txt[ti:], fstr)
ti += len(fstr)
copy(txt[ti:], med)
ti += medsz
copy(txt[ti:], ectx)
return FileSearchMatch{Reg: reg, Text: txt}
}
// 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 bool) (int, []FileSearchMatch) {
fr := bytes.Runes(find)
fsz := len(fr)
if fsz == 0 {
return 0, nil
}
tb.LinesMu.RLock()
defer tb.LinesMu.RUnlock()
cnt := 0
var matches []FileSearchMatch
for ln, rn := range tb.Lines {
sz := len(rn)
ci := 0
for ci < sz {
var i int
if ignoreCase {
i = runes.IndexFold(rn[ci:], fr)
} else {
i = runes.Index(rn[ci:], fr)