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
|
package editor
import (
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"unicode"
"unicode/utf8"
"github.com/pkg/errors"
"github.com/prodhe/poe/gapbuffer"
)
const (
BufferFile uint8 = iota
BufferDir
)
// Buffer is a buffer for editing. It uses an underlying gap buffer for storage and manages all things text related, like insert, delete, selection, searching and undo/redo.
//
// Although the underlying buffer is a pure byte slice, Buffer only works with runes and UTF-8.
type Buffer struct {
buf *gapbuffer.Buffer
file *file
what uint8
dirty bool
q0, q1 int // dot/cursor
off int // offset for reading runes in buffer
lastRune rune // save the last read rune
runeBuf []byte // temp buf to read rune at a time from gap buffer
history History // undo/redo stack
}
// initBuffer initialized a nil buffer into the zero value of buffer.
func (b *Buffer) initBuffer() {
if b.buf == nil {
b.buf = &gapbuffer.Buffer{}
}
}
// NewFile sets a filename for the buffer.
func (b *Buffer) NewFile(fn string) {
b.file = &file{name: fn}
}
// ReadFile reads content of the buffer's filename into the buffer.
func (b *Buffer) ReadFile() error {
b.initBuffer()
if b.file == nil || b.file.read {
return nil // silent
}
info, err := os.Stat(b.file.name)
if err != nil {
// if the file exists, print why we could not open it
// otherwise just close silently
if os.IsExist(err) {
return fmt.Errorf("%s", err)
}
return err
}
// name is a directory; list it's content into the buffer
if info.IsDir() {
files, err := ioutil.ReadDir(b.file.name)
if err != nil {
return fmt.Errorf("%s", err)
}
b.what = BufferDir
// list files in dir
for _, f := range files {
dirchar := ""
if f.IsDir() {
dirchar = string(filepath.Separator)
}
fmt.Fprintf(b.buf, "%s%s\n", f.Name(), dirchar)
}
return nil
}
// name is a file
fh, err := os.OpenFile(b.file.name, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return fmt.Errorf("%s", err)
}
defer fh.Close()
if _, err := io.Copy(b.buf, fh); err != nil {
return fmt.Errorf("%s", err)
}
fh.Seek(0, 0)
h := sha256.New()
if _, err := io.Copy(h, fh); err != nil {
return fmt.Errorf("%s", err)
}
b.file.sha256 = fmt.Sprintf("%x", h.Sum(nil))
b.file.mtime = info.ModTime()
b.file.read = true
b.what = BufferFile
return nil
}
// SaveFile writes content of buffer to its filename.
func (b *Buffer) SaveFile() (int, error) {
b.initBuffer()
if b.file == nil || b.file.name == "" {
return 0, errors.New("no filename")
}
if b.what != BufferFile { // can only save file buffers
return 0, nil
}
// check for file existence if we recently changed the file name
// openmasks := os.O_RDWR | os.O_CREATE
// var namechange bool
// if win.Name() != win.NameTag() { // user has changed name
// openmasks |= os.O_EXCL // must not already exist
// namechange = true // to skip sha256 checksum
// }
f, err := os.OpenFile(b.file.name, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
if os.IsExist(err) {
return 0, fmt.Errorf("%s already exists", b.file.name)
}
return 0, err
}
defer f.Close()
//h := sha256.New()
//if _, err := io.Copy(h, f); err != nil {
// return 0, errors.Wrap(err, "sha256")
//}
//hhex := fmt.Sprintf("%x", h.Sum(nil))
// verify checksum if the file is not newly created via a namechange
// if !namechange && hhex != win.file.sha256 {
// return 0, errors.Errorf("file has been modified outside of poe")
// }
n, err := f.WriteAt(b.buf.Bytes(), 0)
if err != nil {
return 0, err
}
f.Truncate(int64(n))
f.Sync()
b.file.sha256 = fmt.Sprintf("%x", sha256.Sum256(b.buf.Bytes()))
info, err := f.Stat()
if err != nil {
return n, err
}
b.file.mtime = info.ModTime()
b.dirty = false
return n, nil
}
// Name returns either the file from disk name or empty string if the buffer has no disk counterpart.
func (b *Buffer) Name() string {
if b.file == nil || b.file.name == "" {
return ""
}
s, _ := filepath.Abs(b.file.name)
return s
}
// WorkDir returns the working directory of the underlying file, ie the absolute path to the file with the last part stripped. If file is a directory, its name is returned as is.
func (b *Buffer) WorkDir() string {
switch b.what {
case BufferFile:
return filepath.Dir(b.Name())
case BufferDir:
return b.Name()
default:
return ""
}
}
// Write implements io.Writer, with the side effect of storing written data into a history stack for undo/redo.
//
// If dot has content, it will be replaced by an initial deletion before inserting the bytes.
func (b *Buffer) Write(p []byte) (int, error) {
b.initBuffer()
// handle replace
if len(b.ReadDot()) > 0 {
b.Delete()
}
// do the actual insertion
c := Change{b.q0, HInsert, p}
n, err := b.commit(c)
if err != nil {
return n, err
}
b.history.Do(c)
b.SeekDot(n, 1) // move dot
if b.what == BufferFile {
b.dirty = true
}
return n, nil
}
// Delete removes current selection in dot. If dot is empty, it selects the previous rune and deletes that.
func (b *Buffer) Delete() (int, error) {
b.initBuffer()
if len(b.ReadDot()) == 0 {
b.q0--
c, _ := b.buf.ByteAt(b.q0)
for !utf8.RuneStart(c) {
b.q0--
c, _ = b.buf.ByteAt(b.q0)
}
if b.q0 < 0 {
return 0, nil
}
}
c := Change{b.q0, HDelete, []byte(b.ReadDot())}
n, err := b.commit(c)
if err != nil {
return n, err
}
b.history.Do(c)
if b.what == BufferFile {
b.dirty = true
}
return n, nil
}
// Len returns the number of bytes in buffer.
func (b *Buffer) Len() int {
b.initBuffer()
return b.buf.Len()
}
// String returns the entire text buffer as a string.
func (b *Buffer) String() string {
b.initBuffer()
return string(b.buf.Bytes())
}
// Dirty returns true if the buffer has changed since last save.
func (b *Buffer) Dirty() bool {
return b.dirty
}
// ReadRune reads a rune from buffer and advances the internal offset. This could be called in sequence to get all runes from buffer. This populates LastRune().
func (b *Buffer) ReadRune() (r rune, size int, err error) {
r, size, err = b.ReadRuneAt(b.off)
b.off += size
b.lastRune = r
return
}
// UnreadRune returns the rune before the current Seek offset and moves the offset to point to that. This could be called in sequence to scan backwards.
func (b *Buffer) UnreadRune() (r rune, size int, err error) {
b.off--
r, size, err = b.ReadRuneAt(b.off)
b.off++
if err != nil {
return
}
b.off -= size
return
}
// ReadRuneAt returns the rune and its size at offset. If the given offset (in byte count) is not a valid rune, it will try to back up until it finds a valid starting point for a rune and return that one.
//
// This is basically a Seek(offset) followed by a ReadRune(), but does not affect the internal offset for future reads.
func (b *Buffer) ReadRuneAt(offset int) (r rune, size int, err error) {
b.initBuffer()
var c byte
c, err = b.buf.ByteAt(offset)
if err != nil {
return 0, 0, err
}
for !utf8.RuneStart(c) {
offset--
c, err = b.buf.ByteAt(offset)
if err != nil {
return 0, 0, err
}
}
if c < utf8.RuneSelf {
return rune(c), 1, nil
}
if cap(b.runeBuf) < 4 {
b.runeBuf = make([]byte, 4) // max length of a rune
}
_, err = b.buf.ReadAt(b.runeBuf, offset)
if err != nil {
return 0, 0, err
}
r, n := utf8.DecodeRune(b.runeBuf)
return r, n, nil
}
// LastRune returns the last rune read by ReadRune().
func (b *Buffer) LastRune() rune {
return b.lastRune
}
// ReadDot returns content of current dot.
func (b *Buffer) ReadDot() string {
b.initBuffer()
if b.q0 == b.q1 {
return ""
}
buf := make([]byte, b.q1-b.q0)
_, err := b.buf.ReadAt(buf, b.q0)
if err != nil {
return ""
}
return string(buf)
}
// Dot returns current offsets for dot.
func (b *Buffer) Dot() (int, int) {
return b.q0, b.q1
}
// Seek implements io.Seeker and sets the internal offset for next ReadRune() or UnreadRune(). If the offset is not a valid rune start, it will backup until it finds one.
func (b *Buffer) Seek(offset, whence int) (int, error) {
b.initBuffer()
b.off = offset
switch whence {
case io.SeekStart:
b.off = offset
case io.SeekCurrent:
b.off += offset
case io.SeekEnd:
b.off = b.Len() + offset
default:
return 0, errors.New("invalid whence")
}
c, _ := b.buf.ByteAt(b.off)
for !utf8.RuneStart(c) {
b.off--
c, _ = b.buf.ByteAt(b.off)
}
return b.off, nil
}
// SeekDot sets the dot to a single offset in the text buffer.
func (b *Buffer) SeekDot(offset, whence int) (int, error) {
switch whence {
case io.SeekStart:
q0, _, err := b.SetDot(offset, offset)
return q0, err
case io.SeekCurrent:
q0, _, err := b.SetDot(b.q0+offset, b.q0+offset)
return q0, err
case io.SeekEnd:
q0, _, err := b.SetDot(b.Len()+offset, b.Len()+offset)
return q0, err
default:
return 0, errors.New("invalid whence")
}
}
// SetDot sets both ends of the dot into an absolute position. It will check the given offsets and adjust them accordingly, so they are not out of bounds or on an invalid rune start. It returns the final offsets. Error is always nil.
func (b *Buffer) SetDot(q0, q1 int) (int, int, error) {
b.initBuffer()
b.q0, b.q1 = q0, q1
// check out of bounds
if b.q0 < 0 {
b.q0 = 0
}
if b.q1 < 0 {
b.q1 = 0
}
if b.q0 >= b.buf.Len() {
b.q0 = b.buf.Len()
}
if b.q1 >= b.buf.Len() {
b.q1 = b.buf.Len()
}
// q0 must never be greater than q1
if b.q0 > b.q1 {
b.q0 = b.q1
}
if b.q1 < b.q0 {
b.q1 = b.q0
}
// set only to valid rune start
var c byte
c, _ = b.buf.ByteAt(b.q0)
for !utf8.RuneStart(c) {
b.q0--
c, _ = b.buf.ByteAt(b.q0)
}
c, _ = b.buf.ByteAt(b.q1)
for !utf8.RuneStart(c) {
b.q1--
c, _ = b.buf.ByteAt(b.q1)
}
return b.q0, b.q1, nil
}
// ExpandDot expands the current selection in positive or negative offset. A positive offset expands forwards and a negative expands backwards. Q is 0 or 1, either the left or the right end of the dot.
func (b *Buffer) ExpandDot(q, offset int) {
if q < 0 || q > 1 {
return
}
if q == 0 {
b.SetDot(b.q0+offset, b.q1)
} else {
b.SetDot(b.q0, b.q1+offset)
}
}
// Select expands current dot into something useful.
//
// If given pos is adjacent to a quote, parenthese, curly brace or bracket, it tries to select into the matching pair.
//
// If on newline, select the whole line.
//
// Otherwise, select word (longest alphanumeric sequence).
func (b *Buffer) Select(offset int) {
offset, _ = b.Seek(offset, io.SeekStart)
start, end := offset, offset
// space
//start -= t.PrevSpace(start)
//end += t.NextSpace(end)
// word
start -= b.PrevWord(start)
end += b.NextWord(end)
// return a single char selection if no word was found
if start == end {
b.Seek(offset, io.SeekStart)
_, size, _ := b.ReadRune()
end += size
}
// Set dot
b.SetDot(start, end)
}
func (b *Buffer) NextSpace(offset int) (n int) {
offset, _ = b.Seek(offset, io.SeekStart)
r, size, err := b.ReadRune()
if err != nil {
return 0
}
for !unicode.IsSpace(r) {
n += size
r, size, err = b.ReadRune()
if err != nil {
if err == io.EOF {
return n
}
return 0
}
}
return n
}
func (b *Buffer) PrevSpace(offset int) (n int) {
offset, _ = b.Seek(offset, io.SeekStart)
r, size, err := b.ReadRuneAt(offset)
if err != nil {
return 0
}
for !unicode.IsSpace(r) {
r, size, err = b.UnreadRune()
if err != nil {
if err == gapbuffer.ErrOutOfRange {
return n
}
}
n += size
}
if n > 0 {
n -= size // remove last iteration
}
return n
}
func (b *Buffer) NextWord(offset int) (n int) {
offset, _ = b.Seek(offset, io.SeekStart)
r, size, err := b.ReadRune()
if err != nil {
return 0
}
for unicode.IsLetter(r) || unicode.IsDigit(r) {
n += size
r, size, err = b.ReadRune()
if err != nil {
if err == io.EOF {
return n
}
return 0
}
}
return n
}
func (b *Buffer) PrevWord(offset int) (n int) {
offset, _ = b.Seek(offset, io.SeekStart)
r, size, _ := b.ReadRuneAt(offset)
for unicode.IsLetter(r) || unicode.IsDigit(r) {
r, size, _ = b.UnreadRune()
n += size
}
if n > 0 {
n -= size // remove last iteration
}
return n
}
// NextDelim returns number of bytes from given offset up until next delimiter.
func (b *Buffer) NextDelim(delim rune, offset int) (n int) {
b.Seek(offset, io.SeekStart)
r, size, err := b.ReadRune()
if err != nil {
return 0
}
for r != delim {
n += size
r, size, err = b.ReadRune()
if err != nil {
if err == io.EOF {
return n
}
return 0
}
}
return n
}
// PrevDelim returns number of bytes from given offset up until next delimiter.
func (b *Buffer) PrevDelim(delim rune, offset int) (n int) {
b.Seek(offset, io.SeekStart)
r, size, err := b.UnreadRune()
if err != nil {
return 0
}
n += size
for r != delim {
r, size, err = b.UnreadRune()
n += size
if err != nil {
if err == gapbuffer.ErrOutOfRange {
return n
}
return 0
}
}
return n
}
func (b *Buffer) Undo() error {
c, err := b.history.Undo()
if err != nil {
return errors.Wrap(err, "undo")
}
b.commit(c)
// highlight text
b.SetDot(c.offset, c.offset+len(c.content))
return nil
}
func (b *Buffer) Redo() error {
c, err := b.history.Redo()
if err != nil {
return errors.Wrap(err, "redo")
}
b.commit(c)
if c.action == HDelete {
b.SetDot(c.offset, c.offset)
} else {
b.SetDot(c.offset+len(c.content), c.offset+len(c.content))
}
return nil
}
func (b *Buffer) commit(c Change) (int, error) {
b.initBuffer()
switch c.action {
case HInsert:
b.buf.Seek(c.offset) // sync gap buffer
n, err := b.buf.Write([]byte(c.content))
if err != nil {
return 0, err
}
return n, err
case HDelete:
n := len(c.content)
b.buf.Seek(c.offset + n) // sync gap buffer
for i := n; i > 0; i-- {
b.buf.Delete() // gap buffer deletes one byte at a time
}
return n, nil
default:
return 0, errors.New("invalid action in change")
}
}
/* History */
type HistoryAction uint8
const (
HInsert HistoryAction = iota
HDelete
)
type Change struct {
offset int
action HistoryAction
content []byte
}
type ChangeSet []*Change
type History struct {
done []Change
recall []Change
}
func (h *History) Do(c Change) {
h.done = append(h.done, c)
h.recall = nil // clear old recall stack on new do
}
func (h *History) Undo() (Change, error) {
if len(h.done) == 0 {
return Change{}, errors.New("no history")
}
lastdone := h.done[len(h.done)-1]
h.recall = append(h.recall, lastdone)
h.done = h.done[:len(h.done)-1] // remove last one
// Reverse the done action so the returned change can be applied directly.
switch lastdone.action {
case HInsert:
lastdone.action = HDelete
case HDelete:
lastdone.action = HInsert
}
return lastdone, nil
}
func (h *History) Redo() (Change, error) {
if len(h.recall) == 0 {
return Change{}, errors.New("no recall history")
}
lastrecall := h.recall[len(h.recall)-1]
h.done = append(h.done, lastrecall)
h.recall = h.recall[:len(h.recall)-1] //remove last one
return lastrecall, nil
}
|