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