]> git.lizzy.rs Git - micro.git/blob - internal/buffer/buffer.go
Fix some quality issues (#1914)
[micro.git] / internal / buffer / buffer.go
1 package buffer
2
3 import (
4         "bufio"
5         "bytes"
6         "crypto/md5"
7         "errors"
8         "fmt"
9         "io"
10         "io/ioutil"
11         "os"
12         "path"
13         "path/filepath"
14         "strconv"
15         "strings"
16         "sync"
17         "sync/atomic"
18         "time"
19
20         luar "layeh.com/gopher-luar"
21
22         dmp "github.com/sergi/go-diff/diffmatchpatch"
23         "github.com/zyedidia/micro/v2/internal/config"
24         ulua "github.com/zyedidia/micro/v2/internal/lua"
25         "github.com/zyedidia/micro/v2/internal/screen"
26         "github.com/zyedidia/micro/v2/internal/util"
27         "github.com/zyedidia/micro/v2/pkg/highlight"
28         "golang.org/x/text/encoding/htmlindex"
29         "golang.org/x/text/encoding/unicode"
30         "golang.org/x/text/transform"
31 )
32
33 const backupTime = 8000
34
35 var (
36         // OpenBuffers is a list of the currently open buffers
37         OpenBuffers []*Buffer
38         // LogBuf is a reference to the log buffer which can be opened with the
39         // `> log` command
40         LogBuf *Buffer
41 )
42
43 // The BufType defines what kind of buffer this is
44 type BufType struct {
45         Kind     int
46         Readonly bool // The buffer cannot be edited
47         Scratch  bool // The buffer cannot be saved
48         Syntax   bool // Syntax highlighting is enabled
49 }
50
51 var (
52         // BTDefault is a default buffer
53         BTDefault = BufType{0, false, false, true}
54         // BTHelp is a help buffer
55         BTHelp = BufType{1, true, true, true}
56         // BTLog is a log buffer
57         BTLog = BufType{2, true, true, false}
58         // BTScratch is a buffer that cannot be saved (for scratch work)
59         BTScratch = BufType{3, false, true, false}
60         // BTRaw is is a buffer that shows raw terminal events
61         BTRaw = BufType{4, false, true, false}
62         // BTInfo is a buffer for inputting information
63         BTInfo = BufType{5, false, true, false}
64         // BTStdout is a buffer that only writes to stdout
65         // when closed
66         BTStdout = BufType{6, false, true, true}
67
68         // ErrFileTooLarge is returned when the file is too large to hash
69         // (fastdirty is automatically enabled)
70         ErrFileTooLarge = errors.New("File is too large to hash")
71 )
72
73 // SharedBuffer is a struct containing info that is shared among buffers
74 // that have the same file open
75 type SharedBuffer struct {
76         *LineArray
77         // Stores the last modification time of the file the buffer is pointing to
78         ModTime time.Time
79         // Type of the buffer (e.g. help, raw, scratch etc..)
80         Type BufType
81
82         // Path to the file on disk
83         Path string
84         // Absolute path to the file on disk
85         AbsPath string
86         // Name of the buffer on the status line
87         name string
88
89         toStdout bool
90
91         // Settings customized by the user
92         Settings map[string]interface{}
93
94         Suggestions   []string
95         Completions   []string
96         CurSuggestion int
97
98         Messages []*Message
99
100         updateDiffTimer   *time.Timer
101         diffBase          []byte
102         diffBaseLineCount int
103         diffLock          sync.RWMutex
104         diff              map[int]DiffStatus
105
106         requestedBackup bool
107
108         // ReloadDisabled allows the user to disable reloads if they
109         // are viewing a file that is constantly changing
110         ReloadDisabled bool
111
112         isModified bool
113         // Whether or not suggestions can be autocompleted must be shared because
114         // it changes based on how the buffer has changed
115         HasSuggestions bool
116
117         // The Highlighter struct actually performs the highlighting
118         Highlighter *highlight.Highlighter
119         // SyntaxDef represents the syntax highlighting definition being used
120         // This stores the highlighting rules and filetype detection info
121         SyntaxDef *highlight.Def
122
123         ModifiedThisFrame bool
124
125         // Hash of the original buffer -- empty if fastdirty is on
126         origHash [md5.Size]byte
127 }
128
129 func (b *SharedBuffer) insert(pos Loc, value []byte) {
130         b.isModified = true
131         b.HasSuggestions = false
132         b.LineArray.insert(pos, value)
133
134         inslines := bytes.Count(value, []byte{'\n'})
135         b.MarkModified(pos.Y, pos.Y+inslines)
136 }
137 func (b *SharedBuffer) remove(start, end Loc) []byte {
138         b.isModified = true
139         b.HasSuggestions = false
140         defer b.MarkModified(start.Y, end.Y)
141         return b.LineArray.remove(start, end)
142 }
143
144 // MarkModified marks the buffer as modified for this frame
145 // and performs rehighlighting if syntax highlighting is enabled
146 func (b *SharedBuffer) MarkModified(start, end int) {
147         b.ModifiedThisFrame = true
148
149         if !b.Settings["syntax"].(bool) || b.SyntaxDef == nil {
150                 return
151         }
152
153         start = util.Clamp(start, 0, len(b.lines)-1)
154         end = util.Clamp(end, 0, len(b.lines)-1)
155
156         l := -1
157         for i := start; i <= end; i++ {
158                 l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
159         }
160         b.Highlighter.HighlightMatches(b, start, l)
161 }
162
163 // DisableReload disables future reloads of this sharedbuffer
164 func (b *SharedBuffer) DisableReload() {
165         b.ReloadDisabled = true
166 }
167
168 const (
169         DSUnchanged    = 0
170         DSAdded        = 1
171         DSModified     = 2
172         DSDeletedAbove = 3
173 )
174
175 type DiffStatus byte
176
177 // Buffer stores the main information about a currently open file including
178 // the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
179 // all the cursors, the syntax highlighting info, the settings for the buffer
180 // and some misc info about modification time and path location.
181 // The syntax highlighting info must be stored with the buffer because the syntax
182 // highlighter attaches information to each line of the buffer for optimization
183 // purposes so it doesn't have to rehighlight everything on every update.
184 type Buffer struct {
185         *EventHandler
186         *SharedBuffer
187
188         fini        int32
189         cursors     []*Cursor
190         curCursor   int
191         StartCursor Loc
192 }
193
194 // NewBufferFromFileAtLoc opens a new buffer with a given cursor location
195 // If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
196 // would otherwise be (start of file, or saved cursor position if `savecursor` is
197 // enabled)
198 func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
199         var err error
200         filename := path
201         if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
202                 var cursorPos []string
203                 filename, cursorPos = util.GetPathAndCursorPosition(filename)
204                 cursorLoc, err = ParseCursorLocation(cursorPos)
205                 if err != nil {
206                         cursorLoc = Loc{-1, -1}
207                 }
208         }
209
210         filename, err = util.ReplaceHome(filename)
211         if err != nil {
212                 return nil, err
213         }
214
215         f, err := os.OpenFile(filename, os.O_WRONLY, 0)
216         readonly := os.IsPermission(err)
217         f.Close()
218
219         fileInfo, serr := os.Stat(filename)
220         if serr != nil && !os.IsNotExist(serr) {
221                 return nil, serr
222         }
223         if serr == nil && fileInfo.IsDir() {
224                 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
225         }
226
227         file, err := os.Open(filename)
228         if err == nil {
229                 defer file.Close()
230         }
231
232         var buf *Buffer
233         if os.IsNotExist(err) {
234                 // File does not exist -- create an empty buffer with that name
235                 buf = NewBufferFromString("", filename, btype)
236         } else if err != nil {
237                 return nil, err
238         } else {
239                 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
240         }
241
242         if readonly {
243                 buf.SetOptionNative("readonly", true)
244         }
245
246         return buf, nil
247 }
248
249 // NewBufferFromFile opens a new buffer using the given path
250 // It will also automatically handle `~`, and line/column with filename:l:c
251 // It will return an empty buffer if the path does not exist
252 // and an error if the file is a directory
253 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
254         return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
255 }
256
257 // NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
258 func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
259         return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
260 }
261
262 // NewBufferFromString creates a new buffer containing the given string
263 func NewBufferFromString(text, path string, btype BufType) *Buffer {
264         return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
265 }
266
267 // NewBuffer creates a new buffer from a given reader with a given path
268 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
269 // a new buffer
270 // Places the cursor at startcursor. If startcursor is -1, -1 places the
271 // cursor at an autodetected location (based on savecursor or :LINE:COL)
272 func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
273         absPath, _ := filepath.Abs(path)
274
275         b := new(Buffer)
276
277         found := false
278         if len(path) > 0 {
279                 for _, buf := range OpenBuffers {
280                         if buf.AbsPath == absPath && buf.Type != BTInfo {
281                                 found = true
282                                 b.SharedBuffer = buf.SharedBuffer
283                                 b.EventHandler = buf.EventHandler
284                         }
285                 }
286         }
287
288         hasBackup := false
289         if !found {
290                 b.SharedBuffer = new(SharedBuffer)
291                 b.Type = btype
292
293                 b.AbsPath = absPath
294                 b.Path = path
295
296                 b.Settings = config.DefaultCommonSettings()
297                 for k, v := range config.GlobalSettings {
298                         if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
299                                 // make sure setting is not global-only
300                                 b.Settings[k] = v
301                         }
302                 }
303                 config.InitLocalSettings(b.Settings, path)
304
305                 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
306                 if err != nil {
307                         enc = unicode.UTF8
308                         b.Settings["encoding"] = "utf-8"
309                 }
310
311                 hasBackup = b.ApplyBackup(size)
312
313                 if !hasBackup {
314                         reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
315
316                         var ff FileFormat = FFAuto
317
318                         if size == 0 {
319                                 // for empty files, use the fileformat setting instead of
320                                 // autodetection
321                                 switch b.Settings["fileformat"] {
322                                 case "unix":
323                                         ff = FFUnix
324                                 case "dos":
325                                         ff = FFDos
326                                 }
327                         }
328
329                         b.LineArray = NewLineArray(uint64(size), ff, reader)
330                 }
331                 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
332
333                 // The last time this file was modified
334                 b.UpdateModTime()
335         }
336
337         if b.Settings["readonly"].(bool) && b.Type == BTDefault {
338                 b.Type.Readonly = true
339         }
340
341         switch b.Endings {
342         case FFUnix:
343                 b.Settings["fileformat"] = "unix"
344         case FFDos:
345                 b.Settings["fileformat"] = "dos"
346         }
347
348         b.UpdateRules()
349         // init local settings again now that we know the filetype
350         config.InitLocalSettings(b.Settings, b.Path)
351
352         if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
353                 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
354         }
355
356         if startcursor.X != -1 && startcursor.Y != -1 {
357                 b.StartCursor = startcursor
358         } else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
359                 err := b.Unserialize()
360                 if err != nil {
361                         screen.TermMessage(err)
362                 }
363         }
364
365         b.AddCursor(NewCursor(b, b.StartCursor))
366         b.GetActiveCursor().Relocate()
367
368         if !b.Settings["fastdirty"].(bool) && !found {
369                 if size > LargeFileThreshold {
370                         // If the file is larger than LargeFileThreshold fastdirty needs to be on
371                         b.Settings["fastdirty"] = true
372                 } else if !hasBackup {
373                         // since applying a backup does not save the applied backup to disk, we should
374                         // not calculate the original hash based on the backup data
375                         calcHash(b, &b.origHash)
376                 }
377         }
378
379         err := config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
380         if err != nil {
381                 screen.TermMessage(err)
382         }
383
384         OpenBuffers = append(OpenBuffers, b)
385
386         return b
387 }
388
389 // Close removes this buffer from the list of open buffers
390 func (b *Buffer) Close() {
391         for i, buf := range OpenBuffers {
392                 if b == buf {
393                         b.Fini()
394                         copy(OpenBuffers[i:], OpenBuffers[i+1:])
395                         OpenBuffers[len(OpenBuffers)-1] = nil
396                         OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
397                         return
398                 }
399         }
400 }
401
402 // Fini should be called when a buffer is closed and performs
403 // some cleanup
404 func (b *Buffer) Fini() {
405         if !b.Modified() {
406                 b.Serialize()
407         }
408         b.RemoveBackup()
409
410         if b.Type == BTStdout {
411                 fmt.Fprint(util.Stdout, string(b.Bytes()))
412         }
413
414         atomic.StoreInt32(&(b.fini), int32(1))
415 }
416
417 // GetName returns the name that should be displayed in the statusline
418 // for this buffer
419 func (b *Buffer) GetName() string {
420         name := b.name
421         if name == "" {
422                 if b.Path == "" {
423                         return "No name"
424                 }
425                 name = b.Path
426         }
427         if b.Settings["basename"].(bool) {
428                 return path.Base(name)
429         }
430         return name
431 }
432
433 //SetName changes the name for this buffer
434 func (b *Buffer) SetName(s string) {
435         b.name = s
436 }
437
438 // Insert inserts the given string of text at the start location
439 func (b *Buffer) Insert(start Loc, text string) {
440         if !b.Type.Readonly {
441                 b.EventHandler.cursors = b.cursors
442                 b.EventHandler.active = b.curCursor
443                 b.EventHandler.Insert(start, text)
444
445                 b.RequestBackup()
446         }
447 }
448
449 // Remove removes the characters between the start and end locations
450 func (b *Buffer) Remove(start, end Loc) {
451         if !b.Type.Readonly {
452                 b.EventHandler.cursors = b.cursors
453                 b.EventHandler.active = b.curCursor
454                 b.EventHandler.Remove(start, end)
455
456                 b.RequestBackup()
457         }
458 }
459
460 // FileType returns the buffer's filetype
461 func (b *Buffer) FileType() string {
462         return b.Settings["filetype"].(string)
463 }
464
465 // ExternallyModified returns whether the file being edited has
466 // been modified by some external process
467 func (b *Buffer) ExternallyModified() bool {
468         modTime, err := util.GetModTime(b.Path)
469         if err == nil {
470                 return modTime != b.ModTime
471         }
472         return false
473 }
474
475 // UpdateModTime updates the modtime of this file
476 func (b *Buffer) UpdateModTime() (err error) {
477         b.ModTime, err = util.GetModTime(b.Path)
478         return
479 }
480
481 // ReOpen reloads the current buffer from disk
482 func (b *Buffer) ReOpen() error {
483         file, err := os.Open(b.Path)
484         if err != nil {
485                 return err
486         }
487
488         enc, err := htmlindex.Get(b.Settings["encoding"].(string))
489         if err != nil {
490                 return err
491         }
492
493         reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
494         data, err := ioutil.ReadAll(reader)
495         txt := string(data)
496
497         if err != nil {
498                 return err
499         }
500         b.EventHandler.ApplyDiff(txt)
501
502         err = b.UpdateModTime()
503         if !b.Settings["fastdirty"].(bool) {
504                 calcHash(b, &b.origHash)
505         }
506         b.isModified = false
507         b.RelocateCursors()
508         return err
509 }
510
511 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
512 func (b *Buffer) RelocateCursors() {
513         for _, c := range b.cursors {
514                 c.Relocate()
515         }
516 }
517
518 // RuneAt returns the rune at a given location in the buffer
519 func (b *Buffer) RuneAt(loc Loc) rune {
520         line := b.LineBytes(loc.Y)
521         if len(line) > 0 {
522                 i := 0
523                 for len(line) > 0 {
524                         r, _, size := util.DecodeCharacter(line)
525                         line = line[size:]
526
527                         if i == loc.X {
528                                 return r
529                         }
530
531                         i++
532                 }
533         }
534         return '\n'
535 }
536
537 // Modified returns if this buffer has been modified since
538 // being opened
539 func (b *Buffer) Modified() bool {
540         if b.Type.Scratch {
541                 return false
542         }
543
544         if b.Settings["fastdirty"].(bool) {
545                 return b.isModified
546         }
547
548         var buff [md5.Size]byte
549
550         calcHash(b, &buff)
551         return buff != b.origHash
552 }
553
554 // Size returns the number of bytes in the current buffer
555 func (b *Buffer) Size() int {
556         nb := 0
557         for i := 0; i < b.LinesNum(); i++ {
558                 nb += len(b.LineBytes(i))
559
560                 if i != b.LinesNum()-1 {
561                         if b.Endings == FFDos {
562                                 nb++ // carriage return
563                         }
564                         nb++ // newline
565                 }
566         }
567         return nb
568 }
569
570 // calcHash calculates md5 hash of all lines in the buffer
571 func calcHash(b *Buffer, out *[md5.Size]byte) error {
572         h := md5.New()
573
574         size := 0
575         if len(b.lines) > 0 {
576                 n, e := h.Write(b.lines[0].data)
577                 if e != nil {
578                         return e
579                 }
580                 size += n
581
582                 for _, l := range b.lines[1:] {
583                         n, e = h.Write([]byte{'\n'})
584                         if e != nil {
585                                 return e
586                         }
587                         size += n
588                         n, e = h.Write(l.data)
589                         if e != nil {
590                                 return e
591                         }
592                         size += n
593                 }
594         }
595
596         if size > LargeFileThreshold {
597                 return ErrFileTooLarge
598         }
599
600         h.Sum((*out)[:0])
601         return nil
602 }
603
604 // UpdateRules updates the syntax rules and filetype for this buffer
605 // This is called when the colorscheme changes
606 func (b *Buffer) UpdateRules() {
607         if !b.Type.Syntax {
608                 return
609         }
610         ft := b.Settings["filetype"].(string)
611         if ft == "off" {
612                 return
613         }
614         syntaxFile := ""
615         foundDef := false
616         var header *highlight.Header
617         // search for the syntax file in the user's custom syntax files
618         for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
619                 data, err := f.Data()
620                 if err != nil {
621                         screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
622                         continue
623                 }
624
625                 header, err = highlight.MakeHeaderYaml(data)
626                 if err != nil {
627                         screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
628                 }
629                 file, err := highlight.ParseFile(data)
630                 if err != nil {
631                         screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
632                         continue
633                 }
634
635                 if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
636                         syndef, err := highlight.ParseDef(file, header)
637                         if err != nil {
638                                 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
639                                 continue
640                         }
641                         b.SyntaxDef = syndef
642                         syntaxFile = f.Name()
643                         foundDef = true
644                         break
645                 }
646         }
647
648         // search in the default syntax files
649         for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
650                 data, err := f.Data()
651                 if err != nil {
652                         screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
653                         continue
654                 }
655
656                 header, err = highlight.MakeHeader(data)
657                 if err != nil {
658                         screen.TermMessage("Error reading syntax header file", f.Name(), err)
659                         continue
660                 }
661
662                 if ft == "unknown" || ft == "" {
663                         if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
664                                 syntaxFile = f.Name()
665                                 break
666                         }
667                 } else if header.FileType == ft {
668                         syntaxFile = f.Name()
669                         break
670                 }
671         }
672
673         if syntaxFile != "" && !foundDef {
674                 // we found a syntax file using a syntax header file
675                 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
676                         if f.Name() == syntaxFile {
677                                 data, err := f.Data()
678                                 if err != nil {
679                                         screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
680                                         continue
681                                 }
682
683                                 file, err := highlight.ParseFile(data)
684                                 if err != nil {
685                                         screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
686                                         continue
687                                 }
688
689                                 syndef, err := highlight.ParseDef(file, header)
690                                 if err != nil {
691                                         screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
692                                         continue
693                                 }
694                                 b.SyntaxDef = syndef
695                                 break
696                         }
697                 }
698         }
699
700         if b.SyntaxDef != nil && highlight.HasIncludes(b.SyntaxDef) {
701                 includes := highlight.GetIncludes(b.SyntaxDef)
702
703                 var files []*highlight.File
704                 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
705                         data, err := f.Data()
706                         if err != nil {
707                                 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
708                                 continue
709                         }
710                         header, err := highlight.MakeHeaderYaml(data)
711                         if err != nil {
712                                 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
713                                 continue
714                         }
715
716                         for _, i := range includes {
717                                 if header.FileType == i {
718                                         file, err := highlight.ParseFile(data)
719                                         if err != nil {
720                                                 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
721                                                 continue
722                                         }
723                                         files = append(files, file)
724                                         break
725                                 }
726                         }
727                         if len(files) >= len(includes) {
728                                 break
729                         }
730                 }
731
732                 highlight.ResolveIncludes(b.SyntaxDef, files)
733         }
734
735         if b.Highlighter == nil || syntaxFile != "" {
736                 if b.SyntaxDef != nil {
737                         b.Settings["filetype"] = b.SyntaxDef.FileType
738                 }
739         } else {
740                 b.SyntaxDef = &highlight.EmptyDef
741         }
742
743         if b.SyntaxDef != nil {
744                 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
745                 if b.Settings["syntax"].(bool) {
746                         go func() {
747                                 b.Highlighter.HighlightStates(b)
748                                 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
749                                 screen.Redraw()
750                         }()
751                 }
752         }
753 }
754
755 // ClearMatches clears all of the syntax highlighting for the buffer
756 func (b *Buffer) ClearMatches() {
757         for i := range b.lines {
758                 b.SetMatch(i, nil)
759                 b.SetState(i, nil)
760         }
761 }
762
763 // IndentString returns this buffer's indent method (a tabstop or n spaces
764 // depending on the settings)
765 func (b *Buffer) IndentString(tabsize int) string {
766         if b.Settings["tabstospaces"].(bool) {
767                 return util.Spaces(tabsize)
768         }
769         return "\t"
770 }
771
772 // SetCursors resets this buffer's cursors to a new list
773 func (b *Buffer) SetCursors(c []*Cursor) {
774         b.cursors = c
775         b.EventHandler.cursors = b.cursors
776         b.EventHandler.active = b.curCursor
777 }
778
779 // AddCursor adds a new cursor to the list
780 func (b *Buffer) AddCursor(c *Cursor) {
781         b.cursors = append(b.cursors, c)
782         b.EventHandler.cursors = b.cursors
783         b.EventHandler.active = b.curCursor
784         b.UpdateCursors()
785 }
786
787 // SetCurCursor sets the current cursor
788 func (b *Buffer) SetCurCursor(n int) {
789         b.curCursor = n
790 }
791
792 // GetActiveCursor returns the main cursor in this buffer
793 func (b *Buffer) GetActiveCursor() *Cursor {
794         return b.cursors[b.curCursor]
795 }
796
797 // GetCursor returns the nth cursor
798 func (b *Buffer) GetCursor(n int) *Cursor {
799         return b.cursors[n]
800 }
801
802 // GetCursors returns the list of cursors in this buffer
803 func (b *Buffer) GetCursors() []*Cursor {
804         return b.cursors
805 }
806
807 // NumCursors returns the number of cursors
808 func (b *Buffer) NumCursors() int {
809         return len(b.cursors)
810 }
811
812 // MergeCursors merges any cursors that are at the same position
813 // into one cursor
814 func (b *Buffer) MergeCursors() {
815         var cursors []*Cursor
816         for i := 0; i < len(b.cursors); i++ {
817                 c1 := b.cursors[i]
818                 if c1 != nil {
819                         for j := 0; j < len(b.cursors); j++ {
820                                 c2 := b.cursors[j]
821                                 if c2 != nil && i != j && c1.Loc == c2.Loc {
822                                         b.cursors[j] = nil
823                                 }
824                         }
825                         cursors = append(cursors, c1)
826                 }
827         }
828
829         b.cursors = cursors
830
831         for i := range b.cursors {
832                 b.cursors[i].Num = i
833         }
834
835         if b.curCursor >= len(b.cursors) {
836                 b.curCursor = len(b.cursors) - 1
837         }
838         b.EventHandler.cursors = b.cursors
839         b.EventHandler.active = b.curCursor
840 }
841
842 // UpdateCursors updates all the cursors indicies
843 func (b *Buffer) UpdateCursors() {
844         b.EventHandler.cursors = b.cursors
845         b.EventHandler.active = b.curCursor
846         for i, c := range b.cursors {
847                 c.Num = i
848         }
849 }
850
851 func (b *Buffer) RemoveCursor(i int) {
852         copy(b.cursors[i:], b.cursors[i+1:])
853         b.cursors[len(b.cursors)-1] = nil
854         b.cursors = b.cursors[:len(b.cursors)-1]
855         b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
856         b.UpdateCursors()
857 }
858
859 // ClearCursors removes all extra cursors
860 func (b *Buffer) ClearCursors() {
861         for i := 1; i < len(b.cursors); i++ {
862                 b.cursors[i] = nil
863         }
864         b.cursors = b.cursors[:1]
865         b.UpdateCursors()
866         b.curCursor = 0
867         b.GetActiveCursor().ResetSelection()
868 }
869
870 // MoveLinesUp moves the range of lines up one row
871 func (b *Buffer) MoveLinesUp(start int, end int) {
872         if start < 1 || start >= end || end > len(b.lines) {
873                 return
874         }
875         l := string(b.LineBytes(start - 1))
876         if end == len(b.lines) {
877                 b.insert(
878                         Loc{
879                                 util.CharacterCount(b.lines[end-1].data),
880                                 end - 1,
881                         },
882                         []byte{'\n'},
883                 )
884         }
885         b.Insert(
886                 Loc{0, end},
887                 l+"\n",
888         )
889         b.Remove(
890                 Loc{0, start - 1},
891                 Loc{0, start},
892         )
893 }
894
895 // MoveLinesDown moves the range of lines down one row
896 func (b *Buffer) MoveLinesDown(start int, end int) {
897         if start < 0 || start >= end || end >= len(b.lines) {
898                 return
899         }
900         l := string(b.LineBytes(end))
901         b.Insert(
902                 Loc{0, start},
903                 l+"\n",
904         )
905         end++
906         b.Remove(
907                 Loc{0, end},
908                 Loc{0, end + 1},
909         )
910 }
911
912 var BracePairs = [][2]rune{
913         {'(', ')'},
914         {'{', '}'},
915         {'[', ']'},
916 }
917
918 // FindMatchingBrace returns the location in the buffer of the matching bracket
919 // It is given a brace type containing the open and closing character, (for example
920 // '{' and '}') as well as the location to match from
921 // TODO: maybe can be more efficient with utf8 package
922 // returns the location of the matching brace
923 // if the boolean returned is true then the original matching brace is one character left
924 // of the starting location
925 func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, bool) {
926         curLine := []rune(string(b.LineBytes(start.Y)))
927         startChar := ' '
928         if start.X >= 0 && start.X < len(curLine) {
929                 startChar = curLine[start.X]
930         }
931         leftChar := ' '
932         if start.X-1 >= 0 && start.X-1 < len(curLine) {
933                 leftChar = curLine[start.X-1]
934         }
935         var i int
936         if startChar == braceType[0] || leftChar == braceType[0] {
937                 for y := start.Y; y < b.LinesNum(); y++ {
938                         l := []rune(string(b.LineBytes(y)))
939                         xInit := 0
940                         if y == start.Y {
941                                 if startChar == braceType[0] {
942                                         xInit = start.X
943                                 } else {
944                                         xInit = start.X - 1
945                                 }
946                         }
947                         for x := xInit; x < len(l); x++ {
948                                 r := l[x]
949                                 if r == braceType[0] {
950                                         i++
951                                 } else if r == braceType[1] {
952                                         i--
953                                         if i == 0 {
954                                                 if startChar == braceType[0] {
955                                                         return Loc{x, y}, false, true
956                                                 }
957                                                 return Loc{x, y}, true, true
958                                         }
959                                 }
960                         }
961                 }
962         } else if startChar == braceType[1] || leftChar == braceType[1] {
963                 for y := start.Y; y >= 0; y-- {
964                         l := []rune(string(b.lines[y].data))
965                         xInit := len(l) - 1
966                         if y == start.Y {
967                                 if leftChar == braceType[1] {
968                                         xInit = start.X - 1
969                                 } else {
970                                         xInit = start.X
971                                 }
972                         }
973                         for x := xInit; x >= 0; x-- {
974                                 r := l[x]
975                                 if r == braceType[0] {
976                                         i--
977                                         if i == 0 {
978                                                 if leftChar == braceType[1] {
979                                                         return Loc{x, y}, true, true
980                                                 }
981                                                 return Loc{x, y}, false, true
982                                         }
983                                 } else if r == braceType[1] {
984                                         i++
985                                 }
986                         }
987                 }
988         }
989         return start, true, false
990 }
991
992 // Retab changes all tabs to spaces or vice versa
993 func (b *Buffer) Retab() {
994         toSpaces := b.Settings["tabstospaces"].(bool)
995         tabsize := util.IntOpt(b.Settings["tabsize"])
996         dirty := false
997
998         for i := 0; i < b.LinesNum(); i++ {
999                 l := b.LineBytes(i)
1000
1001                 ws := util.GetLeadingWhitespace(l)
1002                 if len(ws) != 0 {
1003                         if toSpaces {
1004                                 ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
1005                         } else {
1006                                 ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
1007                         }
1008                 }
1009
1010                 l = bytes.TrimLeft(l, " \t")
1011                 b.lines[i].data = append(ws, l...)
1012                 b.MarkModified(i, i)
1013                 dirty = true
1014         }
1015
1016         b.isModified = dirty
1017 }
1018
1019 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
1020 // into a loc
1021 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
1022         startpos := Loc{0, 0}
1023         var err error
1024
1025         // if no positions are available exit early
1026         if cursorPositions == nil {
1027                 return startpos, errors.New("No cursor positions were provided.")
1028         }
1029
1030         startpos.Y, err = strconv.Atoi(cursorPositions[0])
1031         startpos.Y--
1032         if err == nil {
1033                 if len(cursorPositions) > 1 {
1034                         startpos.X, err = strconv.Atoi(cursorPositions[1])
1035                         if startpos.X > 0 {
1036                                 startpos.X--
1037                         }
1038                 }
1039         }
1040
1041         return startpos, err
1042 }
1043
1044 // Line returns the string representation of the given line number
1045 func (b *Buffer) Line(i int) string {
1046         return string(b.LineBytes(i))
1047 }
1048
1049 func (b *Buffer) Write(bytes []byte) (n int, err error) {
1050         b.EventHandler.InsertBytes(b.End(), bytes)
1051         return len(bytes), nil
1052 }
1053
1054 func (b *Buffer) updateDiffSync() {
1055         b.diffLock.Lock()
1056         defer b.diffLock.Unlock()
1057
1058         b.diff = make(map[int]DiffStatus)
1059
1060         if b.diffBase == nil {
1061                 return
1062         }
1063
1064         differ := dmp.New()
1065         baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
1066         diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
1067         lineN := 0
1068
1069         for _, diff := range diffs {
1070                 lineCount := len([]rune(diff.Text))
1071
1072                 switch diff.Type {
1073                 case dmp.DiffEqual:
1074                         lineN += lineCount
1075                 case dmp.DiffInsert:
1076                         var status DiffStatus
1077                         if b.diff[lineN] == DSDeletedAbove {
1078                                 status = DSModified
1079                         } else {
1080                                 status = DSAdded
1081                         }
1082                         for i := 0; i < lineCount; i++ {
1083                                 b.diff[lineN] = status
1084                                 lineN++
1085                         }
1086                 case dmp.DiffDelete:
1087                         b.diff[lineN] = DSDeletedAbove
1088                 }
1089         }
1090 }
1091
1092 // UpdateDiff computes the diff between the diff base and the buffer content.
1093 // The update may be performed synchronously or asynchronously.
1094 // UpdateDiff calls the supplied callback when the update is complete.
1095 // The argument passed to the callback is set to true if and only if
1096 // the update was performed synchronously.
1097 // If an asynchronous update is already pending when UpdateDiff is called,
1098 // UpdateDiff does not schedule another update, in which case the callback
1099 // is not called.
1100 func (b *Buffer) UpdateDiff(callback func(bool)) {
1101         if b.updateDiffTimer != nil {
1102                 return
1103         }
1104
1105         lineCount := b.LinesNum()
1106         if b.diffBaseLineCount > lineCount {
1107                 lineCount = b.diffBaseLineCount
1108         }
1109
1110         if lineCount < 1000 {
1111                 b.updateDiffSync()
1112                 callback(true)
1113         } else if lineCount < 30000 {
1114                 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1115                         b.updateDiffTimer = nil
1116                         b.updateDiffSync()
1117                         callback(false)
1118                 })
1119         } else {
1120                 // Don't compute diffs for very large files
1121                 b.diffLock.Lock()
1122                 b.diff = make(map[int]DiffStatus)
1123                 b.diffLock.Unlock()
1124                 callback(true)
1125         }
1126 }
1127
1128 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1129 func (b *Buffer) SetDiffBase(diffBase []byte) {
1130         b.diffBase = diffBase
1131         if diffBase == nil {
1132                 b.diffBaseLineCount = 0
1133         } else {
1134                 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1135         }
1136         b.UpdateDiff(func(synchronous bool) {
1137                 screen.Redraw()
1138         })
1139 }
1140
1141 // DiffStatus returns the diff status for a line in the buffer
1142 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1143         b.diffLock.RLock()
1144         defer b.diffLock.RUnlock()
1145         // Note that the zero value for DiffStatus is equal to DSUnchanged
1146         return b.diff[lineN]
1147 }
1148
1149 // WriteLog writes a string to the log buffer
1150 func WriteLog(s string) {
1151         LogBuf.EventHandler.Insert(LogBuf.End(), s)
1152 }
1153
1154 // GetLogBuf returns the log buffer
1155 func GetLogBuf() *Buffer {
1156         return LogBuf
1157 }