Debian Codegraph @

internal/buffer/buffer.go

raw
1 package buffer
2
3 import (
4 "bufio"
5 "bytes"
6 "crypto/md5"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "os"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "sync"
16 "time"
17
18 luar "layeh.com/gopher-luar"
19
20 dmp "github.com/sergi/go-diff/diffmatchpatch"
21 "github.com/zyedidia/micro/v2/internal/config"
22 ulua "github.com/zyedidia/micro/v2/internal/lua"
23 "github.com/zyedidia/micro/v2/internal/screen"
24 "github.com/zyedidia/micro/v2/internal/util"
25 "github.com/zyedidia/micro/v2/pkg/highlight"
26 "golang.org/x/text/encoding"
27 "golang.org/x/text/encoding/htmlindex"
28 "golang.org/x/text/encoding/unicode"
29 "golang.org/x/text/transform"
30 )
31
32 var (
33 // OpenBuffers is a list of the currently open buffers
34 OpenBuffers []*Buffer
35 // LogBuf is a reference to the log buffer which can be opened with the
36 // `> log` command
37 LogBuf *Buffer
38 )
39
40 // The BufType defines what kind of buffer this is
41 type BufType struct {
42 Kind int
43 Readonly bool // The buffer cannot be edited
44 Scratch bool // The buffer cannot be saved
45 Syntax bool // Syntax highlighting is enabled
46 }
47
48 var (
49 // BTDefault is a default buffer
50 BTDefault = BufType{0, false, false, true}
51 // BTHelp is a help buffer
52 BTHelp = BufType{1, true, true, true}
53 // BTLog is a log buffer
54 BTLog = BufType{2, true, true, false}
55 // BTScratch is a buffer that cannot be saved (for scratch work)
56 BTScratch = BufType{3, false, true, false}
57 // BTRaw is a buffer that shows raw terminal events
58 BTRaw = BufType{4, false, true, false}
59 // BTInfo is a buffer for inputting information
60 BTInfo = BufType{5, false, true, false}
61 // BTStdout is a buffer that only writes to stdout
62 // when closed
63 BTStdout = BufType{6, false, true, true}
64 )
65
66 // SharedBuffer is a struct containing info that is shared among buffers
67 // that have the same file open
68 type SharedBuffer struct {
69 *LineArray
70 // Stores the last modification time of the file the buffer is pointing to
71 ModTime time.Time
72 // Type of the buffer (e.g. help, raw, scratch etc..)
73 Type BufType
74
75 // Path to the file on disk
76 Path string
77 // Absolute path to the file on disk
78 AbsPath string
79 // Name of the buffer on the status line
80 name string
81
82 toStdout bool
83
84 // Settings customized by the user
85 Settings map[string]any
86 // LocalSettings customized by the user for this buffer only
87 LocalSettings map[string]bool
88
89 encoding encoding.Encoding
90
91 Suggestions []string
92 Completions []string
93 CurSuggestion int
94
95 Messages []*Message
96
97 updateDiffTimer *time.Timer
98 diffBase []byte
99 diffBaseLineCount int
100 diffLock sync.RWMutex
101 diff map[int]DiffStatus
102
103 forceKeepBackup bool
104
105 // ReloadDisabled allows the user to disable reloads if they
106 // are viewing a file that is constantly changing
107 ReloadDisabled bool
108
109 isModified bool
110 // Whether or not suggestions can be autocompleted must be shared because
111 // it changes based on how the buffer has changed
112 HasSuggestions bool
113
114 // The Highlighter struct actually performs the highlighting
115 Highlighter *highlight.Highlighter
116 // SyntaxDef represents the syntax highlighting definition being used
117 // This stores the highlighting rules and filetype detection info
118 SyntaxDef *highlight.Def
119
120 ModifiedThisFrame bool
121
122 // Hash of the original buffer -- empty if fastdirty is on
123 origHash [md5.Size]byte
124 }
125
126 func (b *SharedBuffer) insert(pos Loc, value []byte) {
127 b.HasSuggestions = false
128 b.LineArray.insert(pos, value)
129 b.setModified()
130
131 inslines := bytes.Count(value, []byte{'\n'})
132 b.MarkModified(pos.Y, pos.Y+inslines)
133 }
134
135 func (b *SharedBuffer) remove(start, end Loc) []byte {
136 b.HasSuggestions = false
137 defer b.setModified()
138 defer b.MarkModified(start.Y, end.Y)
139 return b.LineArray.remove(start, end)
140 }
141
142 func (b *SharedBuffer) setModified() {
143 if b.Type.Scratch {
144 return
145 }
146
147 if b.Settings["fastdirty"].(bool) {
148 b.isModified = true
149 } else {
150 var buff [md5.Size]byte
151
152 b.calcHash(&buff)
153 b.isModified = buff != b.origHash
154 }
155
156 if b.isModified {
157 b.RequestBackup()
158 } else {
159 b.CancelBackup()
160 }
161 }
162
163 // calcHash calculates md5 hash of all lines in the buffer
164 func (b *SharedBuffer) calcHash(out *[md5.Size]byte) {
165 h := md5.New()
166
167 if len(b.lines) > 0 {
168 h.Write(b.lines[0].data)
169
170 for _, l := range b.lines[1:] {
171 if b.Endings == FFDos {
172 h.Write([]byte{'\r', '\n'})
173 } else {
174 h.Write([]byte{'\n'})
175 }
176 h.Write(l.data)
177 }
178 }
179
180 h.Sum((*out)[:0])
181 }
182
183 // MarkModified marks the buffer as modified for this frame
184 // and performs rehighlighting if syntax highlighting is enabled
185 func (b *SharedBuffer) MarkModified(start, end int) {
186 b.ModifiedThisFrame = true
187
188 start = util.Clamp(start, 0, len(b.lines)-1)
189 end = util.Clamp(end, 0, len(b.lines)-1)
190
191 if b.Settings["syntax"].(bool) && b.SyntaxDef != nil {
192 l := -1
193 for i := start; i <= end; i++ {
194 l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
195 }
196 b.Highlighter.HighlightMatches(b, start, l)
197 }
198
199 for i := start; i <= end; i++ {
200 b.LineArray.invalidateSearchMatches(i)
201 }
202 }
203
204 // DisableReload disables future reloads of this sharedbuffer
205 func (b *SharedBuffer) DisableReload() {
206 b.ReloadDisabled = true
207 }
208
209 const (
210 DSUnchanged = 0
211 DSAdded = 1
212 DSModified = 2
213 DSDeletedAbove = 3
214 )
215
216 type DiffStatus byte
217
218 type Command struct {
219 StartCursor Loc
220 SearchRegex string
221 SearchAfterStart bool
222 }
223
224 var emptyCommand = Command{
225 StartCursor: Loc{-1, -1},
226 SearchRegex: "",
227 SearchAfterStart: false,
228 }
229
230 // Buffer stores the main information about a currently open file including
231 // the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
232 // all the cursors, the syntax highlighting info, the settings for the buffer
233 // and some misc info about modification time and path location.
234 // The syntax highlighting info must be stored with the buffer because the syntax
235 // highlighter attaches information to each line of the buffer for optimization
236 // purposes so it doesn't have to rehighlight everything on every update.
237 // Likewise for the search highlighting.
238 type Buffer struct {
239 *EventHandler
240 *SharedBuffer
241
242 cursors []*Cursor
243 curCursor int
244 StartCursor Loc
245
246 // OptionCallback is called after a buffer option value is changed.
247 // The display module registers its OptionCallback to ensure the buffer window
248 // is properly updated when needed. This is a workaround for the fact that
249 // the buffer module cannot directly call the display's API (it would mean
250 // a circular dependency between packages).
251 OptionCallback func(option string, nativeValue any)
252
253 // The display module registers its own GetVisualX function for getting
254 // the correct visual x location of a cursor when softwrap is used.
255 // This is hacky. Maybe it would be better to move all the visual x logic
256 // from buffer to display, but it would require rewriting a lot of code.
257 GetVisualX func(loc Loc) int
258
259 // Last search stores the last successful search
260 LastSearch string
261 LastSearchRegex bool
262 // HighlightSearch enables highlighting all instances of the last successful search
263 HighlightSearch bool
264
265 // OverwriteMode indicates that we are in overwrite mode (toggled by
266 // Insert key by default) i.e. that typing a character shall replace the
267 // character under the cursor instead of inserting a character before it.
268 OverwriteMode bool
269 }
270
271 // NewBufferFromFileWithCommand opens a new buffer with a given command
272 // If cmd.StartCursor is {-1, -1} the location does not overwrite what the cursor location
273 // would otherwise be (start of file, or saved cursor position if `savecursor` is
274 // enabled)
275 func NewBufferFromFileWithCommand(path string, btype BufType, cmd Command) (*Buffer, error) {
276 var err error
277 filename := path
278 if config.GetGlobalOption("parsecursor").(bool) && cmd.StartCursor.X == -1 && cmd.StartCursor.Y == -1 {
279 var cursorPos []string
280 filename, cursorPos = util.GetPathAndCursorPosition(filename)
281 cmd.StartCursor, err = ParseCursorLocation(cursorPos)
282 if err != nil {
283 cmd.StartCursor = Loc{-1, -1}
284 }
285 }
286
287 filename, err = util.ReplaceHome(filename)
288 if err != nil {
289 return nil, err
290 }
291
292 fileInfo, serr := os.Stat(filename)
293 if serr != nil && !errors.Is(serr, fs.ErrNotExist) {
294 return nil, serr
295 }
296 if serr == nil && fileInfo.IsDir() {
297 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
298 }
299 if serr == nil && !fileInfo.Mode().IsRegular() {
300 return nil, errors.New("Error: " + filename + " is not a regular file and cannot be opened")
301 }
302
303 f, err := os.OpenFile(filename, os.O_WRONLY, 0)
304 readonly := errors.Is(err, fs.ErrPermission)
305 f.Close()
306
307 file, err := os.Open(filename)
308 if err == nil {
309 defer file.Close()
310 }
311
312 var buf *Buffer
313 if errors.Is(err, fs.ErrNotExist) {
314 // File does not exist -- create an empty buffer with that name
315 buf = NewBufferFromString("", filename, btype)
316 } else if err != nil {
317 return nil, err
318 } else {
319 buf = NewBuffer(file, util.FSize(file), filename, btype, cmd)
320 if buf == nil {
321 return nil, errors.New("could not open file")
322 }
323 }
324
325 if readonly && prompt != nil {
326 prompt.Message(fmt.Sprintf("Warning: file is readonly - %s will be attempted when saving", config.GlobalSettings["sucmd"].(string)))
327 // buf.SetOptionNative("readonly", true)
328 }
329
330 return buf, nil
331 }
332
333 // NewBufferFromFile opens a new buffer using the given path
334 // It will also automatically handle `~`, and line/column with filename:l:c
335 // It will return an empty buffer if the path does not exist
336 // and an error if the file is a directory
337 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
338 return NewBufferFromFileWithCommand(path, btype, emptyCommand)
339 }
340
341 // NewBufferFromStringWithCommand creates a new buffer containing the given string
342 // with a cursor loc and a search text
343 func NewBufferFromStringWithCommand(text, path string, btype BufType, cmd Command) *Buffer {
344 return NewBuffer(strings.NewReader(text), int64(len(text)), path, btype, cmd)
345 }
346
347 // NewBufferFromString creates a new buffer containing the given string
348 func NewBufferFromString(text, path string, btype BufType) *Buffer {
349 return NewBuffer(strings.NewReader(text), int64(len(text)), path, btype, emptyCommand)
350 }
351
352 // NewBuffer creates a new buffer from a given reader with a given path
353 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
354 // a new buffer
355 // Places the cursor at startcursor. If startcursor is -1, -1 places the
356 // cursor at an autodetected location (based on savecursor or :LINE:COL)
357 func NewBuffer(r io.Reader, size int64, path string, btype BufType, cmd Command) *Buffer {
358 absPath, err := filepath.Abs(path)
359 if err != nil {
360 absPath = path
361 }
362
363 b := new(Buffer)
364
365 found := false
366 if len(path) > 0 {
367 for _, buf := range OpenBuffers {
368 if buf.AbsPath == absPath && buf.Type != BTInfo {
369 found = true
370 b.SharedBuffer = buf.SharedBuffer
371 b.EventHandler = buf.EventHandler
372 }
373 }
374 }
375
376 hasBackup := false
377 if !found {
378 b.SharedBuffer = new(SharedBuffer)
379 b.Type = btype
380
381 b.AbsPath = absPath
382 b.Path = path
383
384 b.Settings = config.DefaultCommonSettings()
385 b.LocalSettings = make(map[string]bool)
386 for k, v := range config.GlobalSettings {
387 if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
388 // make sure setting is not global-only
389 b.Settings[k] = v
390 }
391 }
392 config.UpdatePathGlobLocals(b.Settings, absPath)
393
394 b.encoding, err = htmlindex.Get(b.Settings["encoding"].(string))
395 if err != nil {
396 b.encoding = unicode.UTF8
397 b.Settings["encoding"] = "utf-8"
398 }
399
400 var ok bool
401 hasBackup, ok = b.ApplyBackup(size)
402
403 if !ok {
404 return NewBufferFromString("", "", btype)
405 }
406 if !hasBackup {
407 reader := bufio.NewReader(transform.NewReader(r, b.encoding.NewDecoder()))
408
409 var ff FileFormat = FFAuto
410
411 if size == 0 {
412 // for empty files, use the fileformat setting instead of
413 // autodetection
414 switch b.Settings["fileformat"] {
415 case "unix":
416 ff = FFUnix
417 case "dos":
418 ff = FFDos
419 }
420 } else {
421 // in case of autodetection treat as locally set
422 b.LocalSettings["fileformat"] = true
423 }
424
425 b.LineArray = NewLineArray(uint64(size), ff, reader)
426 }
427 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
428
429 // The last time this file was modified
430 b.UpdateModTime()
431 }
432
433 if b.Settings["readonly"].(bool) && b.Type == BTDefault {
434 b.Type.Readonly = true
435 }
436
437 switch b.Endings {
438 case FFUnix:
439 b.Settings["fileformat"] = "unix"
440 case FFDos:
441 b.Settings["fileformat"] = "dos"
442 }
443
444 b.UpdateRules()
445 // we know the filetype now, so update per-filetype settings
446 config.UpdateFileTypeLocals(b.Settings, b.Settings["filetype"].(string))
447
448 if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); errors.Is(err, fs.ErrNotExist) {
449 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
450 }
451
452 if cmd.StartCursor.X != -1 && cmd.StartCursor.Y != -1 {
453 b.StartCursor = cmd.StartCursor
454 } else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
455 err := b.Unserialize()
456 if err != nil {
457 screen.TermMessage(err)
458 }
459 }
460
461 b.AddCursor(NewCursor(b, b.StartCursor))
462 b.GetActiveCursor().Relocate()
463
464 if cmd.SearchRegex != "" {
465 match, found, _ := b.FindNext(cmd.SearchRegex, b.Start(), b.End(), b.StartCursor, true, true)
466 if found {
467 if cmd.SearchAfterStart {
468 // Search from current cursor and move it accordingly
469 b.GetActiveCursor().SetSelectionStart(match[0])
470 b.GetActiveCursor().SetSelectionEnd(match[1])
471 b.GetActiveCursor().OrigSelection[0] = b.GetActiveCursor().CurSelection[0]
472 b.GetActiveCursor().OrigSelection[1] = b.GetActiveCursor().CurSelection[1]
473 b.GetActiveCursor().GotoLoc(match[1])
474 }
475 b.LastSearch = cmd.SearchRegex
476 b.LastSearchRegex = true
477 b.HighlightSearch = b.Settings["hlsearch"].(bool)
478 }
479 }
480
481 if !b.Settings["fastdirty"].(bool) && !found {
482 if size > LargeFileThreshold {
483 // If the file is larger than LargeFileThreshold fastdirty needs to be on
484 b.Settings["fastdirty"] = true
485 } else if !hasBackup {
486 // since applying a backup does not save the applied backup to disk, we should
487 // not calculate the original hash based on the backup data
488 b.calcHash(&b.origHash)
489 }
490 }
491
492 err = config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
493 if err != nil {
494 screen.TermMessage(err)
495 }
496
497 OpenBuffers = append(OpenBuffers, b)
498
499 return b
500 }
501
502 // CloseOpenBuffers removes all open buffers
503 func CloseOpenBuffers() {
504 for i, buf := range OpenBuffers {
505 buf.Fini()
506 OpenBuffers[i] = nil
507 }
508 OpenBuffers = OpenBuffers[:0]
509 }
510
511 // Close removes this buffer from the list of open buffers
512 func (b *Buffer) Close() {
513 for i, buf := range OpenBuffers {
514 if b == buf {
515 b.Fini()
516 copy(OpenBuffers[i:], OpenBuffers[i+1:])
517 OpenBuffers[len(OpenBuffers)-1] = nil
518 OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
519 return
520 }
521 }
522 }
523
524 // Fini should be called when a buffer is closed and performs
525 // some cleanup
526 func (b *Buffer) Fini() {
527 if !b.Modified() {
528 b.Serialize()
529 }
530 b.CancelBackup()
531
532 if b.Type == BTStdout {
533 fmt.Fprint(util.Stdout, string(b.Bytes()))
534 }
535 }
536
537 // GetName returns the name that should be displayed in the statusline
538 // for this buffer
539 func (b *Buffer) GetName() string {
540 name := b.name
541 if name == "" {
542 if b.Path == "" {
543 return "No name"
544 }
545 name = b.Path
546 }
547 if b.Settings["basename"].(bool) {
548 return filepath.Base(name)
549 }
550 return name
551 }
552
553 // SetName changes the name for this buffer
554 func (b *Buffer) SetName(s string) {
555 b.name = s
556 }
557
558 // Insert inserts the given string of text at the start location
559 func (b *Buffer) Insert(start Loc, text string) {
560 if !b.Type.Readonly {
561 b.EventHandler.cursors = b.cursors
562 b.EventHandler.active = b.curCursor
563 b.EventHandler.Insert(start, text)
564 }
565 }
566
567 // Remove removes the characters between the start and end locations
568 func (b *Buffer) Remove(start, end Loc) {
569 if !b.Type.Readonly {
570 b.EventHandler.cursors = b.cursors
571 b.EventHandler.active = b.curCursor
572 b.EventHandler.Remove(start, end)
573 }
574 }
575
576 // FileType returns the buffer's filetype
577 func (b *Buffer) FileType() string {
578 return b.Settings["filetype"].(string)
579 }
580
581 // ExternallyModified returns whether the file being edited has
582 // been modified by some external process
583 func (b *Buffer) ExternallyModified() bool {
584 modTime, err := util.GetModTime(b.Path)
585 if err == nil {
586 return modTime != b.ModTime
587 }
588 return false
589 }
590
591 // UpdateModTime updates the modtime of this file
592 func (b *Buffer) UpdateModTime() (err error) {
593 b.ModTime, err = util.GetModTime(b.Path)
594 return
595 }
596
597 // ReOpen reloads the current buffer from disk
598 func (b *Buffer) ReOpen() error {
599 file, err := os.Open(b.Path)
600 if err != nil {
601 return err
602 }
603 defer file.Close()
604
605 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
606 if err != nil {
607 return err
608 }
609
610 reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
611 data, err := io.ReadAll(reader)
612 txt := string(data)
613
614 if err != nil {
615 return err
616 }
617 b.EventHandler.ApplyDiff(txt)
618
619 err = b.UpdateModTime()
620 if !b.Settings["fastdirty"].(bool) {
621 if len(data) > LargeFileThreshold {
622 b.Settings["fastdirty"] = true
623 } else {
624 b.calcHash(&b.origHash)
625 }
626 }
627 b.isModified = false
628 b.RelocateCursors()
629 return err
630 }
631
632 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
633 func (b *Buffer) RelocateCursors() {
634 for _, c := range b.cursors {
635 c.Relocate()
636 }
637 }
638
639 // DeselectCursors removes selection from all cursors
640 func (b *Buffer) DeselectCursors() {
641 for _, c := range b.cursors {
642 c.Deselect(true)
643 }
644 }
645
646 // RuneAt returns the rune at a given location in the buffer
647 func (b *Buffer) RuneAt(loc Loc) rune {
648 line := b.LineBytes(loc.Y)
649 if len(line) > 0 {
650 i := 0
651 for len(line) > 0 {
652 r, _, size := util.DecodeCharacter(line)
653 line = line[size:]
654
655 if i == loc.X {
656 return r
657 }
658
659 i++
660 }
661 }
662 return '\n'
663 }
664
665 // WordAt returns the word around a given location in the buffer
666 func (b *Buffer) WordAt(loc Loc) []byte {
667 if len(b.LineBytes(loc.Y)) == 0 || !util.IsWordChar(b.RuneAt(loc)) {
668 return []byte{}
669 }
670
671 start := loc
672 end := loc.Move(1, b)
673
674 for start.X > 0 && util.IsWordChar(b.RuneAt(start.Move(-1, b))) {
675 start.X--
676 }
677
678 lineLen := util.CharacterCount(b.LineBytes(loc.Y))
679 for end.X < lineLen && util.IsWordChar(b.RuneAt(end)) {
680 end.X++
681 }
682
683 return b.Substr(start, end)
684 }
685
686 // Shared returns if there are other buffers with the same file as this buffer
687 func (b *Buffer) Shared() bool {
688 for _, buf := range OpenBuffers {
689 if buf != b && buf.SharedBuffer == b.SharedBuffer {
690 return true
691 }
692 }
693 return false
694 }
695
696 // Modified returns if this buffer has been modified since
697 // being opened
698 func (b *Buffer) Modified() bool {
699 return b.isModified
700 }
701
702 // Size returns the number of bytes in the current buffer
703 func (b *Buffer) Size() int {
704 nb := 0
705 for i := 0; i < b.LinesNum(); i++ {
706 nb += len(b.LineBytes(i))
707
708 if i != b.LinesNum()-1 {
709 if b.Endings == FFDos {
710 nb++ // carriage return
711 }
712 nb++ // newline
713 }
714 }
715 return nb
716 }
717
718 func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight.Def {
719 data, err := f.Data()
720 if err != nil {
721 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
722 return nil
723 }
724
725 if header == nil {
726 header, err = highlight.MakeHeaderYaml(data)
727 if err != nil {
728 screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
729 return nil
730 }
731 }
732
733 file, err := highlight.ParseFile(data)
734 if err != nil {
735 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
736 return nil
737 }
738
739 syndef, err := highlight.ParseDef(file, header)
740 if err != nil {
741 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
742 return nil
743 }
744
745 return syndef
746 }
747
748 // findRealRuntimeSyntaxDef finds a specific syntax definition
749 // in the user's custom syntax files
750 func findRealRuntimeSyntaxDef(name string, header *highlight.Header) *highlight.Def {
751 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
752 if f.Name() == name {
753 syndef := parseDefFromFile(f, header)
754 if syndef != nil {
755 return syndef
756 }
757 }
758 }
759 return nil
760 }
761
762 // findRuntimeSyntaxDef finds a specific syntax definition
763 // in the built-in syntax files
764 func findRuntimeSyntaxDef(name string, header *highlight.Header) *highlight.Def {
765 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
766 if f.Name() == name {
767 syndef := parseDefFromFile(f, header)
768 if syndef != nil {
769 return syndef
770 }
771 }
772 }
773 return nil
774 }
775
776 func resolveIncludes(syndef *highlight.Def) {
777 includes := highlight.GetIncludes(syndef)
778 if len(includes) == 0 {
779 return
780 }
781
782 var files []*highlight.File
783 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
784 data, err := f.Data()
785 if err != nil {
786 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
787 continue
788 }
789
790 header, err := highlight.MakeHeaderYaml(data)
791 if err != nil {
792 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
793 continue
794 }
795
796 for _, i := range includes {
797 if header.FileType == i {
798 file, err := highlight.ParseFile(data)
799 if err != nil {
800 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
801 continue
802 }
803 files = append(files, file)
804 break
805 }
806 }
807 if len(files) >= len(includes) {
808 break
809 }
810 }
811
812 highlight.ResolveIncludes(syndef, files)
813 }
814
815 // UpdateRules updates the syntax rules and filetype for this buffer
816 // This is called when the colorscheme changes
817 func (b *Buffer) UpdateRules() {
818 if !b.Type.Syntax {
819 return
820 }
821 ft := b.Settings["filetype"].(string)
822 if ft == "off" {
823 b.ClearMatches()
824 b.SyntaxDef = nil
825 return
826 }
827
828 b.SyntaxDef = nil
829
830 // syntaxFileInfo is an internal helper structure
831 // to store properties of one single syntax file
832 type syntaxFileInfo struct {
833 header *highlight.Header
834 fileName string
835 syntaxDef *highlight.Def
836 }
837
838 fnameMatches := []syntaxFileInfo{}
839 headerMatches := []syntaxFileInfo{}
840 syntaxFile := ""
841 foundDef := false
842 var header *highlight.Header
843 // search for the syntax file in the user's custom syntax files
844 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
845 if f.Name() == "default" {
846 continue
847 }
848
849 data, err := f.Data()
850 if err != nil {
851 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
852 continue
853 }
854
855 header, err = highlight.MakeHeaderYaml(data)
856 if err != nil {
857 screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
858 continue
859 }
860
861 matchedFileType := false
862 matchedFileName := false
863 matchedFileHeader := false
864
865 if ft == "unknown" || ft == "" {
866 if header.MatchFileName(b.Path) {
867 matchedFileName = true
868 }
869 if len(fnameMatches) == 0 && header.MatchFileHeader(b.lines[0].data) {
870 matchedFileHeader = true
871 }
872 } else if header.FileType == ft {
873 matchedFileType = true
874 }
875
876 if matchedFileType || matchedFileName || matchedFileHeader {
877 file, err := highlight.ParseFile(data)
878 if err != nil {
879 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
880 continue
881 }
882
883 syndef, err := highlight.ParseDef(file, header)
884 if err != nil {
885 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
886 continue
887 }
888
889 if matchedFileType {
890 b.SyntaxDef = syndef
891 syntaxFile = f.Name()
892 foundDef = true
893 break
894 }
895
896 if matchedFileName {
897 fnameMatches = append(fnameMatches, syntaxFileInfo{header, f.Name(), syndef})
898 } else if matchedFileHeader {
899 headerMatches = append(headerMatches, syntaxFileInfo{header, f.Name(), syndef})
900 }
901 }
902 }
903
904 if !foundDef {
905 // search for the syntax file in the built-in syntax files
906 for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
907 data, err := f.Data()
908 if err != nil {
909 screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
910 continue
911 }
912
913 header, err = highlight.MakeHeader(data)
914 if err != nil {
915 screen.TermMessage("Error reading syntax header file", f.Name(), err)
916 continue
917 }
918
919 if ft == "unknown" || ft == "" {
920 if header.MatchFileName(b.Path) {
921 fnameMatches = append(fnameMatches, syntaxFileInfo{header, f.Name(), nil})
922 }
923 if len(fnameMatches) == 0 && header.MatchFileHeader(b.lines[0].data) {
924 headerMatches = append(headerMatches, syntaxFileInfo{header, f.Name(), nil})
925 }
926 } else if header.FileType == ft {
927 syntaxFile = f.Name()
928 break
929 }
930 }
931 }
932
933 if syntaxFile == "" {
934 matches := fnameMatches
935 if len(matches) == 0 {
936 matches = headerMatches
937 }
938
939 length := len(matches)
940 if length > 0 {
941 signatureMatch := false
942 if length > 1 {
943 // multiple matching syntax files found, try to resolve the ambiguity
944 // using signatures
945 detectlimit := util.IntOpt(b.Settings["detectlimit"])
946 lineCount := len(b.lines)
947 limit := lineCount
948 if detectlimit > 0 && lineCount > detectlimit {
949 limit = detectlimit
950 }
951
952 matchLoop:
953 for _, m := range matches {
954 if m.header.HasFileSignature() {
955 for i := 0; i < limit; i++ {
956 if m.header.MatchFileSignature(b.lines[i].data) {
957 syntaxFile = m.fileName
958 if m.syntaxDef != nil {
959 b.SyntaxDef = m.syntaxDef
960 foundDef = true
961 }
962 header = m.header
963 signatureMatch = true
964 break matchLoop
965 }
966 }
967 }
968 }
969 }
970 if length == 1 || !signatureMatch {
971 syntaxFile = matches[0].fileName
972 if matches[0].syntaxDef != nil {
973 b.SyntaxDef = matches[0].syntaxDef
974 foundDef = true
975 }
976 header = matches[0].header
977 }
978 }
979 }
980
981 if syntaxFile != "" && !foundDef {
982 // we found a syntax file using a syntax header file
983 b.SyntaxDef = findRuntimeSyntaxDef(syntaxFile, header)
984 }
985
986 if b.SyntaxDef != nil {
987 b.Settings["filetype"] = b.SyntaxDef.FileType
988 } else {
989 // search for the default file in the user's custom syntax files
990 b.SyntaxDef = findRealRuntimeSyntaxDef("default", nil)
991 if b.SyntaxDef == nil {
992 // search for the default file in the built-in syntax files
993 b.SyntaxDef = findRuntimeSyntaxDef("default", nil)
994 }
995 }
996
997 if b.SyntaxDef != nil {
998 resolveIncludes(b.SyntaxDef)
999 }
1000
1001 if b.SyntaxDef != nil {
1002 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
1003 if b.Settings["syntax"].(bool) {
1004 go func() {
1005 b.Highlighter.HighlightStates(b)
1006 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
1007 screen.Redraw()
1008 }()
1009 }
1010 }
1011 }
1012
1013 // ClearMatches clears all of the syntax highlighting for the buffer
1014 func (b *Buffer) ClearMatches() {
1015 for i := range b.lines {
1016 b.SetMatch(i, nil)
1017 b.SetState(i, nil)
1018 }
1019 }
1020
1021 // IndentString returns this buffer's indent method (a tabstop or n spaces
1022 // depending on the settings)
1023 func (b *Buffer) IndentString(tabsize int) string {
1024 if b.Settings["tabstospaces"].(bool) {
1025 return util.Spaces(tabsize)
1026 }
1027 return "\t"
1028 }
1029
1030 // SetCursors resets this buffer's cursors to a new list
1031 func (b *Buffer) SetCursors(c []*Cursor) {
1032 b.cursors = c
1033 b.EventHandler.cursors = b.cursors
1034 b.EventHandler.active = b.curCursor
1035 }
1036
1037 // AddCursor adds a new cursor to the list
1038 func (b *Buffer) AddCursor(c *Cursor) {
1039 b.cursors = append(b.cursors, c)
1040 b.EventHandler.cursors = b.cursors
1041 b.EventHandler.active = b.curCursor
1042 b.UpdateCursors()
1043 }
1044
1045 // SetCurCursor sets the current cursor
1046 func (b *Buffer) SetCurCursor(n int) {
1047 b.curCursor = n
1048 }
1049
1050 // GetActiveCursor returns the main cursor in this buffer
1051 func (b *Buffer) GetActiveCursor() *Cursor {
1052 return b.cursors[b.curCursor]
1053 }
1054
1055 // GetCursor returns the nth cursor
1056 func (b *Buffer) GetCursor(n int) *Cursor {
1057 return b.cursors[n]
1058 }
1059
1060 // GetCursors returns the list of cursors in this buffer
1061 func (b *Buffer) GetCursors() []*Cursor {
1062 return b.cursors
1063 }
1064
1065 // NumCursors returns the number of cursors
1066 func (b *Buffer) NumCursors() int {
1067 return len(b.cursors)
1068 }
1069
1070 // MergeCursors merges any cursors that are at the same position
1071 // into one cursor
1072 func (b *Buffer) MergeCursors() {
1073 var cursors []*Cursor
1074 for i := 0; i < len(b.cursors); i++ {
1075 c1 := b.cursors[i]
1076 if c1 != nil {
1077 for j := 0; j < len(b.cursors); j++ {
1078 c2 := b.cursors[j]
1079 if c2 != nil && i != j && c1.Loc == c2.Loc {
1080 b.cursors[j] = nil
1081 }
1082 }
1083 cursors = append(cursors, c1)
1084 }
1085 }
1086
1087 b.cursors = cursors
1088
1089 for i := range b.cursors {
1090 b.cursors[i].Num = i
1091 }
1092
1093 if b.curCursor >= len(b.cursors) {
1094 b.curCursor = len(b.cursors) - 1
1095 }
1096 b.EventHandler.cursors = b.cursors
1097 b.EventHandler.active = b.curCursor
1098 }
1099
1100 // UpdateCursors updates all the cursors indices
1101 func (b *Buffer) UpdateCursors() {
1102 b.EventHandler.cursors = b.cursors
1103 b.EventHandler.active = b.curCursor
1104 for i, c := range b.cursors {
1105 c.Num = i
1106 }
1107 }
1108
1109 func (b *Buffer) RemoveCursor(i int) {
1110 copy(b.cursors[i:], b.cursors[i+1:])
1111 b.cursors[len(b.cursors)-1] = nil
1112 b.cursors = b.cursors[:len(b.cursors)-1]
1113 b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
1114 b.UpdateCursors()
1115 }
1116
1117 // ClearCursors removes all extra cursors
1118 func (b *Buffer) ClearCursors() {
1119 for i := 1; i < len(b.cursors); i++ {
1120 b.cursors[i] = nil
1121 }
1122 b.cursors = b.cursors[:1]
1123 b.UpdateCursors()
1124 b.curCursor = 0
1125 b.GetActiveCursor().Deselect(true)
1126 }
1127
1128 // MoveLinesUp moves the range of lines up one row
1129 func (b *Buffer) MoveLinesUp(start int, end int) {
1130 if start < 1 || start >= end || end > len(b.lines) {
1131 return
1132 }
1133 l := string(b.LineBytes(start - 1))
1134 if end == len(b.lines) {
1135 b.insert(
1136 Loc{
1137 util.CharacterCount(b.lines[end-1].data),
1138 end - 1,
1139 },
1140 []byte{'\n'},
1141 )
1142 }
1143 b.Insert(
1144 Loc{0, end},
1145 l+"\n",
1146 )
1147 b.Remove(
1148 Loc{0, start - 1},
1149 Loc{0, start},
1150 )
1151 }
1152
1153 // MoveLinesDown moves the range of lines down one row
1154 func (b *Buffer) MoveLinesDown(start int, end int) {
1155 if start < 0 || start >= end || end >= len(b.lines) {
1156 return
1157 }
1158 l := string(b.LineBytes(end))
1159 b.Insert(
1160 Loc{0, start},
1161 l+"\n",
1162 )
1163 end++
1164 b.Remove(
1165 Loc{0, end},
1166 Loc{0, end + 1},
1167 )
1168 }
1169
1170 var BracePairs = [][2]rune{
1171 {'(', ')'},
1172 {'{', '}'},
1173 {'[', ']'},
1174 }
1175
1176 func (b *Buffer) findMatchingBrace(braceType [2]rune, start Loc, char rune) (Loc, bool) {
1177 var i int
1178 if char == braceType[0] {
1179 for y := start.Y; y < b.LinesNum(); y++ {
1180 l := []rune(string(b.LineBytes(y)))
1181 xInit := 0
1182 if y == start.Y {
1183 xInit = start.X
1184 }
1185 for x := xInit; x < len(l); x++ {
1186 r := l[x]
1187 if r == braceType[0] {
1188 i++
1189 } else if r == braceType[1] {
1190 i--
1191 if i == 0 {
1192 return Loc{x, y}, true
1193 }
1194 }
1195 }
1196 }
1197 } else if char == braceType[1] {
1198 for y := start.Y; y >= 0; y-- {
1199 l := []rune(string(b.lines[y].data))
1200 xInit := len(l) - 1
1201 if y == start.Y {
1202 xInit = start.X
1203 }
1204 for x := xInit; x >= 0; x-- {
1205 r := l[x]
1206 if r == braceType[1] {
1207 i++
1208 } else if r == braceType[0] {
1209 i--
1210 if i == 0 {
1211 return Loc{x, y}, true
1212 }
1213 }
1214 }
1215 }
1216 }
1217 return start, false
1218 }
1219
1220 // If there is a brace character (for example '{' or ']') at the given start location,
1221 // FindMatchingBrace returns the location of the matching brace for it (for example '}'
1222 // or '['). The second returned value is true if there was no matching brace found
1223 // for given starting location but it was found for the location one character left
1224 // of it. The third returned value is true if the matching brace was found at all.
1225 func (b *Buffer) FindMatchingBrace(start Loc) (Loc, bool, bool) {
1226 // TODO: maybe can be more efficient with utf8 package
1227 curLine := []rune(string(b.LineBytes(start.Y)))
1228
1229 // first try to find matching brace for the given location (it has higher priority)
1230 if start.X >= 0 && start.X < len(curLine) {
1231 startChar := curLine[start.X]
1232
1233 for _, bp := range BracePairs {
1234 if startChar == bp[0] || startChar == bp[1] {
1235 mb, found := b.findMatchingBrace(bp, start, startChar)
1236 if found {
1237 return mb, false, true
1238 }
1239 }
1240 }
1241 }
1242
1243 if b.Settings["matchbraceleft"].(bool) {
1244 // failed to find matching brace for the given location, so try to find matching
1245 // brace for the location one character left of it
1246 if start.X-1 >= 0 && start.X-1 < len(curLine) {
1247 leftChar := curLine[start.X-1]
1248 left := Loc{start.X - 1, start.Y}
1249
1250 for _, bp := range BracePairs {
1251 if leftChar == bp[0] || leftChar == bp[1] {
1252 mb, found := b.findMatchingBrace(bp, left, leftChar)
1253 if found {
1254 return mb, true, true
1255 }
1256 }
1257 }
1258 }
1259 }
1260
1261 return start, false, false
1262 }
1263
1264 // Retab changes all tabs to spaces or vice versa
1265 func (b *Buffer) Retab() {
1266 toSpaces := b.Settings["tabstospaces"].(bool)
1267 tabsize := util.IntOpt(b.Settings["tabsize"])
1268
1269 for i := 0; i < b.LinesNum(); i++ {
1270 l := b.LineBytes(i)
1271
1272 ws := util.GetLeadingWhitespace(l)
1273 if len(ws) != 0 {
1274 if toSpaces {
1275 ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
1276 } else {
1277 ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
1278 }
1279 }
1280
1281 l = bytes.TrimLeft(l, " \t")
1282
1283 b.Lock()
1284 b.lines[i].data = append(ws, l...)
1285 b.Unlock()
1286
1287 b.MarkModified(i, i)
1288 }
1289
1290 b.setModified()
1291 }
1292
1293 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
1294 // into a loc
1295 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
1296 startpos := Loc{0, 0}
1297 var err error
1298
1299 // if no positions are available exit early
1300 if cursorPositions == nil {
1301 return startpos, errors.New("No cursor positions were provided.")
1302 }
1303
1304 startpos.Y, err = strconv.Atoi(cursorPositions[0])
1305 startpos.Y--
1306 if err == nil {
1307 if len(cursorPositions) > 1 {
1308 startpos.X, err = strconv.Atoi(cursorPositions[1])
1309 if startpos.X > 0 {
1310 startpos.X--
1311 }
1312 }
1313 }
1314
1315 return startpos, err
1316 }
1317
1318 // Line returns the string representation of the given line number
1319 func (b *Buffer) Line(i int) string {
1320 return string(b.LineBytes(i))
1321 }
1322
1323 func (b *Buffer) Write(bytes []byte) (n int, err error) {
1324 b.EventHandler.InsertBytes(b.End(), bytes)
1325 return len(bytes), nil
1326 }
1327
1328 func (b *Buffer) updateDiff(synchronous bool) {
1329 b.diffLock.Lock()
1330 defer b.diffLock.Unlock()
1331
1332 b.diff = make(map[int]DiffStatus)
1333
1334 if b.diffBase == nil {
1335 return
1336 }
1337
1338 differ := dmp.New()
1339
1340 if !synchronous {
1341 b.Lock()
1342 }
1343 bytes := b.Bytes()
1344 if !synchronous {
1345 b.Unlock()
1346 }
1347
1348 baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(bytes))
1349 diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
1350 lineN := 0
1351
1352 for _, diff := range diffs {
1353 lineCount := len([]rune(diff.Text))
1354
1355 switch diff.Type {
1356 case dmp.DiffEqual:
1357 lineN += lineCount
1358 case dmp.DiffInsert:
1359 var status DiffStatus
1360 if b.diff[lineN] == DSDeletedAbove {
1361 status = DSModified
1362 } else {
1363 status = DSAdded
1364 }
1365 for i := 0; i < lineCount; i++ {
1366 b.diff[lineN] = status
1367 lineN++
1368 }
1369 case dmp.DiffDelete:
1370 b.diff[lineN] = DSDeletedAbove
1371 }
1372 }
1373 }
1374
1375 // UpdateDiff computes the diff between the diff base and the buffer content.
1376 // The update may be performed synchronously or asynchronously.
1377 // If an asynchronous update is already pending when UpdateDiff is called,
1378 // UpdateDiff does not schedule another update.
1379 func (b *Buffer) UpdateDiff() {
1380 if b.updateDiffTimer != nil {
1381 return
1382 }
1383
1384 lineCount := b.LinesNum()
1385 if b.diffBaseLineCount > lineCount {
1386 lineCount = b.diffBaseLineCount
1387 }
1388
1389 if lineCount < 1000 {
1390 b.updateDiff(true)
1391 } else if lineCount < 30000 {
1392 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1393 b.updateDiffTimer = nil
1394 b.updateDiff(false)
1395 screen.Redraw()
1396 })
1397 } else {
1398 // Don't compute diffs for very large files
1399 b.diffLock.Lock()
1400 b.diff = make(map[int]DiffStatus)
1401 b.diffLock.Unlock()
1402 }
1403 }
1404
1405 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1406 func (b *Buffer) SetDiffBase(diffBase []byte) {
1407 b.diffBase = diffBase
1408 if diffBase == nil {
1409 b.diffBaseLineCount = 0
1410 } else {
1411 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1412 }
1413 b.UpdateDiff()
1414 }
1415
1416 // DiffStatus returns the diff status for a line in the buffer
1417 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1418 b.diffLock.RLock()
1419 defer b.diffLock.RUnlock()
1420 // Note that the zero value for DiffStatus is equal to DSUnchanged
1421 return b.diff[lineN]
1422 }
1423
1424 // FindNextDiffLine returns the line number of the next block of diffs.
1425 // If `startLine` is already in a block of diffs, lines in that block are skipped.
1426 func (b *Buffer) FindNextDiffLine(startLine int, forward bool) (int, error) {
1427 if b.diff == nil {
1428 return 0, errors.New("no diff data")
1429 }
1430 startStatus, ok := b.diff[startLine]
1431 if !ok {
1432 startStatus = DSUnchanged
1433 }
1434 curLine := startLine
1435 for {
1436 curStatus, ok := b.diff[curLine]
1437 if !ok {
1438 curStatus = DSUnchanged
1439 }
1440 if curLine < 0 || curLine > b.LinesNum() {
1441 return 0, errors.New("no next diff hunk")
1442 }
1443 if curStatus != startStatus {
1444 if startStatus != DSUnchanged && curStatus == DSUnchanged {
1445 // Skip over the block of unchanged text
1446 startStatus = DSUnchanged
1447 } else {
1448 return curLine, nil
1449 }
1450 }
1451 if forward {
1452 curLine++
1453 } else {
1454 curLine--
1455 }
1456 }
1457 }
1458
1459 // SearchMatch returns true if the given location is within a match of the last search.
1460 // It is used for search highlighting
1461 func (b *Buffer) SearchMatch(pos Loc) bool {
1462 return b.LineArray.SearchMatch(b, pos)
1463 }
1464
1465 // WriteLog writes a string to the log buffer
1466 func WriteLog(s string) {
1467 LogBuf.EventHandler.Insert(LogBuf.End(), s)
1468 }
1469
1470 // GetLogBuf returns the log buffer
1471 func GetLogBuf() *Buffer {
1472 return LogBuf
1473 }