19 luar "layeh.com/gopher-luar"
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"
32 const backupTime = 8000
35 // OpenBuffers is a list of the currently open buffers
37 // LogBuf is a reference to the log buffer which can be opened with the
42 // The BufType defines what kind of buffer this is
45 Readonly bool // The buffer cannot be edited
46 Scratch bool // The buffer cannot be saved
47 Syntax bool // Syntax highlighting is enabled
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}
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")
69 // SharedBuffer is a struct containing info that is shared among buffers
70 // that have the same file open
71 type SharedBuffer struct {
73 // Stores the last modification time of the file the buffer is pointing to
75 // Type of the buffer (e.g. help, raw, scratch etc..)
78 // ReloadDisabled allows the user to disable reloads if they
79 // are viewing a file that is constantly changing
83 // Whether or not suggestions can be autocompleted must be shared because
84 // it changes based on how the buffer has changed
87 // Modifications is the list of modified regions for syntax highlighting
90 // Hash of the original buffer -- empty if fastdirty is on
91 origHash [md5.Size]byte
94 func (b *SharedBuffer) insert(pos Loc, value []byte) {
96 b.HasSuggestions = false
97 b.LineArray.insert(pos, value)
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'})})
103 func (b *SharedBuffer) remove(start, end Loc) []byte {
105 b.HasSuggestions = false
106 b.Modifications = append(b.Modifications, Loc{start.Y, start.Y})
107 return b.LineArray.remove(start, end)
110 // DisableReload disables future reloads of this sharedbuffer
111 func (b *SharedBuffer) DisableReload() {
112 b.ReloadDisabled = true
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.
139 // Path to the file on disk
141 // Absolute path to the file on disk
143 // Name of the buffer on the status line
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
153 // Settings customized by the user
154 Settings map[string]interface{}
162 updateDiffTimer *time.Timer
164 diffBaseLineCount int
165 diffLock sync.RWMutex
166 diff map[int]DiffStatus
168 // counts the number of edits
169 // resets every backupTime edits
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) {
179 filename, cursorPos := util.GetPathAndCursorPosition(path)
180 filename, err = util.ReplaceHome(filename)
185 file, err := os.Open(filename)
186 fileInfo, _ := os.Stat(filename)
188 if err == nil && fileInfo.IsDir() {
189 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
194 cursorLoc, cursorerr := ParseCursorLocation(cursorPos)
195 if cursorerr != nil {
196 cursorLoc = Loc{-1, -1}
201 // File does not exist -- create an empty buffer with that name
202 buf = NewBufferFromString("", filename, btype)
204 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
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)
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
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)
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
232 config.InitLocalSettings(b.Settings, path)
234 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
237 b.Settings["encoding"] = "utf-8"
240 reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
244 for _, buf := range OpenBuffers {
245 if buf.AbsPath == absPath && buf.Type != BTInfo {
247 b.SharedBuffer = buf.SharedBuffer
248 b.EventHandler = buf.EventHandler
257 b.SharedBuffer = new(SharedBuffer)
260 hasBackup := b.ApplyBackup(size)
263 b.LineArray = NewLineArray(uint64(size), FFAuto, reader)
265 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
268 if b.Settings["readonly"].(bool) && b.Type == BTDefault {
269 b.Type.Readonly = true
272 // The last time this file was modified
277 b.Settings["fileformat"] = "unix"
279 b.Settings["fileformat"] = "dos"
283 config.InitLocalSettings(b.Settings, b.Path)
285 if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
286 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
289 if startcursor.X != -1 && startcursor.Y != -1 {
290 b.StartCursor = startcursor
292 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
293 err := b.Unserialize()
295 screen.TermMessage(err)
300 b.AddCursor(NewCursor(b, b.StartCursor))
301 b.GetActiveCursor().Relocate()
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
308 calcHash(b, &b.origHash)
312 err = config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
314 screen.TermMessage(err)
317 b.Modifications = make([]Loc, 0, 10)
319 OpenBuffers = append(OpenBuffers, b)
324 // Close removes this buffer from the list of open buffers
325 func (b *Buffer) Close() {
326 for i, buf := range OpenBuffers {
329 copy(OpenBuffers[i:], OpenBuffers[i+1:])
330 OpenBuffers[len(OpenBuffers)-1] = nil
331 OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
337 // Fini should be called when a buffer is closed and performs
339 func (b *Buffer) Fini() {
346 // GetName returns the name that should be displayed in the statusline
348 func (b *Buffer) GetName() string {
358 //SetName changes the name for this buffer
359 func (b *Buffer) SetName(s string) {
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)
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)
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
390 func (b *Buffer) ClearModifications() {
391 // clear slice without resetting the cap
392 b.Modifications = b.Modifications[:0]
395 // FileType returns the buffer's filetype
396 func (b *Buffer) FileType() string {
397 return b.Settings["filetype"].(string)
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)
405 return modTime != b.ModTime
410 // UpdateModTime updates the modtime of this file
411 func (b *Buffer) UpdateModTime() (err error) {
412 b.ModTime, err = util.GetModTime(b.Path)
416 // ReOpen reloads the current buffer from disk
417 func (b *Buffer) ReOpen() error {
418 file, err := os.Open(b.Path)
423 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
428 reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
429 data, err := ioutil.ReadAll(reader)
435 b.EventHandler.ApplyDiff(txt)
437 err = b.UpdateModTime()
438 if !b.Settings["fastdirty"].(bool) {
439 calcHash(b, &b.origHash)
446 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
447 func (b *Buffer) RelocateCursors() {
448 for _, c := range b.cursors {
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)
459 r, size := utf8.DecodeRune(line)
471 // Modified returns if this buffer has been modified since
473 func (b *Buffer) Modified() bool {
478 if b.Settings["fastdirty"].(bool) {
482 var buff [md5.Size]byte
485 return buff != b.origHash
488 // calcHash calculates md5 hash of all lines in the buffer
489 func calcHash(b *Buffer, out *[md5.Size]byte) error {
493 if len(b.lines) > 0 {
494 n, e := h.Write(b.lines[0].data)
500 for _, l := range b.lines[1:] {
501 n, e = h.Write([]byte{'\n'})
506 n, e = h.Write(l.data)
514 if size > LargeFileThreshold {
515 return ErrFileTooLarge
522 // UpdateRules updates the syntax rules and filetype for this buffer
523 // This is called when the colorscheme changes
524 func (b *Buffer) UpdateRules() {
528 ft := b.Settings["filetype"].(string)
533 var header *highlight.Header
534 for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
535 data, err := f.Data()
537 screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
541 header, err = highlight.MakeHeader(data)
543 screen.TermMessage("Error reading syntax header file", f.Name(), err)
547 if ft == "unknown" || ft == "" {
548 if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
549 syntaxFile = f.Name()
552 } else if header.FileType == ft {
553 syntaxFile = f.Name()
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()
564 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
568 header, err = highlight.MakeHeaderYaml(data)
569 file, err := highlight.ParseFile(data)
571 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
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)
578 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
586 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
587 if f.Name() == syntaxFile {
588 data, err := f.Data()
590 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
594 file, err := highlight.ParseFile(data)
596 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
600 syndef, err := highlight.ParseDef(file, header)
602 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
611 if b.SyntaxDef != nil && highlight.HasIncludes(b.SyntaxDef) {
612 includes := highlight.GetIncludes(b.SyntaxDef)
614 var files []*highlight.File
615 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
616 data, err := f.Data()
618 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
621 header, err := highlight.MakeHeaderYaml(data)
623 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
627 for _, i := range includes {
628 if header.FileType == i {
629 file, err := highlight.ParseFile(data)
631 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
634 files = append(files, file)
638 if len(files) >= len(includes) {
643 highlight.ResolveIncludes(b.SyntaxDef, files)
646 if b.Highlighter == nil || syntaxFile != "" {
647 if b.SyntaxDef != nil {
648 b.Settings["filetype"] = b.SyntaxDef.FileType
651 b.SyntaxDef = &highlight.EmptyDef
654 if b.SyntaxDef != nil {
655 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
656 if b.Settings["syntax"].(bool) {
658 b.Highlighter.HighlightStates(b)
659 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
666 // ClearMatches clears all of the syntax highlighting for the buffer
667 func (b *Buffer) ClearMatches() {
668 for i := range b.lines {
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)
683 // SetCursors resets this buffer's cursors to a new list
684 func (b *Buffer) SetCursors(c []*Cursor) {
686 b.EventHandler.cursors = b.cursors
687 b.EventHandler.active = b.curCursor
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
698 // SetCurCursor sets the current cursor
699 func (b *Buffer) SetCurCursor(n int) {
703 // GetActiveCursor returns the main cursor in this buffer
704 func (b *Buffer) GetActiveCursor() *Cursor {
705 return b.cursors[b.curCursor]
708 // GetCursor returns the nth cursor
709 func (b *Buffer) GetCursor(n int) *Cursor {
713 // GetCursors returns the list of cursors in this buffer
714 func (b *Buffer) GetCursors() []*Cursor {
718 // NumCursors returns the number of cursors
719 func (b *Buffer) NumCursors() int {
720 return len(b.cursors)
723 // MergeCursors merges any cursors that are at the same position
725 func (b *Buffer) MergeCursors() {
726 var cursors []*Cursor
727 for i := 0; i < len(b.cursors); i++ {
730 for j := 0; j < len(b.cursors); j++ {
732 if c2 != nil && i != j && c1.Loc == c2.Loc {
736 cursors = append(cursors, c1)
742 for i := range b.cursors {
746 if b.curCursor >= len(b.cursors) {
747 b.curCursor = len(b.cursors) - 1
749 b.EventHandler.cursors = b.cursors
750 b.EventHandler.active = b.curCursor
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 {
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)
770 // ClearCursors removes all extra cursors
771 func (b *Buffer) ClearCursors() {
772 for i := 1; i < len(b.cursors); i++ {
775 b.cursors = b.cursors[:1]
778 b.GetActiveCursor().ResetSelection()
779 log.Println("Cleared cursors:", len(b.cursors))
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) {
787 l := string(b.LineBytes(start - 1))
788 if end == len(b.lines) {
791 utf8.RuneCount(b.lines[end-1].data),
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 {
813 l := string(b.LineBytes(end))
825 var BracePairs = [][2]rune{
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)))
841 if start.X >= 0 && start.X < len(curLine) {
842 startChar = curLine[start.X]
845 if start.X-1 >= 0 && start.X-1 < len(curLine) {
846 leftChar = curLine[start.X-1]
849 if startChar == braceType[0] || leftChar == braceType[0] {
850 for y := start.Y; y < b.LinesNum(); y++ {
851 l := []rune(string(b.LineBytes(y)))
854 if startChar == braceType[0] {
860 for x := xInit; x < len(l); x++ {
862 if r == braceType[0] {
864 } else if r == braceType[1] {
867 if startChar == braceType[0] {
868 return Loc{x, y}, false, true
870 return Loc{x, y}, true, true
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))
880 if leftChar == braceType[1] {
886 for x := xInit; x >= 0; x-- {
888 if r == braceType[0] {
891 if leftChar == braceType[1] {
892 return Loc{x, y}, true, true
894 return Loc{x, y}, false, true
896 } else if r == braceType[1] {
902 return start, true, false
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"])
911 for i := 0; i < b.LinesNum(); i++ {
914 ws := util.GetLeadingWhitespace(l)
917 ws = bytes.Replace(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize), -1)
919 ws = bytes.Replace(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'}, -1)
923 l = bytes.TrimLeft(l, " \t")
924 b.lines[i].data = append(ws, l...)
925 b.Modifications = append(b.Modifications, Loc{i, i})
932 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
934 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
935 startpos := Loc{0, 0}
938 // if no positions are available exit early
939 if cursorPositions == nil {
940 return startpos, errors.New("No cursor positions were provided.")
943 startpos.Y, err = strconv.Atoi(cursorPositions[0])
946 if len(cursorPositions) > 1 {
947 startpos.X, err = strconv.Atoi(cursorPositions[1])
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))
962 func (b *Buffer) Write(bytes []byte) (n int, err error) {
963 b.EventHandler.InsertBytes(b.End(), bytes)
964 return len(bytes), nil
967 func (b *Buffer) updateDiffSync() {
969 defer b.diffLock.Unlock()
971 b.diff = make(map[int]DiffStatus)
973 if b.diffBase == nil {
978 baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
979 diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
982 for _, diff := range diffs {
983 lineCount := len([]rune(diff.Text))
989 var status DiffStatus
990 if b.diff[lineN] == DSDeletedAbove {
995 for i := 0; i < lineCount; i++ {
996 b.diff[lineN] = status
1000 b.diff[lineN] = DSDeletedAbove
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
1013 func (b *Buffer) UpdateDiff(callback func(bool)) {
1014 if b.updateDiffTimer != nil {
1018 lineCount := b.LinesNum()
1019 if b.diffBaseLineCount > lineCount {
1020 lineCount = b.diffBaseLineCount
1023 if lineCount < 1000 {
1026 } else if lineCount < 30000 {
1027 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1028 b.updateDiffTimer = nil
1033 // Don't compute diffs for very large files
1035 b.diff = make(map[int]DiffStatus)
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
1047 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1049 b.UpdateDiff(func(synchronous bool) {
1054 // DiffStatus returns the diff status for a line in the buffer
1055 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1057 defer b.diffLock.RUnlock()
1058 // Note that the zero value for DiffStatus is equal to DSUnchanged
1059 return b.diff[lineN]
1062 // WriteLog writes a string to the log buffer
1063 func WriteLog(s string) {
1064 LogBuf.EventHandler.Insert(LogBuf.End(), s)
1067 // GetLogBuf returns the log buffer
1068 func GetLogBuf() *Buffer {