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