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