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.
193 // OptionCallback is called after a buffer option value is changed.
194 // The display module registers its OptionCallback to ensure the buffer window
195 // is properly updated when needed. This is a workaround for the fact that
196 // the buffer module cannot directly call the display's API (it would mean
197 // a circular dependency between packages).
198 OptionCallback func(option string, nativeValue interface{})
200 // The display module registers its own GetVisualX function for getting
201 // the correct visual x location of a cursor when softwrap is used.
202 // This is hacky. Maybe it would be better to move all the visual x logic
203 // from buffer to display, but it would require rewriting a lot of code.
204 GetVisualX func(loc Loc) int
207 // NewBufferFromFileAtLoc opens a new buffer with a given cursor location
208 // If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
209 // would otherwise be (start of file, or saved cursor position if `savecursor` is
211 func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
214 if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
215 var cursorPos []string
216 filename, cursorPos = util.GetPathAndCursorPosition(filename)
217 cursorLoc, err = ParseCursorLocation(cursorPos)
219 cursorLoc = Loc{-1, -1}
223 filename, err = util.ReplaceHome(filename)
228 f, err := os.OpenFile(filename, os.O_WRONLY, 0)
229 readonly := os.IsPermission(err)
232 fileInfo, serr := os.Stat(filename)
233 if serr != nil && !os.IsNotExist(serr) {
236 if serr == nil && fileInfo.IsDir() {
237 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
240 file, err := os.Open(filename)
246 if os.IsNotExist(err) {
247 // File does not exist -- create an empty buffer with that name
248 buf = NewBufferFromString("", filename, btype)
249 } else if err != nil {
252 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
254 return nil, errors.New("could not open file")
258 if readonly && prompt != nil {
259 prompt.Message("Warning: file is readonly - sudo will be attempted when saving")
260 // buf.SetOptionNative("readonly", true)
266 // NewBufferFromFile opens a new buffer using the given path
267 // It will also automatically handle `~`, and line/column with filename:l:c
268 // It will return an empty buffer if the path does not exist
269 // and an error if the file is a directory
270 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
271 return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
274 // NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
275 func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
276 return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
279 // NewBufferFromString creates a new buffer containing the given string
280 func NewBufferFromString(text, path string, btype BufType) *Buffer {
281 return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
284 // NewBuffer creates a new buffer from a given reader with a given path
285 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
287 // Places the cursor at startcursor. If startcursor is -1, -1 places the
288 // cursor at an autodetected location (based on savecursor or :LINE:COL)
289 func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
290 absPath, _ := filepath.Abs(path)
296 for _, buf := range OpenBuffers {
297 if buf.AbsPath == absPath && buf.Type != BTInfo {
299 b.SharedBuffer = buf.SharedBuffer
300 b.EventHandler = buf.EventHandler
307 b.SharedBuffer = new(SharedBuffer)
313 // this is a little messy since we need to know some settings to read
314 // the file properly, but some settings depend on the filetype, which
315 // we don't know until reading the file. We first read the settings
316 // into a local variable and then use that to determine the encoding,
317 // readonly, and fileformat necessary for reading the file and
318 // assigning the filetype.
319 settings := config.DefaultCommonSettings()
320 b.Settings = config.DefaultCommonSettings()
321 for k, v := range config.GlobalSettings {
322 if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
323 // make sure setting is not global-only
328 config.InitLocalSettings(settings, path)
329 b.Settings["readonly"] = settings["readonly"]
330 b.Settings["filetype"] = settings["filetype"]
331 b.Settings["syntax"] = settings["syntax"]
333 enc, err := htmlindex.Get(settings["encoding"].(string))
336 b.Settings["encoding"] = "utf-8"
340 hasBackup, ok = b.ApplyBackup(size)
343 return NewBufferFromString("", "", btype)
346 reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
348 var ff FileFormat = FFAuto
351 // for empty files, use the fileformat setting instead of
353 switch settings["fileformat"] {
361 b.LineArray = NewLineArray(uint64(size), ff, reader)
363 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
365 // The last time this file was modified
369 if b.Settings["readonly"].(bool) && b.Type == BTDefault {
370 b.Type.Readonly = true
375 b.Settings["fileformat"] = "unix"
377 b.Settings["fileformat"] = "dos"
381 // init local settings again now that we know the filetype
382 config.InitLocalSettings(b.Settings, b.Path)
384 if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
385 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
388 if startcursor.X != -1 && startcursor.Y != -1 {
389 b.StartCursor = startcursor
390 } else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
391 err := b.Unserialize()
393 screen.TermMessage(err)
397 b.AddCursor(NewCursor(b, b.StartCursor))
398 b.GetActiveCursor().Relocate()
400 if !b.Settings["fastdirty"].(bool) && !found {
401 if size > LargeFileThreshold {
402 // If the file is larger than LargeFileThreshold fastdirty needs to be on
403 b.Settings["fastdirty"] = true
404 } else if !hasBackup {
405 // since applying a backup does not save the applied backup to disk, we should
406 // not calculate the original hash based on the backup data
407 calcHash(b, &b.origHash)
411 err := config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
413 screen.TermMessage(err)
416 OpenBuffers = append(OpenBuffers, b)
421 // Close removes this buffer from the list of open buffers
422 func (b *Buffer) Close() {
423 for i, buf := range OpenBuffers {
426 copy(OpenBuffers[i:], OpenBuffers[i+1:])
427 OpenBuffers[len(OpenBuffers)-1] = nil
428 OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
434 // Fini should be called when a buffer is closed and performs
436 func (b *Buffer) Fini() {
442 if b.Type == BTStdout {
443 fmt.Fprint(util.Stdout, string(b.Bytes()))
446 atomic.StoreInt32(&(b.fini), int32(1))
449 // GetName returns the name that should be displayed in the statusline
451 func (b *Buffer) GetName() string {
459 if b.Settings["basename"].(bool) {
460 return path.Base(name)
465 //SetName changes the name for this buffer
466 func (b *Buffer) SetName(s string) {
470 // Insert inserts the given string of text at the start location
471 func (b *Buffer) Insert(start Loc, text string) {
472 if !b.Type.Readonly {
473 b.EventHandler.cursors = b.cursors
474 b.EventHandler.active = b.curCursor
475 b.EventHandler.Insert(start, text)
481 // Remove removes the characters between the start and end locations
482 func (b *Buffer) Remove(start, end Loc) {
483 if !b.Type.Readonly {
484 b.EventHandler.cursors = b.cursors
485 b.EventHandler.active = b.curCursor
486 b.EventHandler.Remove(start, end)
492 // FileType returns the buffer's filetype
493 func (b *Buffer) FileType() string {
494 return b.Settings["filetype"].(string)
497 // ExternallyModified returns whether the file being edited has
498 // been modified by some external process
499 func (b *Buffer) ExternallyModified() bool {
500 modTime, err := util.GetModTime(b.Path)
502 return modTime != b.ModTime
507 // UpdateModTime updates the modtime of this file
508 func (b *Buffer) UpdateModTime() (err error) {
509 b.ModTime, err = util.GetModTime(b.Path)
513 // ReOpen reloads the current buffer from disk
514 func (b *Buffer) ReOpen() error {
515 file, err := os.Open(b.Path)
520 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
525 reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
526 data, err := ioutil.ReadAll(reader)
532 b.EventHandler.ApplyDiff(txt)
534 err = b.UpdateModTime()
535 if !b.Settings["fastdirty"].(bool) {
536 calcHash(b, &b.origHash)
543 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
544 func (b *Buffer) RelocateCursors() {
545 for _, c := range b.cursors {
550 // RuneAt returns the rune at a given location in the buffer
551 func (b *Buffer) RuneAt(loc Loc) rune {
552 line := b.LineBytes(loc.Y)
556 r, _, size := util.DecodeCharacter(line)
569 // WordAt returns the word around a given location in the buffer
570 func (b *Buffer) WordAt(loc Loc) []byte {
571 if len(b.LineBytes(loc.Y)) == 0 || !util.IsWordChar(b.RuneAt(loc)) {
576 end := loc.Move(1, b)
578 for start.X > 0 && util.IsWordChar(b.RuneAt(start.Move(-1, b))) {
582 lineLen := util.CharacterCount(b.LineBytes(loc.Y))
583 for end.X < lineLen && util.IsWordChar(b.RuneAt(end)) {
587 return b.Substr(start, end)
590 // Modified returns if this buffer has been modified since
592 func (b *Buffer) Modified() bool {
597 if b.Settings["fastdirty"].(bool) {
601 var buff [md5.Size]byte
604 return buff != b.origHash
607 // Size returns the number of bytes in the current buffer
608 func (b *Buffer) Size() int {
610 for i := 0; i < b.LinesNum(); i++ {
611 nb += len(b.LineBytes(i))
613 if i != b.LinesNum()-1 {
614 if b.Endings == FFDos {
615 nb++ // carriage return
623 // calcHash calculates md5 hash of all lines in the buffer
624 func calcHash(b *Buffer, out *[md5.Size]byte) error {
628 if len(b.lines) > 0 {
629 n, e := h.Write(b.lines[0].data)
635 for _, l := range b.lines[1:] {
636 n, e = h.Write([]byte{'\n'})
641 n, e = h.Write(l.data)
649 if size > LargeFileThreshold {
650 return ErrFileTooLarge
657 // UpdateRules updates the syntax rules and filetype for this buffer
658 // This is called when the colorscheme changes
659 func (b *Buffer) UpdateRules() {
663 ft := b.Settings["filetype"].(string)
669 var header *highlight.Header
670 // search for the syntax file in the user's custom syntax files
671 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
672 data, err := f.Data()
674 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
678 header, err = highlight.MakeHeaderYaml(data)
680 screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
682 file, err := highlight.ParseFile(data)
684 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
688 if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
689 syndef, err := highlight.ParseDef(file, header)
691 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
695 syntaxFile = f.Name()
701 // search in the default syntax files
702 for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
703 data, err := f.Data()
705 screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
709 header, err = highlight.MakeHeader(data)
711 screen.TermMessage("Error reading syntax header file", f.Name(), err)
715 if ft == "unknown" || ft == "" {
716 if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
717 syntaxFile = f.Name()
720 } else if header.FileType == ft {
721 syntaxFile = f.Name()
726 if syntaxFile != "" && !foundDef {
727 // we found a syntax file using a syntax header file
728 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
729 if f.Name() == syntaxFile {
730 data, err := f.Data()
732 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
736 file, err := highlight.ParseFile(data)
738 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
742 syndef, err := highlight.ParseDef(file, header)
744 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
753 if b.SyntaxDef != nil && highlight.HasIncludes(b.SyntaxDef) {
754 includes := highlight.GetIncludes(b.SyntaxDef)
756 var files []*highlight.File
757 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
758 data, err := f.Data()
760 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
763 header, err := highlight.MakeHeaderYaml(data)
765 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
769 for _, i := range includes {
770 if header.FileType == i {
771 file, err := highlight.ParseFile(data)
773 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
776 files = append(files, file)
780 if len(files) >= len(includes) {
785 highlight.ResolveIncludes(b.SyntaxDef, files)
788 if b.Highlighter == nil || syntaxFile != "" {
789 if b.SyntaxDef != nil {
790 b.Settings["filetype"] = b.SyntaxDef.FileType
793 b.SyntaxDef = &highlight.EmptyDef
796 if b.SyntaxDef != nil {
797 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
798 if b.Settings["syntax"].(bool) {
800 b.Highlighter.HighlightStates(b)
801 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
808 // ClearMatches clears all of the syntax highlighting for the buffer
809 func (b *Buffer) ClearMatches() {
810 for i := range b.lines {
816 // IndentString returns this buffer's indent method (a tabstop or n spaces
817 // depending on the settings)
818 func (b *Buffer) IndentString(tabsize int) string {
819 if b.Settings["tabstospaces"].(bool) {
820 return util.Spaces(tabsize)
825 // SetCursors resets this buffer's cursors to a new list
826 func (b *Buffer) SetCursors(c []*Cursor) {
828 b.EventHandler.cursors = b.cursors
829 b.EventHandler.active = b.curCursor
832 // AddCursor adds a new cursor to the list
833 func (b *Buffer) AddCursor(c *Cursor) {
834 b.cursors = append(b.cursors, c)
835 b.EventHandler.cursors = b.cursors
836 b.EventHandler.active = b.curCursor
840 // SetCurCursor sets the current cursor
841 func (b *Buffer) SetCurCursor(n int) {
845 // GetActiveCursor returns the main cursor in this buffer
846 func (b *Buffer) GetActiveCursor() *Cursor {
847 return b.cursors[b.curCursor]
850 // GetCursor returns the nth cursor
851 func (b *Buffer) GetCursor(n int) *Cursor {
855 // GetCursors returns the list of cursors in this buffer
856 func (b *Buffer) GetCursors() []*Cursor {
860 // NumCursors returns the number of cursors
861 func (b *Buffer) NumCursors() int {
862 return len(b.cursors)
865 // MergeCursors merges any cursors that are at the same position
867 func (b *Buffer) MergeCursors() {
868 var cursors []*Cursor
869 for i := 0; i < len(b.cursors); i++ {
872 for j := 0; j < len(b.cursors); j++ {
874 if c2 != nil && i != j && c1.Loc == c2.Loc {
878 cursors = append(cursors, c1)
884 for i := range b.cursors {
888 if b.curCursor >= len(b.cursors) {
889 b.curCursor = len(b.cursors) - 1
891 b.EventHandler.cursors = b.cursors
892 b.EventHandler.active = b.curCursor
895 // UpdateCursors updates all the cursors indicies
896 func (b *Buffer) UpdateCursors() {
897 b.EventHandler.cursors = b.cursors
898 b.EventHandler.active = b.curCursor
899 for i, c := range b.cursors {
904 func (b *Buffer) RemoveCursor(i int) {
905 copy(b.cursors[i:], b.cursors[i+1:])
906 b.cursors[len(b.cursors)-1] = nil
907 b.cursors = b.cursors[:len(b.cursors)-1]
908 b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
912 // ClearCursors removes all extra cursors
913 func (b *Buffer) ClearCursors() {
914 for i := 1; i < len(b.cursors); i++ {
917 b.cursors = b.cursors[:1]
920 b.GetActiveCursor().ResetSelection()
923 // MoveLinesUp moves the range of lines up one row
924 func (b *Buffer) MoveLinesUp(start int, end int) {
925 if start < 1 || start >= end || end > len(b.lines) {
928 l := string(b.LineBytes(start - 1))
929 if end == len(b.lines) {
932 util.CharacterCount(b.lines[end-1].data),
948 // MoveLinesDown moves the range of lines down one row
949 func (b *Buffer) MoveLinesDown(start int, end int) {
950 if start < 0 || start >= end || end >= len(b.lines) {
953 l := string(b.LineBytes(end))
965 var BracePairs = [][2]rune{
971 // FindMatchingBrace returns the location in the buffer of the matching bracket
972 // It is given a brace type containing the open and closing character, (for example
973 // '{' and '}') as well as the location to match from
974 // TODO: maybe can be more efficient with utf8 package
975 // returns the location of the matching brace
976 // if the boolean returned is true then the original matching brace is one character left
977 // of the starting location
978 func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, bool) {
979 curLine := []rune(string(b.LineBytes(start.Y)))
981 if start.X >= 0 && start.X < len(curLine) {
982 startChar = curLine[start.X]
985 if start.X-1 >= 0 && start.X-1 < len(curLine) {
986 leftChar = curLine[start.X-1]
989 if startChar == braceType[0] || leftChar == braceType[0] {
990 for y := start.Y; y < b.LinesNum(); y++ {
991 l := []rune(string(b.LineBytes(y)))
994 if startChar == braceType[0] {
1000 for x := xInit; x < len(l); x++ {
1002 if r == braceType[0] {
1004 } else if r == braceType[1] {
1007 if startChar == braceType[0] {
1008 return Loc{x, y}, false, true
1010 return Loc{x, y}, true, true
1015 } else if startChar == braceType[1] || leftChar == braceType[1] {
1016 for y := start.Y; y >= 0; y-- {
1017 l := []rune(string(b.lines[y].data))
1020 if leftChar == braceType[1] {
1026 for x := xInit; x >= 0; x-- {
1028 if r == braceType[0] {
1031 if leftChar == braceType[1] {
1032 return Loc{x, y}, true, true
1034 return Loc{x, y}, false, true
1036 } else if r == braceType[1] {
1042 return start, true, false
1045 // Retab changes all tabs to spaces or vice versa
1046 func (b *Buffer) Retab() {
1047 toSpaces := b.Settings["tabstospaces"].(bool)
1048 tabsize := util.IntOpt(b.Settings["tabsize"])
1051 for i := 0; i < b.LinesNum(); i++ {
1054 ws := util.GetLeadingWhitespace(l)
1057 ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
1059 ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
1063 l = bytes.TrimLeft(l, " \t")
1064 b.lines[i].data = append(ws, l...)
1065 b.MarkModified(i, i)
1069 b.isModified = dirty
1072 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
1074 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
1075 startpos := Loc{0, 0}
1078 // if no positions are available exit early
1079 if cursorPositions == nil {
1080 return startpos, errors.New("No cursor positions were provided.")
1083 startpos.Y, err = strconv.Atoi(cursorPositions[0])
1086 if len(cursorPositions) > 1 {
1087 startpos.X, err = strconv.Atoi(cursorPositions[1])
1094 return startpos, err
1097 // Line returns the string representation of the given line number
1098 func (b *Buffer) Line(i int) string {
1099 return string(b.LineBytes(i))
1102 func (b *Buffer) Write(bytes []byte) (n int, err error) {
1103 b.EventHandler.InsertBytes(b.End(), bytes)
1104 return len(bytes), nil
1107 func (b *Buffer) updateDiffSync() {
1109 defer b.diffLock.Unlock()
1111 b.diff = make(map[int]DiffStatus)
1113 if b.diffBase == nil {
1118 baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
1119 diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
1122 for _, diff := range diffs {
1123 lineCount := len([]rune(diff.Text))
1128 case dmp.DiffInsert:
1129 var status DiffStatus
1130 if b.diff[lineN] == DSDeletedAbove {
1135 for i := 0; i < lineCount; i++ {
1136 b.diff[lineN] = status
1139 case dmp.DiffDelete:
1140 b.diff[lineN] = DSDeletedAbove
1145 // UpdateDiff computes the diff between the diff base and the buffer content.
1146 // The update may be performed synchronously or asynchronously.
1147 // UpdateDiff calls the supplied callback when the update is complete.
1148 // The argument passed to the callback is set to true if and only if
1149 // the update was performed synchronously.
1150 // If an asynchronous update is already pending when UpdateDiff is called,
1151 // UpdateDiff does not schedule another update, in which case the callback
1153 func (b *Buffer) UpdateDiff(callback func(bool)) {
1154 if b.updateDiffTimer != nil {
1158 lineCount := b.LinesNum()
1159 if b.diffBaseLineCount > lineCount {
1160 lineCount = b.diffBaseLineCount
1163 if lineCount < 1000 {
1166 } else if lineCount < 30000 {
1167 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1168 b.updateDiffTimer = nil
1173 // Don't compute diffs for very large files
1175 b.diff = make(map[int]DiffStatus)
1181 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1182 func (b *Buffer) SetDiffBase(diffBase []byte) {
1183 b.diffBase = diffBase
1184 if diffBase == nil {
1185 b.diffBaseLineCount = 0
1187 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1189 b.UpdateDiff(func(synchronous bool) {
1194 // DiffStatus returns the diff status for a line in the buffer
1195 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1197 defer b.diffLock.RUnlock()
1198 // Note that the zero value for DiffStatus is equal to DSUnchanged
1199 return b.diff[lineN]
1202 // WriteLog writes a string to the log buffer
1203 func WriteLog(s string) {
1204 LogBuf.EventHandler.Insert(LogBuf.End(), s)
1207 // GetLogBuf returns the log buffer
1208 func GetLogBuf() *Buffer {