]> git.lizzy.rs Git - micro.git/blob - internal/buffer/buffer.go
Move multi-cursors correctly after newlines
[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         // 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         log.Println("insert", string(value), pos.Y, pos.Y+inslines)
132         b.MarkModified(pos.Y, pos.Y+inslines)
133 }
134 func (b *SharedBuffer) remove(start, end Loc) []byte {
135         b.isModified = true
136         b.HasSuggestions = false
137         defer b.MarkModified(start.Y, end.Y)
138         return b.LineArray.remove(start, end)
139 }
140
141 // MarkModified marks the buffer as modified for this frame
142 // and performs rehighlighting if syntax highlighting is enabled
143 func (b *SharedBuffer) MarkModified(start, end int) {
144         b.ModifiedThisFrame = true
145
146         if !b.Settings["syntax"].(bool) || b.SyntaxDef == nil {
147                 return
148         }
149
150         log.Println("Modified", start, end, len(b.lines))
151         start = util.Clamp(start, 0, len(b.lines))
152         end = util.Clamp(end, 0, len(b.lines))
153
154         l := -1
155         log.Println("Modified", start, end)
156         for i := start; i <= end; i++ {
157                 l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
158         }
159         b.Highlighter.HighlightMatches(b, start, l+1)
160 }
161
162 // DisableReload disables future reloads of this sharedbuffer
163 func (b *SharedBuffer) DisableReload() {
164         b.ReloadDisabled = true
165 }
166
167 const (
168         DSUnchanged    = 0
169         DSAdded        = 1
170         DSModified     = 2
171         DSDeletedAbove = 3
172 )
173
174 type DiffStatus byte
175
176 // Buffer stores the main information about a currently open file including
177 // the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
178 // all the cursors, the syntax highlighting info, the settings for the buffer
179 // and some misc info about modification time and path location.
180 // The syntax highlighting info must be stored with the buffer because the syntax
181 // highlighter attaches information to each line of the buffer for optimization
182 // purposes so it doesn't have to rehighlight everything on every update.
183 type Buffer struct {
184         *EventHandler
185         *SharedBuffer
186
187         cursors     []*Cursor
188         curCursor   int
189         StartCursor Loc
190 }
191
192 // NewBufferFromFile opens a new buffer using the given path
193 // It will also automatically handle `~`, and line/column with filename:l:c
194 // It will return an empty buffer if the path does not exist
195 // and an error if the file is a directory
196 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
197         var err error
198         filename, cursorPos := util.GetPathAndCursorPosition(path)
199         filename, err = util.ReplaceHome(filename)
200         if err != nil {
201                 return nil, err
202         }
203
204         file, err := os.Open(filename)
205         fileInfo, _ := os.Stat(filename)
206
207         if err == nil && fileInfo.IsDir() {
208                 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
209         }
210
211         defer file.Close()
212
213         cursorLoc, cursorerr := ParseCursorLocation(cursorPos)
214         if cursorerr != nil {
215                 cursorLoc = Loc{-1, -1}
216         }
217
218         var buf *Buffer
219         if err != nil {
220                 // File does not exist -- create an empty buffer with that name
221                 buf = NewBufferFromString("", filename, btype)
222         } else {
223                 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
224         }
225
226         return buf, nil
227 }
228
229 // NewBufferFromString creates a new buffer containing the given string
230 func NewBufferFromString(text, path string, btype BufType) *Buffer {
231         return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
232 }
233
234 // NewBuffer creates a new buffer from a given reader with a given path
235 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
236 // a new buffer
237 // Places the cursor at startcursor. If startcursor is -1, -1 places the
238 // cursor at an autodetected location (based on savecursor or :LINE:COL)
239 func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
240         absPath, _ := filepath.Abs(path)
241
242         b := new(Buffer)
243
244         found := false
245         if len(path) > 0 {
246                 for _, buf := range OpenBuffers {
247                         if buf.AbsPath == absPath && buf.Type != BTInfo {
248                                 found = true
249                                 b.SharedBuffer = buf.SharedBuffer
250                                 b.EventHandler = buf.EventHandler
251                         }
252                 }
253         }
254
255         if !found {
256                 b.SharedBuffer = new(SharedBuffer)
257                 b.Type = btype
258
259                 b.AbsPath = absPath
260                 b.Path = path
261
262                 b.Settings = config.DefaultCommonSettings()
263                 for k, v := range config.GlobalSettings {
264                         if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
265                                 // make sure setting is not global-only
266                                 b.Settings[k] = v
267                         }
268                 }
269                 config.InitLocalSettings(b.Settings, path)
270
271                 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
272                 if err != nil {
273                         enc = unicode.UTF8
274                         b.Settings["encoding"] = "utf-8"
275                 }
276
277                 hasBackup := b.ApplyBackup(size)
278
279                 if !hasBackup {
280                         reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
281                         b.LineArray = NewLineArray(uint64(size), FFAuto, reader)
282                 }
283                 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
284
285                 // The last time this file was modified
286                 b.UpdateModTime()
287         }
288
289         if b.Settings["readonly"].(bool) && b.Type == BTDefault {
290                 b.Type.Readonly = true
291         }
292
293         switch b.Endings {
294         case FFUnix:
295                 b.Settings["fileformat"] = "unix"
296         case FFDos:
297                 b.Settings["fileformat"] = "dos"
298         }
299
300         b.UpdateRules()
301         // init local settings again now that we know the filetype
302         config.InitLocalSettings(b.Settings, b.Path)
303
304         if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
305                 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
306         }
307
308         if startcursor.X != -1 && startcursor.Y != -1 {
309                 b.StartCursor = startcursor
310         } else {
311                 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
312                         err := b.Unserialize()
313                         if err != nil {
314                                 screen.TermMessage(err)
315                         }
316                 }
317         }
318
319         b.AddCursor(NewCursor(b, b.StartCursor))
320         b.GetActiveCursor().Relocate()
321
322         if !b.Settings["fastdirty"].(bool) && !found {
323                 if size > LargeFileThreshold {
324                         // If the file is larger than LargeFileThreshold fastdirty needs to be on
325                         b.Settings["fastdirty"] = true
326                 } else {
327                         calcHash(b, &b.origHash)
328                 }
329         }
330
331         err := config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
332         if err != nil {
333                 screen.TermMessage(err)
334         }
335
336         OpenBuffers = append(OpenBuffers, b)
337
338         return b
339 }
340
341 // Close removes this buffer from the list of open buffers
342 func (b *Buffer) Close() {
343         for i, buf := range OpenBuffers {
344                 if b == buf {
345                         b.Fini()
346                         copy(OpenBuffers[i:], OpenBuffers[i+1:])
347                         OpenBuffers[len(OpenBuffers)-1] = nil
348                         OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
349                         return
350                 }
351         }
352 }
353
354 // Fini should be called when a buffer is closed and performs
355 // some cleanup
356 func (b *Buffer) Fini() {
357         if !b.Modified() {
358                 b.Serialize()
359         }
360         b.RemoveBackup()
361 }
362
363 // GetName returns the name that should be displayed in the statusline
364 // for this buffer
365 func (b *Buffer) GetName() string {
366         if b.name == "" {
367                 if b.Path == "" {
368                         return "No name"
369                 }
370                 return b.Path
371         }
372         return b.name
373 }
374
375 //SetName changes the name for this buffer
376 func (b *Buffer) SetName(s string) {
377         b.name = s
378 }
379
380 // Insert inserts the given string of text at the start location
381 func (b *Buffer) Insert(start Loc, text string) {
382         if !b.Type.Readonly {
383                 b.EventHandler.cursors = b.cursors
384                 b.EventHandler.active = b.curCursor
385                 b.EventHandler.Insert(start, text)
386
387                 go b.Backup(true)
388         }
389 }
390
391 // Remove removes the characters between the start and end locations
392 func (b *Buffer) Remove(start, end Loc) {
393         if !b.Type.Readonly {
394                 b.EventHandler.cursors = b.cursors
395                 b.EventHandler.active = b.curCursor
396                 b.EventHandler.Remove(start, end)
397
398                 go b.Backup(true)
399         }
400 }
401
402 // FileType returns the buffer's filetype
403 func (b *Buffer) FileType() string {
404         return b.Settings["filetype"].(string)
405 }
406
407 // ExternallyModified returns whether the file being edited has
408 // been modified by some external process
409 func (b *Buffer) ExternallyModified() bool {
410         modTime, err := util.GetModTime(b.Path)
411         if err == nil {
412                 return modTime != b.ModTime
413         }
414         return false
415 }
416
417 // UpdateModTime updates the modtime of this file
418 func (b *Buffer) UpdateModTime() (err error) {
419         b.ModTime, err = util.GetModTime(b.Path)
420         return
421 }
422
423 // ReOpen reloads the current buffer from disk
424 func (b *Buffer) ReOpen() error {
425         file, err := os.Open(b.Path)
426         if err != nil {
427                 return err
428         }
429
430         enc, err := htmlindex.Get(b.Settings["encoding"].(string))
431         if err != nil {
432                 return err
433         }
434
435         reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
436         data, err := ioutil.ReadAll(reader)
437         txt := string(data)
438
439         if err != nil {
440                 return err
441         }
442         b.EventHandler.ApplyDiff(txt)
443
444         err = b.UpdateModTime()
445         if !b.Settings["fastdirty"].(bool) {
446                 calcHash(b, &b.origHash)
447         }
448         b.isModified = false
449         b.RelocateCursors()
450         return err
451 }
452
453 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
454 func (b *Buffer) RelocateCursors() {
455         for _, c := range b.cursors {
456                 c.Relocate()
457         }
458 }
459
460 // RuneAt returns the rune at a given location in the buffer
461 func (b *Buffer) RuneAt(loc Loc) rune {
462         line := b.LineBytes(loc.Y)
463         if len(line) > 0 {
464                 i := 0
465                 for len(line) > 0 {
466                         r, size := utf8.DecodeRune(line)
467                         line = line[size:]
468                         i++
469
470                         if i == loc.X {
471                                 return r
472                         }
473                 }
474         }
475         return '\n'
476 }
477
478 // Modified returns if this buffer has been modified since
479 // being opened
480 func (b *Buffer) Modified() bool {
481         if b.Type.Scratch {
482                 return false
483         }
484
485         if b.Settings["fastdirty"].(bool) {
486                 return b.isModified
487         }
488
489         var buff [md5.Size]byte
490
491         calcHash(b, &buff)
492         return buff != b.origHash
493 }
494
495 // calcHash calculates md5 hash of all lines in the buffer
496 func calcHash(b *Buffer, out *[md5.Size]byte) error {
497         h := md5.New()
498
499         size := 0
500         if len(b.lines) > 0 {
501                 n, e := h.Write(b.lines[0].data)
502                 if e != nil {
503                         return e
504                 }
505                 size += n
506
507                 for _, l := range b.lines[1:] {
508                         n, e = h.Write([]byte{'\n'})
509                         if e != nil {
510                                 return e
511                         }
512                         size += n
513                         n, e = h.Write(l.data)
514                         if e != nil {
515                                 return e
516                         }
517                         size += n
518                 }
519         }
520
521         if size > LargeFileThreshold {
522                 return ErrFileTooLarge
523         }
524
525         h.Sum((*out)[:0])
526         return nil
527 }
528
529 // UpdateRules updates the syntax rules and filetype for this buffer
530 // This is called when the colorscheme changes
531 func (b *Buffer) UpdateRules() {
532         if !b.Type.Syntax {
533                 return
534         }
535         ft := b.Settings["filetype"].(string)
536         if ft == "off" {
537                 return
538         }
539         syntaxFile := ""
540         var header *highlight.Header
541         for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
542                 data, err := f.Data()
543                 if err != nil {
544                         screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
545                         continue
546                 }
547
548                 header, err = highlight.MakeHeader(data)
549                 if err != nil {
550                         screen.TermMessage("Error reading syntax header file", f.Name(), err)
551                         continue
552                 }
553
554                 if ft == "unknown" || ft == "" {
555                         if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
556                                 syntaxFile = f.Name()
557                                 break
558                         }
559                 } else if header.FileType == ft {
560                         syntaxFile = f.Name()
561                         break
562                 }
563         }
564
565         if syntaxFile == "" {
566                 // search for the syntax file in the user's custom syntax files
567                 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
568                         log.Println("real runtime file", f.Name())
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         log.Println("Cleared cursors:", len(b.cursors))
787 }
788
789 // MoveLinesUp moves the range of lines up one row
790 func (b *Buffer) MoveLinesUp(start int, end int) {
791         if start < 1 || start >= end || end > len(b.lines) {
792                 return
793         }
794         l := string(b.LineBytes(start - 1))
795         if end == len(b.lines) {
796                 b.Insert(
797                         Loc{
798                                 utf8.RuneCount(b.lines[end-1].data),
799                                 end - 1,
800                         },
801                         "\n"+l,
802                 )
803         } else {
804                 b.Insert(
805                         Loc{0, end},
806                         l+"\n",
807                 )
808         }
809         b.Remove(
810                 Loc{0, start - 1},
811                 Loc{0, start},
812         )
813 }
814
815 // MoveLinesDown moves the range of lines down one row
816 func (b *Buffer) MoveLinesDown(start int, end int) {
817         if start < 0 || start >= end || end >= len(b.lines)-1 {
818                 return
819         }
820         l := string(b.LineBytes(end))
821         b.Insert(
822                 Loc{0, start},
823                 l+"\n",
824         )
825         end++
826         b.Remove(
827                 Loc{0, end},
828                 Loc{0, end + 1},
829         )
830 }
831
832 var BracePairs = [][2]rune{
833         {'(', ')'},
834         {'{', '}'},
835         {'[', ']'},
836 }
837
838 // FindMatchingBrace returns the location in the buffer of the matching bracket
839 // It is given a brace type containing the open and closing character, (for example
840 // '{' and '}') as well as the location to match from
841 // TODO: maybe can be more efficient with utf8 package
842 // returns the location of the matching brace
843 // if the boolean returned is true then the original matching brace is one character left
844 // of the starting location
845 func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, bool) {
846         curLine := []rune(string(b.LineBytes(start.Y)))
847         startChar := ' '
848         if start.X >= 0 && start.X < len(curLine) {
849                 startChar = curLine[start.X]
850         }
851         leftChar := ' '
852         if start.X-1 >= 0 && start.X-1 < len(curLine) {
853                 leftChar = curLine[start.X-1]
854         }
855         var i int
856         if startChar == braceType[0] || leftChar == braceType[0] {
857                 for y := start.Y; y < b.LinesNum(); y++ {
858                         l := []rune(string(b.LineBytes(y)))
859                         xInit := 0
860                         if y == start.Y {
861                                 if startChar == braceType[0] {
862                                         xInit = start.X
863                                 } else {
864                                         xInit = start.X - 1
865                                 }
866                         }
867                         for x := xInit; x < len(l); x++ {
868                                 r := l[x]
869                                 if r == braceType[0] {
870                                         i++
871                                 } else if r == braceType[1] {
872                                         i--
873                                         if i == 0 {
874                                                 if startChar == braceType[0] {
875                                                         return Loc{x, y}, false, true
876                                                 }
877                                                 return Loc{x, y}, true, true
878                                         }
879                                 }
880                         }
881                 }
882         } else if startChar == braceType[1] || leftChar == braceType[1] {
883                 for y := start.Y; y >= 0; y-- {
884                         l := []rune(string(b.lines[y].data))
885                         xInit := len(l) - 1
886                         if y == start.Y {
887                                 if leftChar == braceType[1] {
888                                         xInit = start.X - 1
889                                 } else {
890                                         xInit = start.X
891                                 }
892                         }
893                         for x := xInit; x >= 0; x-- {
894                                 r := l[x]
895                                 if r == braceType[0] {
896                                         i--
897                                         if i == 0 {
898                                                 if leftChar == braceType[1] {
899                                                         return Loc{x, y}, true, true
900                                                 }
901                                                 return Loc{x, y}, false, true
902                                         }
903                                 } else if r == braceType[1] {
904                                         i++
905                                 }
906                         }
907                 }
908         }
909         return start, true, false
910 }
911
912 // Retab changes all tabs to spaces or vice versa
913 func (b *Buffer) Retab() {
914         toSpaces := b.Settings["tabstospaces"].(bool)
915         tabsize := util.IntOpt(b.Settings["tabsize"])
916         dirty := false
917
918         for i := 0; i < b.LinesNum(); i++ {
919                 l := b.LineBytes(i)
920
921                 ws := util.GetLeadingWhitespace(l)
922                 if len(ws) != 0 {
923                         if toSpaces {
924                                 ws = bytes.Replace(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize), -1)
925                         } else {
926                                 ws = bytes.Replace(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'}, -1)
927                         }
928                 }
929
930                 l = bytes.TrimLeft(l, " \t")
931                 b.lines[i].data = append(ws, l...)
932                 b.MarkModified(i, i)
933                 dirty = true
934         }
935
936         b.isModified = dirty
937 }
938
939 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
940 // into a loc
941 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
942         startpos := Loc{0, 0}
943         var err error
944
945         // if no positions are available exit early
946         if cursorPositions == nil {
947                 return startpos, errors.New("No cursor positions were provided.")
948         }
949
950         startpos.Y, err = strconv.Atoi(cursorPositions[0])
951         startpos.Y--
952         if err == nil {
953                 if len(cursorPositions) > 1 {
954                         startpos.X, err = strconv.Atoi(cursorPositions[1])
955                         if startpos.X > 0 {
956                                 startpos.X--
957                         }
958                 }
959         }
960
961         return startpos, err
962 }
963
964 // Line returns the string representation of the given line number
965 func (b *Buffer) Line(i int) string {
966         return string(b.LineBytes(i))
967 }
968
969 func (b *Buffer) Write(bytes []byte) (n int, err error) {
970         b.EventHandler.InsertBytes(b.End(), bytes)
971         return len(bytes), nil
972 }
973
974 func (b *Buffer) updateDiffSync() {
975         b.diffLock.Lock()
976         defer b.diffLock.Unlock()
977
978         b.diff = make(map[int]DiffStatus)
979
980         if b.diffBase == nil {
981                 return
982         }
983
984         differ := dmp.New()
985         baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
986         diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
987         lineN := 0
988
989         for _, diff := range diffs {
990                 lineCount := len([]rune(diff.Text))
991
992                 switch diff.Type {
993                 case dmp.DiffEqual:
994                         lineN += lineCount
995                 case dmp.DiffInsert:
996                         var status DiffStatus
997                         if b.diff[lineN] == DSDeletedAbove {
998                                 status = DSModified
999                         } else {
1000                                 status = DSAdded
1001                         }
1002                         for i := 0; i < lineCount; i++ {
1003                                 b.diff[lineN] = status
1004                                 lineN++
1005                         }
1006                 case dmp.DiffDelete:
1007                         b.diff[lineN] = DSDeletedAbove
1008                 }
1009         }
1010 }
1011
1012 // UpdateDiff computes the diff between the diff base and the buffer content.
1013 // The update may be performed synchronously or asynchronously.
1014 // UpdateDiff calls the supplied callback when the update is complete.
1015 // The argument passed to the callback is set to true if and only if
1016 // the update was performed synchronously.
1017 // If an asynchronous update is already pending when UpdateDiff is called,
1018 // UpdateDiff does not schedule another update, in which case the callback
1019 // is not called.
1020 func (b *Buffer) UpdateDiff(callback func(bool)) {
1021         if b.updateDiffTimer != nil {
1022                 return
1023         }
1024
1025         lineCount := b.LinesNum()
1026         if b.diffBaseLineCount > lineCount {
1027                 lineCount = b.diffBaseLineCount
1028         }
1029
1030         if lineCount < 1000 {
1031                 b.updateDiffSync()
1032                 callback(true)
1033         } else if lineCount < 30000 {
1034                 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1035                         b.updateDiffTimer = nil
1036                         b.updateDiffSync()
1037                         callback(false)
1038                 })
1039         } else {
1040                 // Don't compute diffs for very large files
1041                 b.diffLock.Lock()
1042                 b.diff = make(map[int]DiffStatus)
1043                 b.diffLock.Unlock()
1044                 callback(true)
1045         }
1046 }
1047
1048 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1049 func (b *Buffer) SetDiffBase(diffBase []byte) {
1050         b.diffBase = diffBase
1051         if diffBase == nil {
1052                 b.diffBaseLineCount = 0
1053         } else {
1054                 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1055         }
1056         b.UpdateDiff(func(synchronous bool) {
1057                 screen.Redraw()
1058         })
1059 }
1060
1061 // DiffStatus returns the diff status for a line in the buffer
1062 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1063         b.diffLock.RLock()
1064         defer b.diffLock.RUnlock()
1065         // Note that the zero value for DiffStatus is equal to DSUnchanged
1066         return b.diff[lineN]
1067 }
1068
1069 // WriteLog writes a string to the log buffer
1070 func WriteLog(s string) {
1071         LogBuf.EventHandler.Insert(LogBuf.End(), s)
1072 }
1073
1074 // GetLogBuf returns the log buffer
1075 func GetLogBuf() *Buffer {
1076         return LogBuf
1077 }