20 luar "layeh.com/gopher-luar"
22 dmp "github.com/sergi/go-diff/diffmatchpatch"
23 "github.com/zyedidia/micro/v2/internal/config"
24 ulua "github.com/zyedidia/micro/v2/internal/lua"
25 "github.com/zyedidia/micro/v2/internal/screen"
26 "github.com/zyedidia/micro/v2/internal/util"
27 "github.com/zyedidia/micro/v2/pkg/highlight"
28 "golang.org/x/text/encoding/htmlindex"
29 "golang.org/x/text/encoding/unicode"
30 "golang.org/x/text/transform"
33 const backupTime = 8000
36 // OpenBuffers is a list of the currently open buffers
38 // LogBuf is a reference to the log buffer which can be opened with the
43 // The BufType defines what kind of buffer this is
46 Readonly bool // The buffer cannot be edited
47 Scratch bool // The buffer cannot be saved
48 Syntax bool // Syntax highlighting is enabled
52 // BTDefault is a default buffer
53 BTDefault = BufType{0, false, false, true}
54 // BTHelp is a help buffer
55 BTHelp = BufType{1, true, true, true}
56 // BTLog is a log buffer
57 BTLog = BufType{2, true, true, false}
58 // BTScratch is a buffer that cannot be saved (for scratch work)
59 BTScratch = BufType{3, false, true, false}
60 // BTRaw is is a buffer that shows raw terminal events
61 BTRaw = BufType{4, false, true, false}
62 // BTInfo is a buffer for inputting information
63 BTInfo = BufType{5, false, true, false}
64 // BTStdout is a buffer that only writes to stdout
66 BTStdout = BufType{6, false, true, true}
68 // ErrFileTooLarge is returned when the file is too large to hash
69 // (fastdirty is automatically enabled)
70 ErrFileTooLarge = errors.New("File is too large to hash")
73 // SharedBuffer is a struct containing info that is shared among buffers
74 // that have the same file open
75 type SharedBuffer struct {
77 // Stores the last modification time of the file the buffer is pointing to
79 // Type of the buffer (e.g. help, raw, scratch etc..)
82 // Path to the file on disk
84 // Absolute path to the file on disk
86 // Name of the buffer on the status line
91 // Settings customized by the user
92 Settings map[string]interface{}
100 updateDiffTimer *time.Timer
102 diffBaseLineCount int
103 diffLock sync.RWMutex
104 diff map[int]DiffStatus
108 // ReloadDisabled allows the user to disable reloads if they
109 // are viewing a file that is constantly changing
113 // Whether or not suggestions can be autocompleted must be shared because
114 // it changes based on how the buffer has changed
117 // The Highlighter struct actually performs the highlighting
118 Highlighter *highlight.Highlighter
119 // SyntaxDef represents the syntax highlighting definition being used
120 // This stores the highlighting rules and filetype detection info
121 SyntaxDef *highlight.Def
123 ModifiedThisFrame bool
125 // Hash of the original buffer -- empty if fastdirty is on
126 origHash [md5.Size]byte
129 func (b *SharedBuffer) insert(pos Loc, value []byte) {
131 b.HasSuggestions = false
132 b.LineArray.insert(pos, value)
134 inslines := bytes.Count(value, []byte{'\n'})
135 b.MarkModified(pos.Y, pos.Y+inslines)
137 func (b *SharedBuffer) remove(start, end Loc) []byte {
139 b.HasSuggestions = false
140 defer b.MarkModified(start.Y, end.Y)
141 return b.LineArray.remove(start, end)
144 // MarkModified marks the buffer as modified for this frame
145 // and performs rehighlighting if syntax highlighting is enabled
146 func (b *SharedBuffer) MarkModified(start, end int) {
147 b.ModifiedThisFrame = true
149 if !b.Settings["syntax"].(bool) || b.SyntaxDef == nil {
153 start = util.Clamp(start, 0, len(b.lines)-1)
154 end = util.Clamp(end, 0, len(b.lines)-1)
157 for i := start; i <= end; i++ {
158 l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
160 b.Highlighter.HighlightMatches(b, start, l)
163 // DisableReload disables future reloads of this sharedbuffer
164 func (b *SharedBuffer) DisableReload() {
165 b.ReloadDisabled = true
177 // Buffer stores the main information about a currently open file including
178 // the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
179 // all the cursors, the syntax highlighting info, the settings for the buffer
180 // and some misc info about modification time and path location.
181 // The syntax highlighting info must be stored with the buffer because the syntax
182 // highlighter attaches information to each line of the buffer for optimization
183 // purposes so it doesn't have to rehighlight everything on every update.
194 // NewBufferFromFileAtLoc opens a new buffer with a given cursor location
195 // If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
196 // would otherwise be (start of file, or saved cursor position if `savecursor` is
198 func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
201 if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
202 var cursorPos []string
203 filename, cursorPos = util.GetPathAndCursorPosition(filename)
204 cursorLoc, err = ParseCursorLocation(cursorPos)
206 cursorLoc = Loc{-1, -1}
210 filename, err = util.ReplaceHome(filename)
215 f, err := os.OpenFile(filename, os.O_WRONLY, 0)
216 readonly := os.IsPermission(err)
219 fileInfo, serr := os.Stat(filename)
220 if serr != nil && !os.IsNotExist(serr) {
223 if serr == nil && fileInfo.IsDir() {
224 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
227 file, err := os.Open(filename)
233 if os.IsNotExist(err) {
234 // File does not exist -- create an empty buffer with that name
235 buf = NewBufferFromString("", filename, btype)
236 } else if err != nil {
239 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
243 buf.SetOptionNative("readonly", true)
249 // NewBufferFromFile opens a new buffer using the given path
250 // It will also automatically handle `~`, and line/column with filename:l:c
251 // It will return an empty buffer if the path does not exist
252 // and an error if the file is a directory
253 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
254 return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
257 // NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
258 func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
259 return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
262 // NewBufferFromString creates a new buffer containing the given string
263 func NewBufferFromString(text, path string, btype BufType) *Buffer {
264 return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
267 // NewBuffer creates a new buffer from a given reader with a given path
268 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
270 // Places the cursor at startcursor. If startcursor is -1, -1 places the
271 // cursor at an autodetected location (based on savecursor or :LINE:COL)
272 func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
273 absPath, _ := filepath.Abs(path)
279 for _, buf := range OpenBuffers {
280 if buf.AbsPath == absPath && buf.Type != BTInfo {
282 b.SharedBuffer = buf.SharedBuffer
283 b.EventHandler = buf.EventHandler
290 b.SharedBuffer = new(SharedBuffer)
296 b.Settings = config.DefaultCommonSettings()
297 for k, v := range config.GlobalSettings {
298 if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
299 // make sure setting is not global-only
303 config.InitLocalSettings(b.Settings, path)
305 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
308 b.Settings["encoding"] = "utf-8"
311 hasBackup = b.ApplyBackup(size)
314 reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
316 var ff FileFormat = FFAuto
319 // for empty files, use the fileformat setting instead of
321 switch b.Settings["fileformat"] {
329 b.LineArray = NewLineArray(uint64(size), ff, reader)
331 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
333 // The last time this file was modified
337 if b.Settings["readonly"].(bool) && b.Type == BTDefault {
338 b.Type.Readonly = true
343 b.Settings["fileformat"] = "unix"
345 b.Settings["fileformat"] = "dos"
349 // init local settings again now that we know the filetype
350 config.InitLocalSettings(b.Settings, b.Path)
352 if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
353 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
356 if startcursor.X != -1 && startcursor.Y != -1 {
357 b.StartCursor = startcursor
358 } else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
359 err := b.Unserialize()
361 screen.TermMessage(err)
365 b.AddCursor(NewCursor(b, b.StartCursor))
366 b.GetActiveCursor().Relocate()
368 if !b.Settings["fastdirty"].(bool) && !found {
369 if size > LargeFileThreshold {
370 // If the file is larger than LargeFileThreshold fastdirty needs to be on
371 b.Settings["fastdirty"] = true
372 } else if !hasBackup {
373 // since applying a backup does not save the applied backup to disk, we should
374 // not calculate the original hash based on the backup data
375 calcHash(b, &b.origHash)
379 err := config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
381 screen.TermMessage(err)
384 OpenBuffers = append(OpenBuffers, b)
389 // Close removes this buffer from the list of open buffers
390 func (b *Buffer) Close() {
391 for i, buf := range OpenBuffers {
394 copy(OpenBuffers[i:], OpenBuffers[i+1:])
395 OpenBuffers[len(OpenBuffers)-1] = nil
396 OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
402 // Fini should be called when a buffer is closed and performs
404 func (b *Buffer) Fini() {
410 if b.Type == BTStdout {
411 fmt.Fprint(util.Stdout, string(b.Bytes()))
414 atomic.StoreInt32(&(b.fini), int32(1))
417 // GetName returns the name that should be displayed in the statusline
419 func (b *Buffer) GetName() string {
427 if b.Settings["basename"].(bool) {
428 return path.Base(name)
433 //SetName changes the name for this buffer
434 func (b *Buffer) SetName(s string) {
438 // Insert inserts the given string of text at the start location
439 func (b *Buffer) Insert(start Loc, text string) {
440 if !b.Type.Readonly {
441 b.EventHandler.cursors = b.cursors
442 b.EventHandler.active = b.curCursor
443 b.EventHandler.Insert(start, text)
449 // Remove removes the characters between the start and end locations
450 func (b *Buffer) Remove(start, end Loc) {
451 if !b.Type.Readonly {
452 b.EventHandler.cursors = b.cursors
453 b.EventHandler.active = b.curCursor
454 b.EventHandler.Remove(start, end)
460 // FileType returns the buffer's filetype
461 func (b *Buffer) FileType() string {
462 return b.Settings["filetype"].(string)
465 // ExternallyModified returns whether the file being edited has
466 // been modified by some external process
467 func (b *Buffer) ExternallyModified() bool {
468 modTime, err := util.GetModTime(b.Path)
470 return modTime != b.ModTime
475 // UpdateModTime updates the modtime of this file
476 func (b *Buffer) UpdateModTime() (err error) {
477 b.ModTime, err = util.GetModTime(b.Path)
481 // ReOpen reloads the current buffer from disk
482 func (b *Buffer) ReOpen() error {
483 file, err := os.Open(b.Path)
488 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
493 reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
494 data, err := ioutil.ReadAll(reader)
500 b.EventHandler.ApplyDiff(txt)
502 err = b.UpdateModTime()
503 if !b.Settings["fastdirty"].(bool) {
504 calcHash(b, &b.origHash)
511 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
512 func (b *Buffer) RelocateCursors() {
513 for _, c := range b.cursors {
518 // RuneAt returns the rune at a given location in the buffer
519 func (b *Buffer) RuneAt(loc Loc) rune {
520 line := b.LineBytes(loc.Y)
524 r, _, size := util.DecodeCharacter(line)
537 // Modified returns if this buffer has been modified since
539 func (b *Buffer) Modified() bool {
544 if b.Settings["fastdirty"].(bool) {
548 var buff [md5.Size]byte
551 return buff != b.origHash
554 // Size returns the number of bytes in the current buffer
555 func (b *Buffer) Size() int {
557 for i := 0; i < b.LinesNum(); i++ {
558 nb += len(b.LineBytes(i))
560 if i != b.LinesNum()-1 {
561 if b.Endings == FFDos {
562 nb++ // carriage return
570 // calcHash calculates md5 hash of all lines in the buffer
571 func calcHash(b *Buffer, out *[md5.Size]byte) error {
575 if len(b.lines) > 0 {
576 n, e := h.Write(b.lines[0].data)
582 for _, l := range b.lines[1:] {
583 n, e = h.Write([]byte{'\n'})
588 n, e = h.Write(l.data)
596 if size > LargeFileThreshold {
597 return ErrFileTooLarge
604 // UpdateRules updates the syntax rules and filetype for this buffer
605 // This is called when the colorscheme changes
606 func (b *Buffer) UpdateRules() {
610 ft := b.Settings["filetype"].(string)
616 var header *highlight.Header
617 // search for the syntax file in the user's custom syntax files
618 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
619 data, err := f.Data()
621 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
625 header, err = highlight.MakeHeaderYaml(data)
627 screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
629 file, err := highlight.ParseFile(data)
631 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
635 if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
636 syndef, err := highlight.ParseDef(file, header)
638 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
642 syntaxFile = f.Name()
648 // search in the default syntax files
649 for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
650 data, err := f.Data()
652 screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
656 header, err = highlight.MakeHeader(data)
658 screen.TermMessage("Error reading syntax header file", f.Name(), err)
662 if ft == "unknown" || ft == "" {
663 if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
664 syntaxFile = f.Name()
667 } else if header.FileType == ft {
668 syntaxFile = f.Name()
673 if syntaxFile != "" && !foundDef {
674 // we found a syntax file using a syntax header file
675 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
676 if f.Name() == syntaxFile {
677 data, err := f.Data()
679 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
683 file, err := highlight.ParseFile(data)
685 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
689 syndef, err := highlight.ParseDef(file, header)
691 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
700 if b.SyntaxDef != nil && highlight.HasIncludes(b.SyntaxDef) {
701 includes := highlight.GetIncludes(b.SyntaxDef)
703 var files []*highlight.File
704 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
705 data, err := f.Data()
707 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
710 header, err := highlight.MakeHeaderYaml(data)
712 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
716 for _, i := range includes {
717 if header.FileType == i {
718 file, err := highlight.ParseFile(data)
720 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
723 files = append(files, file)
727 if len(files) >= len(includes) {
732 highlight.ResolveIncludes(b.SyntaxDef, files)
735 if b.Highlighter == nil || syntaxFile != "" {
736 if b.SyntaxDef != nil {
737 b.Settings["filetype"] = b.SyntaxDef.FileType
740 b.SyntaxDef = &highlight.EmptyDef
743 if b.SyntaxDef != nil {
744 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
745 if b.Settings["syntax"].(bool) {
747 b.Highlighter.HighlightStates(b)
748 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
755 // ClearMatches clears all of the syntax highlighting for the buffer
756 func (b *Buffer) ClearMatches() {
757 for i := range b.lines {
763 // IndentString returns this buffer's indent method (a tabstop or n spaces
764 // depending on the settings)
765 func (b *Buffer) IndentString(tabsize int) string {
766 if b.Settings["tabstospaces"].(bool) {
767 return util.Spaces(tabsize)
772 // SetCursors resets this buffer's cursors to a new list
773 func (b *Buffer) SetCursors(c []*Cursor) {
775 b.EventHandler.cursors = b.cursors
776 b.EventHandler.active = b.curCursor
779 // AddCursor adds a new cursor to the list
780 func (b *Buffer) AddCursor(c *Cursor) {
781 b.cursors = append(b.cursors, c)
782 b.EventHandler.cursors = b.cursors
783 b.EventHandler.active = b.curCursor
787 // SetCurCursor sets the current cursor
788 func (b *Buffer) SetCurCursor(n int) {
792 // GetActiveCursor returns the main cursor in this buffer
793 func (b *Buffer) GetActiveCursor() *Cursor {
794 return b.cursors[b.curCursor]
797 // GetCursor returns the nth cursor
798 func (b *Buffer) GetCursor(n int) *Cursor {
802 // GetCursors returns the list of cursors in this buffer
803 func (b *Buffer) GetCursors() []*Cursor {
807 // NumCursors returns the number of cursors
808 func (b *Buffer) NumCursors() int {
809 return len(b.cursors)
812 // MergeCursors merges any cursors that are at the same position
814 func (b *Buffer) MergeCursors() {
815 var cursors []*Cursor
816 for i := 0; i < len(b.cursors); i++ {
819 for j := 0; j < len(b.cursors); j++ {
821 if c2 != nil && i != j && c1.Loc == c2.Loc {
825 cursors = append(cursors, c1)
831 for i := range b.cursors {
835 if b.curCursor >= len(b.cursors) {
836 b.curCursor = len(b.cursors) - 1
838 b.EventHandler.cursors = b.cursors
839 b.EventHandler.active = b.curCursor
842 // UpdateCursors updates all the cursors indicies
843 func (b *Buffer) UpdateCursors() {
844 b.EventHandler.cursors = b.cursors
845 b.EventHandler.active = b.curCursor
846 for i, c := range b.cursors {
851 func (b *Buffer) RemoveCursor(i int) {
852 copy(b.cursors[i:], b.cursors[i+1:])
853 b.cursors[len(b.cursors)-1] = nil
854 b.cursors = b.cursors[:len(b.cursors)-1]
855 b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
859 // ClearCursors removes all extra cursors
860 func (b *Buffer) ClearCursors() {
861 for i := 1; i < len(b.cursors); i++ {
864 b.cursors = b.cursors[:1]
867 b.GetActiveCursor().ResetSelection()
870 // MoveLinesUp moves the range of lines up one row
871 func (b *Buffer) MoveLinesUp(start int, end int) {
872 if start < 1 || start >= end || end > len(b.lines) {
875 l := string(b.LineBytes(start - 1))
876 if end == len(b.lines) {
879 util.CharacterCount(b.lines[end-1].data),
895 // MoveLinesDown moves the range of lines down one row
896 func (b *Buffer) MoveLinesDown(start int, end int) {
897 if start < 0 || start >= end || end >= len(b.lines) {
900 l := string(b.LineBytes(end))
912 var BracePairs = [][2]rune{
918 // FindMatchingBrace returns the location in the buffer of the matching bracket
919 // It is given a brace type containing the open and closing character, (for example
920 // '{' and '}') as well as the location to match from
921 // TODO: maybe can be more efficient with utf8 package
922 // returns the location of the matching brace
923 // if the boolean returned is true then the original matching brace is one character left
924 // of the starting location
925 func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, bool) {
926 curLine := []rune(string(b.LineBytes(start.Y)))
928 if start.X >= 0 && start.X < len(curLine) {
929 startChar = curLine[start.X]
932 if start.X-1 >= 0 && start.X-1 < len(curLine) {
933 leftChar = curLine[start.X-1]
936 if startChar == braceType[0] || leftChar == braceType[0] {
937 for y := start.Y; y < b.LinesNum(); y++ {
938 l := []rune(string(b.LineBytes(y)))
941 if startChar == braceType[0] {
947 for x := xInit; x < len(l); x++ {
949 if r == braceType[0] {
951 } else if r == braceType[1] {
954 if startChar == braceType[0] {
955 return Loc{x, y}, false, true
957 return Loc{x, y}, true, true
962 } else if startChar == braceType[1] || leftChar == braceType[1] {
963 for y := start.Y; y >= 0; y-- {
964 l := []rune(string(b.lines[y].data))
967 if leftChar == braceType[1] {
973 for x := xInit; x >= 0; x-- {
975 if r == braceType[0] {
978 if leftChar == braceType[1] {
979 return Loc{x, y}, true, true
981 return Loc{x, y}, false, true
983 } else if r == braceType[1] {
989 return start, true, false
992 // Retab changes all tabs to spaces or vice versa
993 func (b *Buffer) Retab() {
994 toSpaces := b.Settings["tabstospaces"].(bool)
995 tabsize := util.IntOpt(b.Settings["tabsize"])
998 for i := 0; i < b.LinesNum(); i++ {
1001 ws := util.GetLeadingWhitespace(l)
1004 ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
1006 ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
1010 l = bytes.TrimLeft(l, " \t")
1011 b.lines[i].data = append(ws, l...)
1012 b.MarkModified(i, i)
1016 b.isModified = dirty
1019 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
1021 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
1022 startpos := Loc{0, 0}
1025 // if no positions are available exit early
1026 if cursorPositions == nil {
1027 return startpos, errors.New("No cursor positions were provided.")
1030 startpos.Y, err = strconv.Atoi(cursorPositions[0])
1033 if len(cursorPositions) > 1 {
1034 startpos.X, err = strconv.Atoi(cursorPositions[1])
1041 return startpos, err
1044 // Line returns the string representation of the given line number
1045 func (b *Buffer) Line(i int) string {
1046 return string(b.LineBytes(i))
1049 func (b *Buffer) Write(bytes []byte) (n int, err error) {
1050 b.EventHandler.InsertBytes(b.End(), bytes)
1051 return len(bytes), nil
1054 func (b *Buffer) updateDiffSync() {
1056 defer b.diffLock.Unlock()
1058 b.diff = make(map[int]DiffStatus)
1060 if b.diffBase == nil {
1065 baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
1066 diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
1069 for _, diff := range diffs {
1070 lineCount := len([]rune(diff.Text))
1075 case dmp.DiffInsert:
1076 var status DiffStatus
1077 if b.diff[lineN] == DSDeletedAbove {
1082 for i := 0; i < lineCount; i++ {
1083 b.diff[lineN] = status
1086 case dmp.DiffDelete:
1087 b.diff[lineN] = DSDeletedAbove
1092 // UpdateDiff computes the diff between the diff base and the buffer content.
1093 // The update may be performed synchronously or asynchronously.
1094 // UpdateDiff calls the supplied callback when the update is complete.
1095 // The argument passed to the callback is set to true if and only if
1096 // the update was performed synchronously.
1097 // If an asynchronous update is already pending when UpdateDiff is called,
1098 // UpdateDiff does not schedule another update, in which case the callback
1100 func (b *Buffer) UpdateDiff(callback func(bool)) {
1101 if b.updateDiffTimer != nil {
1105 lineCount := b.LinesNum()
1106 if b.diffBaseLineCount > lineCount {
1107 lineCount = b.diffBaseLineCount
1110 if lineCount < 1000 {
1113 } else if lineCount < 30000 {
1114 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1115 b.updateDiffTimer = nil
1120 // Don't compute diffs for very large files
1122 b.diff = make(map[int]DiffStatus)
1128 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1129 func (b *Buffer) SetDiffBase(diffBase []byte) {
1130 b.diffBase = diffBase
1131 if diffBase == nil {
1132 b.diffBaseLineCount = 0
1134 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1136 b.UpdateDiff(func(synchronous bool) {
1141 // DiffStatus returns the diff status for a line in the buffer
1142 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1144 defer b.diffLock.RUnlock()
1145 // Note that the zero value for DiffStatus is equal to DSUnchanged
1146 return b.diff[lineN]
1149 // WriteLog writes a string to the log buffer
1150 func WriteLog(s string) {
1151 LogBuf.EventHandler.Insert(LogBuf.End(), s)
1154 // GetLogBuf returns the log buffer
1155 func GetLogBuf() *Buffer {