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