This repository was archived by the owner on Oct 2, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy patheditor.go
More file actions
859 lines (739 loc) · 22.6 KB
/
Copy patheditor.go
File metadata and controls
859 lines (739 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
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
package gvcode
import (
"image"
"io"
"strings"
"time"
"gioui.org/f32"
"gioui.org/gesture"
"gioui.org/io/event"
"gioui.org/io/key"
"gioui.org/io/pointer"
"gioui.org/io/semantic"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/op/clip"
"gioui.org/op/paint"
"gioui.org/text"
"gioui.org/unit"
"github.com/oligo/gvcode/color"
"github.com/oligo/gvcode/gutter"
"github.com/oligo/gvcode/internal/buffer"
gestureExt "github.com/oligo/gvcode/internal/gesture"
"github.com/oligo/gvcode/textview"
)
// Editor implements an editable and scrollable text area.
type Editor struct {
// mode sets the mode of the editor to work in.
mode EditorMode
// text manages the text buffer and provides shaping and cursor positioning
// services.
text *textview.TextView
buffer buffer.TextSource
snippetCtx *snippetContext
// colorPalette configures the color scheme used for syntax highlighting.
colorPalette *color.ColorPalette
// gutterGap specifies the right inset between the gutter and the
// editor text area.
gutterGap unit.Dp
// gutterManager manages multiple gutter providers (line numbers, breakpoints, etc.)
gutterManager *gutter.Manager
// hooks
onPaste BeforePasteHook
onEnterHook EnterHook
onTextInputHook TextInputHook
completor Completion
// last input when the editor received an EditEvent.
lastInput *key.EditEvent
// scratch is a byte buffer that is reused to efficiently read portions of text
// from the textView.
scratch []byte
blinkStart time.Time
// ime tracks the state relevant to input methods.
ime struct {
imeState
scratch []byte
}
dragging bool
dragger gesture.Drag
scroller gestureExt.Scroll
hover gestureExt.Hover
scrollCaret bool
showCaret bool
clicker gesture.Click
pending []EditorEvent
// commands is a registry of key commands.
commands map[key.Name][]keyCommand
// autoInsertions tracks recently inserted closing brackets or quotes.
autoInsertions map[int]rune
// gutterWidth can be used to guide to set the horizontal offset when
// laying out a horizontal scrollbar.
gutterWidth int
// word highlighting state
wordHighlighter wordHighlighter
// selection highlighting state
selectionHighlighter selectionHighlighter
// line ending detected when the editor loads content
lineEnding LineEnding
}
type imeState struct {
selection struct {
rng key.Range
caret key.Caret
}
snippet key.Snippet
start, end int
isComposing bool
composition key.Range
}
type EditorEvent interface {
isEditorEvent()
}
// A ChangeEvent is generated for every user change to the text.
type ChangeEvent struct{}
// A SelectEvent is generated when the user selects some text, or changes the
// selection (e.g. with a shift-click), including if they remove the
// selection. The selected text is not part of the event, on the theory that
// it could be a relatively expensive operation (for a large editor), most
// applications won't actually care about it, and those that do can call
// Editor.SelectedText() (which can be empty).
type SelectEvent struct{}
// A HoverEvent is generated if the pointer hovers and keep still or maybe some
// small movement for some time.
type HoverEvent struct {
PixelOff image.Point
Pos Position
IsCancel bool
}
const (
blinksPerSecond = 1
maxBlinkDuration = 10 * time.Second
)
// initBuffer should be invoked first in every exported function that accesses
// text state. It ensures that the underlying text widget is both ready to use
// and has its fields synced with the editor.
func (e *Editor) initBuffer() {
if e.buffer == nil {
e.text = textview.NewTextView()
e.buffer = e.text.Source()
}
e.text.CaretWidth = unit.Dp(1)
e.wordHighlighter.editor = e
e.selectionHighlighter.editor = e
}
// Update the state of the editor in response to input events. Update consumes editor
// input events until there are no remaining events or an editor event is generated.
// To fully update the state of the editor, callers should call Update until it returns
// false.
func (e *Editor) Update(gtx layout.Context) (EditorEvent, bool) {
e.initBuffer()
event, ok := e.processEvents(gtx)
// Notify IME of selection if it changed.
newSel := e.ime.selection
start, end := e.text.Selection()
newSel.rng = key.Range{
Start: start,
End: end,
}
caretPos, carAsc, carDesc := e.text.CaretInfo()
newSel.caret = key.Caret{
Pos: layout.FPt(caretPos),
Ascent: float32(carAsc),
Descent: float32(carDesc),
}
if newSel != e.ime.selection {
e.ime.selection = newSel
gtx.Execute(key.SelectionCmd{Tag: e, Range: newSel.rng, Caret: newSel.caret})
}
e.updateSnippet(gtx, e.ime.start, e.ime.end)
return event, ok
}
func (e *Editor) Layout(gtx layout.Context, lt *text.Shaper) layout.Dimensions {
for {
_, ok := e.Update(gtx)
if !ok {
break
}
}
// Adjust scrolling for new viewport and layout.
e.text.ScrollRel(0, 0)
if e.scrollCaret {
e.scrollCaret = false
e.text.ScrollToCaret()
}
defer clip.Rect(image.Rectangle{Max: gtx.Constraints.Max}).Push(gtx.Ops).Pop()
e.scroller.Add(gtx.Ops)
if e.colorPalette != nil && e.colorPalette.Background.IsSet() {
e.colorPalette.Background.Op(nil).Add(gtx.Ops)
paint.PaintOp{}.Add(gtx.Ops)
}
return layout.Flex{
Axis: layout.Horizontal,
}.Layout(gtx,
layout.Rigid(func(gtx layout.Context) layout.Dimensions {
if e.gutterManager != nil && e.gutterManager.HasProviders() {
ctx := e.buildGutterContext(gtx, lt)
// Process gutter events
for {
evt, ok := e.gutterManager.Update(gtx)
if !ok {
break
}
e.pending = append(e.pending, GutterEventWrapper{Event: evt})
}
dims := layout.Inset{Right: max(0, e.gutterGap)}.Layout(gtx,
func(gtx layout.Context) layout.Dimensions {
return e.gutterManager.Layout(gtx, ctx)
})
e.gutterWidth = dims.Size.X
// Paint provider-based line highlights (full-width, behind content)
highlights := e.gutterManager.CollectHighlights()
e.paintProviderHighlights(gtx, ctx, highlights)
return dims
}
return layout.Dimensions{}
}),
layout.Flexed(1, func(gtx layout.Context) layout.Dimensions {
e.text.Layout(gtx, lt)
dims := e.layout(gtx)
if e.completor != nil {
e.text.PaintOverlay(gtx, e.completor.Offset(), e.completor.Layout)
}
return dims
}),
)
}
func (e *Editor) layout(gtx layout.Context) layout.Dimensions {
defer clip.Rect(image.Rectangle{Max: gtx.Constraints.Max}).Push(gtx.Ops).Pop()
pointer.CursorText.Add(gtx.Ops)
event.Op(gtx.Ops, e)
//e.scroller.Add(gtx.Ops)
e.clicker.Add(gtx.Ops)
e.dragger.Add(gtx.Ops)
e.hover.Add(gtx.Ops)
e.showCaret = false
if gtx.Focused(e) {
now := gtx.Now
dt := now.Sub(e.blinkStart)
blinking := dt < maxBlinkDuration
const timePerBlink = time.Second / blinksPerSecond
nextBlink := now.Add(timePerBlink/2 - dt%(timePerBlink/2))
if blinking {
gtx.Execute(op.InvalidateCmd{At: nextBlink})
}
e.showCaret = !blinking || dt%timePerBlink < timePerBlink/2
}
semantic.Editor.Add(gtx.Ops)
// determine the various colors to use.
if e.colorPalette == nil {
panic("No color palette is set!")
}
var textColor, selectColor color.Color
if e.colorPalette.Foreground.IsSet() {
textColor = e.colorPalette.Foreground
}
if e.colorPalette.SelectColor.IsSet() {
selectColor = e.colorPalette.SelectColor
} else {
selectColor = textColor.MulAlpha(0x60)
}
if e.Len() > 0 {
e.paintSelection(gtx, selectColor)
e.text.HighlightMatchingBrackets(gtx, selectColor.Op(gtx.Ops))
if e.wordHighlighter.IsDirty() {
e.wordHighlighter.HighlightAtCaret(e.colorPalette.SelectColor)
}
if e.selectionHighlighter.IsDirty() {
e.selectionHighlighter.HighlightSelection(e.colorPalette.SelectColor)
}
e.paintText(gtx, textColor)
e.paintComposition(gtx, textColor)
}
if gtx.Enabled() {
e.paintCaret(gtx, textColor)
}
return layout.Dimensions{Size: gtx.Constraints.Max}
}
// PaintOverlay draws a overlay widget over the main editor area.
func (e *Editor) PaintOverlay(gtx layout.Context, position image.Point, w layout.Widget) {
offset := position.Add(e.text.ScrollOff()).Add(image.Point{X: e.gutterWidth})
e.text.PaintOverlay(gtx, offset, w)
}
// paintSelection paints the contrasting background for selected text using the provided
// material to set the painting material for the selection.
func (e *Editor) paintSelection(gtx layout.Context, material color.Color) {
e.initBuffer()
e.text.PaintSelection(gtx, material.Op(gtx.Ops))
}
// paintText paints the text glyphs using the provided material to set the fill of the
// glyphs.
func (e *Editor) paintText(gtx layout.Context, material color.Color) {
e.initBuffer()
e.text.PaintText(gtx, material.Op(gtx.Ops))
}
// paintCaret paints the text glyphs using the provided material to set the fill material
// of the caret rectangle.
func (e *Editor) paintCaret(gtx layout.Context, material color.Color) {
e.initBuffer()
if !e.showCaret || e.mode == ModeReadOnly {
return
}
e.text.PaintCaret(gtx, material.Op(gtx.Ops))
}
func (e *Editor) paintComposition(gtx layout.Context, material color.Color) {
e.initBuffer()
if !e.ime.isComposing {
return
}
e.text.PaintComposition(gtx, e.ime.composition, material.Op(gtx.Ops), "dash")
}
// Len is the length of the editor contents, in runes.
func (e *Editor) Len() int {
e.initBuffer()
return e.buffer.Len()
}
// Text returns the contents of the editor. This method is not concurrent safe,
// and you should use the Reader returned from GetReader to read from multiple
// goroutines.
//
// Text does not convert \n to \r\n if the detected lineEnding is \r\n, it's the
// caller's responsibility to do the convertion.
func (e *Editor) Text() string {
e.initBuffer()
srcReader := buffer.NewReader(e.text.Source())
e.scratch = srcReader.ReadAll(e.scratch)
return string(e.scratch)
}
// TextView returns the underlying text view for advanced text manipulation.
func (e *Editor) TextView() *textview.TextView {
e.initBuffer()
return e.text
}
// ReadTextBetween reads text between two rune offsets (start inclusive, end exclusive).
func (e *Editor) ReadTextBetween(start, end int) string {
return e.text.ReadTextBetween(start, end)
}
// GetReader returns a [io.ReadSeeker] to the caller to read the text buffer. This
// is the preferred way to read from the editor, especially when reading from
// multiple goroutines.
//
// GetReader does not convert \n to \r\n if the detected lineEnding is \r\n, it's the
// caller's responsibility to do the convertion.
func (e *Editor) GetReader() io.ReadSeeker {
return buffer.NewReader(e.text.Source())
}
// SetText init the editor with content s.
// It also detects the content indent kind, indent size, and the line ending style.
// Internally the editor uses \n for line ending, so it also convert all \r\n to \n
// before populate the internal text buffer.
func (e *Editor) SetText(s string) {
e.initBuffer()
e.resetIME()
clear(e.autoInsertions)
e.lastInput = nil
indent, _, size := GuessIndentation(s)
e.text.SoftTab = indent == Spaces
e.text.TabWidth = size
e.lineEnding = DetectLineEnding(s)
e.text.SetText(StripLineEnding(s))
// Reset xoff and move the caret to the beginning.
e.SetCaret(0, 0)
}
func (e *Editor) resetIME() {
if e.ime.isComposing {
e.buffer.UnGroupOp()
}
e.ime.imeState = imeState{}
}
// CaretPos returns the line & column numbers of the caret.
func (e *Editor) CaretPos() (line, col int) {
e.initBuffer()
return e.text.CaretPos()
}
// CaretCoords returns the coordinates of the caret, relative to the
// editor itself.
func (e *Editor) CaretCoords() f32.Point {
e.initBuffer()
return e.text.CaretCoords()
}
// ConvertPos convert a line/col position to rune offset and its pixel position relative to
// the editor itself.
func (e *Editor) ConvertPos(line, col int) (runeOff int, pos f32.Point) {
e.initBuffer()
runeOff = e.text.ConvertPos(line, col)
pos = e.text.RuneCoords(runeOff)
return
}
// Lines returns the total number of rendered logical lines.
func (e *Editor) Lines() int {
e.initBuffer()
return e.text.Paragraphs()
}
// ReadUntil reads in the specified direction from the current caret position until the
// seperator returns false. It returns the read text.
func (e *Editor) ReadUntil(direction int, seperator func(r rune) bool) string {
return e.text.ReadUntil(direction, seperator)
}
// Delete runes from the caret position. The sign of the argument specifies the
// direction to delete: positive is forward, negative is backward.
//
// If there is a selection, it is deleted and counts as a single grapheme
// cluster.
func (e *Editor) Delete(graphemeClusters int) (deletedRunes int) {
e.initBuffer()
if graphemeClusters == 0 {
return 0
}
if graphemeClusters < 0 {
// update selection based on some rules.
e.onDeleteBackward()
}
start, end := e.text.Selection()
if start != end {
graphemeClusters -= sign(graphemeClusters)
}
// Move caret by the target quantity of clusters.
e.text.MoveCaret(0, graphemeClusters)
// Get the new rune offsets of the selection.
start, end = e.text.Selection()
e.replace(start, end, "")
// Reset xoff.
e.text.MoveCaret(0, 0)
e.ClearSelection()
return end - start
}
// DeleteLine delete the current line, and place the caret at the
// start of the next line.
func (e *Editor) DeleteLine() (deletedRunes int) {
e.initBuffer()
start, end := e.text.SelectedLineRange()
if start == end {
return 0
}
e.replace(start, end, "")
// Reset xoff.
e.text.MoveCaret(0, 0)
e.SetCaret(start, start)
e.ClearSelection()
return end - start
}
// Inert insert text s at the cursor position. If there is a selection,
// it replace the selection with text s.
func (e *Editor) Insert(s string) (insertedRunes int) {
e.initBuffer()
if s == "" {
return
}
s = StripLineEnding(s)
start, end := e.text.Selection()
moves := e.replace(start, end, s)
if end < start {
start = end
}
// Reset xoff.
e.text.MoveCaret(0, 0)
e.SetCaret(start+moves, start+moves)
e.scrollCaret = true
return moves
}
func isSingleLine(s string) bool {
return len(s) > 1 && strings.Count(s, "\n") == 1 && s[len(s)-1] == '\n'
}
// InsertLine insert a line of text before the current line, and place the caret at the
// start of the current line.
//
// This single line insertion is mainly for paste operation after copying/cutting the
// current line(paragraph) when there is no selection, but it can also used outside of
// the editor to insert a entire line(paragraph).
func (e *Editor) InsertLine(s string) (insertedRunes int) {
e.initBuffer()
if s == "" {
return
}
s = StripLineEnding(s)
if isSingleLine(s) && e.text.SelectionLen() == 0 {
// If s is a paragraph of text, insert s between the current line
// and the previous line.
start, end := e.text.SelectedLineRange()
moves := e.replace(start, start, s)
// Reset xoff.
e.text.MoveCaret(0, 0)
e.SetCaret(end, end)
e.scrollCaret = true
return moves
}
return
}
// undo revert the last operation(s).
func (e *Editor) undo() (EditorEvent, bool) {
e.initBuffer()
positions, ok := e.text.Undo()
if !ok {
return nil, false
}
var start, end int
for _, pos := range positions {
start = pos.Start
end = pos.End
}
e.SetCaret(end, start)
return ChangeEvent{}, true
}
// redo revert the last undo operation.
func (e *Editor) redo() (EditorEvent, bool) {
e.initBuffer()
positions, ok := e.text.Redo()
if !ok {
return nil, false
}
var start, end int
for _, pos := range positions {
start = pos.Start
end = pos.End
}
e.SetCaret(end, start)
return ChangeEvent{}, true
}
// replace the text between start and end with s. Indices are in runes.
// It returns the number of runes inserted.
func (e *Editor) replace(start, end int, s string) int {
length := e.text.Len()
if start > end {
start, end = end, start
}
start = min(start, length)
end = min(end, length)
sc := e.text.Replace(start, end, s)
newEnd := start + sc
if len(e.autoInsertions) > 0 && (start != end || sc != 0) {
updated := make(map[int]rune, len(e.autoInsertions))
for pos, r := range e.autoInsertions {
switch {
case pos < start:
updated[pos] = r
case pos >= end:
updated[pos+newEnd-end] = r
}
}
e.autoInsertions = updated
}
adjust := func(pos int) int {
switch {
case newEnd < pos && pos <= end:
pos = newEnd
case end < pos:
diff := newEnd - end
pos = pos + diff
}
return pos
}
e.ime.start = adjust(e.ime.start)
e.ime.end = adjust(e.ime.end)
e.text.UpdateSyntaxTokensOffset(start, end, newEnd)
return sc
}
// ReplaceAll replaces all texts specifed in TextRange with newStr.
// It returns the number of occurrences replaced.
func (e *Editor) ReplaceAll(texts []TextRange, newStr string) int {
if len(texts) <= 0 {
return 0
}
// Traverse in reverse order to prevent match offsets from changing after
// each replace.
e.buffer.GroupOp()
finalPos := 0
for idx := len(texts) - 1; idx >= 0; idx-- {
start, end := texts[idx].Start, texts[idx].End
e.replace(start, end, newStr)
finalPos = start
}
e.buffer.UnGroupOp()
e.SetCaret(finalPos, finalPos)
return len(texts)
}
// MoveCaret moves the caret (aka selection start) and the selection end
// relative to their current positions. Positive distances moves forward,
// negative distances moves backward. Distances are in grapheme clusters,
// which closely match what users perceive as "characters" even when the
// characters are multiple code points long.
func (e *Editor) MoveCaret(startDelta, endDelta int) {
e.initBuffer()
e.text.MoveCaret(startDelta, endDelta)
}
// deleteWord deletes the next word(s) in the specified direction.
// Unlike moveWord, deleteWord treats whitespace as a word itself.
// Positive is forward, negative is backward.
// Absolute values greater than one will delete that many words.
// The selection counts as a single word.
func (e *Editor) deleteWord(distance int) (deletedRunes int) {
if distance == 0 {
return
}
start, end := e.text.Selection()
if start != end {
deletedRunes = e.Delete(1)
distance -= sign(distance)
}
if distance == 0 {
return deletedRunes
}
// split the distance information into constituent parts to be
// used independently.
words, direction := distance, 1
if distance < 0 {
words, direction = distance*-1, -1
}
caret, _ := e.text.Selection()
// atEnd if offset is at or beyond either side of the buffer.
atEnd := func(runes int) bool {
idx := caret + runes*direction
return idx <= 0 || idx >= e.Len()
}
// next returns the appropriate rune given the direction and offset in runes.
next := func(runes int) rune {
idx := caret + runes*direction
if idx < 0 {
idx = 0
} else if idx > e.Len() {
idx = e.Len()
}
var r rune
if direction < 0 {
r, _ = e.buffer.ReadRuneAt(idx - 1)
} else {
r, _ = e.buffer.ReadRuneAt(idx)
}
return r
}
runes := 1
for ii := 0; ii < words; ii++ {
r := next(runes)
isSeperator := e.text.IsWordSeperator(r)
for r := next(runes); (isSeperator == e.text.IsWordSeperator(r)) && !atEnd(runes); r = next(runes) {
runes += 1
}
}
deletedRunes += e.Delete(runes * direction)
return deletedRunes
}
// SelectionLen returns the length of the selection, in runes; it is
// equivalent to utf8.RuneCountInString(e.SelectedText()).
func (e *Editor) SelectionLen() int {
e.initBuffer()
return e.text.SelectionLen()
}
// Selection returns the start and end of the selection, as rune offsets.
// start can be > end.
func (e *Editor) Selection() (start, end int) {
e.initBuffer()
return e.text.Selection()
}
// SelectLines select logical lines starting from the current line(inclusive).
// The number of lines to be selected is specified by totalLines. If backward
// is true, it select lines backward.
func (e *Editor) SelectLines(totalLines int, backward bool) {
e.initBuffer()
start, end := e.text.Selection()
caretStart := min(start, end)
firstLine, _ := e.text.FindParagraph(caretStart)
start, end = e.text.RangeOfLines(firstLine, totalLines, backward)
if start == 0 && end == 0 {
return
}
e.SetCaret(start, end)
}
// SetCaret moves the caret to start, and sets the selection end to end. start
// and end are in runes, and represent offsets into the editor text.
func (e *Editor) SetCaret(start, end int) {
e.initBuffer()
e.text.SetCaret(start, end)
e.scrollCaret = true
e.scroller.Stop()
}
// SelectedText returns the currently selected text (if any) from the editor.
func (e *Editor) SelectedText() string {
e.initBuffer()
e.scratch = e.text.SelectedText(e.scratch)
return string(e.scratch)
}
// ClearSelection clears the selection, by setting the selection end equal to
// the selection start.
func (e *Editor) ClearSelection() {
e.initBuffer()
e.text.ClearSelection()
}
// ScrollRatio returns the viewport's start and end scrolling offset in ratio
// relating to the reandered document coordinate space.
func (e *Editor) ScrollRatio() (minX, maxX float32, minY, maxY float32) {
textDims := e.text.FullDimensions()
visibleDims := e.text.Dimensions()
scrollOff := e.text.ScrollOff()
minX = float32(scrollOff.X) / float32(textDims.Size.X)
maxX = float32(scrollOff.X+visibleDims.Size.X) / float32(textDims.Size.X)
minY = float32(scrollOff.Y) / float32(textDims.Size.Y)
maxY = float32(scrollOff.Y+visibleDims.Size.Y) / float32(textDims.Size.Y)
return
}
// Scroll scrolls the horizontal or vertical scrollbar, using ratio related to
// the rendered document size.
func (e *Editor) Scroll(gtx layout.Context, xRatio, yRatio float32) {
textDims := e.text.FullDimensions().Size
xRatio = min(1.0, xRatio)
xRatio = max(xRatio, -1.0)
yRatio = min(1.0, yRatio)
yRatio = max(yRatio, -1.0)
e.text.ScrollRel(int(float32(textDims.X)*xRatio), int(float32(textDims.Y)*yRatio))
}
// GutterWidth returns the width of the gutter in pixel, which can be used to
// guide to set the horizontal offset when laying out a horizontal scrollbar.
func (e *Editor) GutterWidth() int {
return e.gutterWidth
}
// Deprecated: use Mode() method please.
func (e *Editor) ReadOnly() bool {
return e.mode == ModeReadOnly
}
func (e *Editor) Mode() EditorMode {
return e.mode
}
func (e *Editor) TabStyle() (TabStyle, int) {
if e.text.SoftTab {
return Spaces, e.text.TabWidth
}
return Tabs, e.text.TabWidth
}
func (e *Editor) ColorPalette() *color.ColorPalette {
return e.colorPalette
}
func (e *Editor) DetectedLineEnding() LineEnding {
return e.lineEnding
}
// SetDebug enable or disable the debug mode.
// In debug mode, internal buffer state is printed.
func SetDebug(enable bool) {
buffer.SetDebug(enable)
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
func sign(n int) int {
switch {
case n < 0:
return -1
case n > 0:
return 1
default:
return 0
}
}
func (s ChangeEvent) isEditorEvent() {}
func (s SelectEvent) isEditorEvent() {}
func (s HoverEvent) isEditorEvent() {}
func (s GutterEventWrapper) isEditorEvent() {}
// gutterEventWrapper wraps gutter events to implement EditorEvent.
type GutterEventWrapper struct {
Event gutter.GutterEvent
}