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 start = util.Clamp(start, 0, len(b.lines)-1)
150 end = util.Clamp(end, 0, len(b.lines)-1)
152 if b.Settings["syntax"].(bool) && b.SyntaxDef != nil {
154 for i := start; i <= end; i++ {
155 l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
157 b.Highlighter.HighlightMatches(b, start, l)
160 for i := start; i <= end; i++ {
161 b.LineArray.invalidateSearchMatches(i)
165 // DisableReload disables future reloads of this sharedbuffer
166 func (b *SharedBuffer) DisableReload() {
167 b.ReloadDisabled = true
179 // Buffer stores the main information about a currently open file including
180 // the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
181 // all the cursors, the syntax highlighting info, the settings for the buffer
182 // and some misc info about modification time and path location.
183 // The syntax highlighting info must be stored with the buffer because the syntax
184 // highlighter attaches information to each line of the buffer for optimization
185 // purposes so it doesn't have to rehighlight everything on every update.
186 // Likewise for the search highlighting.
196 // OptionCallback is called after a buffer option value is changed.
197 // The display module registers its OptionCallback to ensure the buffer window
198 // is properly updated when needed. This is a workaround for the fact that
199 // the buffer module cannot directly call the display's API (it would mean
200 // a circular dependency between packages).
201 OptionCallback func(option string, nativeValue interface{})
203 // The display module registers its own GetVisualX function for getting
204 // the correct visual x location of a cursor when softwrap is used.
205 // This is hacky. Maybe it would be better to move all the visual x logic
206 // from buffer to display, but it would require rewriting a lot of code.
207 GetVisualX func(loc Loc) int
209 // Last search stores the last successful search
212 // HighlightSearch enables highlighting all instances of the last successful search
216 // NewBufferFromFileAtLoc opens a new buffer with a given cursor location
217 // If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
218 // would otherwise be (start of file, or saved cursor position if `savecursor` is
220 func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
223 if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
224 var cursorPos []string
225 filename, cursorPos = util.GetPathAndCursorPosition(filename)
226 cursorLoc, err = ParseCursorLocation(cursorPos)
228 cursorLoc = Loc{-1, -1}
232 filename, err = util.ReplaceHome(filename)
237 f, err := os.OpenFile(filename, os.O_WRONLY, 0)
238 readonly := os.IsPermission(err)
241 fileInfo, serr := os.Stat(filename)
242 if serr != nil && !os.IsNotExist(serr) {
245 if serr == nil && fileInfo.IsDir() {
246 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
249 file, err := os.Open(filename)
255 if os.IsNotExist(err) {
256 // File does not exist -- create an empty buffer with that name
257 buf = NewBufferFromString("", filename, btype)
258 } else if err != nil {
261 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
263 return nil, errors.New("could not open file")
267 if readonly && prompt != nil {
268 prompt.Message(fmt.Sprintf("Warning: file is readonly - %s will be attempted when saving", config.GlobalSettings["sucmd"].(string)))
269 // buf.SetOptionNative("readonly", true)
275 // NewBufferFromFile opens a new buffer using the given path
276 // It will also automatically handle `~`, and line/column with filename:l:c
277 // It will return an empty buffer if the path does not exist
278 // and an error if the file is a directory
279 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
280 return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
283 // NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
284 func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
285 return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
288 // NewBufferFromString creates a new buffer containing the given string
289 func NewBufferFromString(text, path string, btype BufType) *Buffer {
290 return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
293 // NewBuffer creates a new buffer from a given reader with a given path
294 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
296 // Places the cursor at startcursor. If startcursor is -1, -1 places the
297 // cursor at an autodetected location (based on savecursor or :LINE:COL)
298 func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
299 absPath, err := filepath.Abs(path)
308 for _, buf := range OpenBuffers {
309 if buf.AbsPath == absPath && buf.Type != BTInfo {
311 b.SharedBuffer = buf.SharedBuffer
312 b.EventHandler = buf.EventHandler
319 b.SharedBuffer = new(SharedBuffer)
325 // this is a little messy since we need to know some settings to read
326 // the file properly, but some settings depend on the filetype, which
327 // we don't know until reading the file. We first read the settings
328 // into a local variable and then use that to determine the encoding,
329 // readonly, and fileformat necessary for reading the file and
330 // assigning the filetype.
331 settings := config.DefaultCommonSettings()
332 b.Settings = config.DefaultCommonSettings()
333 for k, v := range config.GlobalSettings {
334 if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
335 // make sure setting is not global-only
340 config.InitLocalSettings(settings, absPath)
341 b.Settings["readonly"] = settings["readonly"]
342 b.Settings["filetype"] = settings["filetype"]
343 b.Settings["syntax"] = settings["syntax"]
345 enc, err := htmlindex.Get(settings["encoding"].(string))
348 b.Settings["encoding"] = "utf-8"
352 hasBackup, ok = b.ApplyBackup(size)
355 return NewBufferFromString("", "", btype)
358 reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
360 var ff FileFormat = FFAuto
363 // for empty files, use the fileformat setting instead of
365 switch settings["fileformat"] {
373 b.LineArray = NewLineArray(uint64(size), ff, reader)
375 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
377 // The last time this file was modified
381 if b.Settings["readonly"].(bool) && b.Type == BTDefault {
382 b.Type.Readonly = true
387 b.Settings["fileformat"] = "unix"
389 b.Settings["fileformat"] = "dos"
393 // init local settings again now that we know the filetype
394 config.InitLocalSettings(b.Settings, b.Path)
396 if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
397 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
400 if startcursor.X != -1 && startcursor.Y != -1 {
401 b.StartCursor = startcursor
402 } else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
403 err := b.Unserialize()
405 screen.TermMessage(err)
409 b.AddCursor(NewCursor(b, b.StartCursor))
410 b.GetActiveCursor().Relocate()
412 if !b.Settings["fastdirty"].(bool) && !found {
413 if size > LargeFileThreshold {
414 // If the file is larger than LargeFileThreshold fastdirty needs to be on
415 b.Settings["fastdirty"] = true
416 } else if !hasBackup {
417 // since applying a backup does not save the applied backup to disk, we should
418 // not calculate the original hash based on the backup data
419 calcHash(b, &b.origHash)
423 err := config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
425 screen.TermMessage(err)
428 OpenBuffers = append(OpenBuffers, b)
433 // Close removes this buffer from the list of open buffers
434 func (b *Buffer) Close() {
435 for i, buf := range OpenBuffers {
438 copy(OpenBuffers[i:], OpenBuffers[i+1:])
439 OpenBuffers[len(OpenBuffers)-1] = nil
440 OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
446 // Fini should be called when a buffer is closed and performs
448 func (b *Buffer) Fini() {
454 if b.Type == BTStdout {
455 fmt.Fprint(util.Stdout, string(b.Bytes()))
458 atomic.StoreInt32(&(b.fini), int32(1))
461 // GetName returns the name that should be displayed in the statusline
463 func (b *Buffer) GetName() string {
471 if b.Settings["basename"].(bool) {
472 return path.Base(name)
477 //SetName changes the name for this buffer
478 func (b *Buffer) SetName(s string) {
482 // Insert inserts the given string of text at the start location
483 func (b *Buffer) Insert(start Loc, text string) {
484 if !b.Type.Readonly {
485 b.EventHandler.cursors = b.cursors
486 b.EventHandler.active = b.curCursor
487 b.EventHandler.Insert(start, text)
493 // Remove removes the characters between the start and end locations
494 func (b *Buffer) Remove(start, end Loc) {
495 if !b.Type.Readonly {
496 b.EventHandler.cursors = b.cursors
497 b.EventHandler.active = b.curCursor
498 b.EventHandler.Remove(start, end)
504 // FileType returns the buffer's filetype
505 func (b *Buffer) FileType() string {
506 return b.Settings["filetype"].(string)
509 // ExternallyModified returns whether the file being edited has
510 // been modified by some external process
511 func (b *Buffer) ExternallyModified() bool {
512 modTime, err := util.GetModTime(b.Path)
514 return modTime != b.ModTime
519 // UpdateModTime updates the modtime of this file
520 func (b *Buffer) UpdateModTime() (err error) {
521 b.ModTime, err = util.GetModTime(b.Path)
525 // ReOpen reloads the current buffer from disk
526 func (b *Buffer) ReOpen() error {
527 file, err := os.Open(b.Path)
532 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
537 reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
538 data, err := ioutil.ReadAll(reader)
544 b.EventHandler.ApplyDiff(txt)
546 err = b.UpdateModTime()
547 if !b.Settings["fastdirty"].(bool) {
548 calcHash(b, &b.origHash)
555 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
556 func (b *Buffer) RelocateCursors() {
557 for _, c := range b.cursors {
562 // RuneAt returns the rune at a given location in the buffer
563 func (b *Buffer) RuneAt(loc Loc) rune {
564 line := b.LineBytes(loc.Y)
568 r, _, size := util.DecodeCharacter(line)
581 // WordAt returns the word around a given location in the buffer
582 func (b *Buffer) WordAt(loc Loc) []byte {
583 if len(b.LineBytes(loc.Y)) == 0 || !util.IsWordChar(b.RuneAt(loc)) {
588 end := loc.Move(1, b)
590 for start.X > 0 && util.IsWordChar(b.RuneAt(start.Move(-1, b))) {
594 lineLen := util.CharacterCount(b.LineBytes(loc.Y))
595 for end.X < lineLen && util.IsWordChar(b.RuneAt(end)) {
599 return b.Substr(start, end)
602 // Modified returns if this buffer has been modified since
604 func (b *Buffer) Modified() bool {
609 if b.Settings["fastdirty"].(bool) {
613 var buff [md5.Size]byte
616 return buff != b.origHash
619 // Size returns the number of bytes in the current buffer
620 func (b *Buffer) Size() int {
622 for i := 0; i < b.LinesNum(); i++ {
623 nb += len(b.LineBytes(i))
625 if i != b.LinesNum()-1 {
626 if b.Endings == FFDos {
627 nb++ // carriage return
635 // calcHash calculates md5 hash of all lines in the buffer
636 func calcHash(b *Buffer, out *[md5.Size]byte) error {
640 if len(b.lines) > 0 {
641 n, e := h.Write(b.lines[0].data)
647 for _, l := range b.lines[1:] {
648 n, e = h.Write([]byte{'\n'})
653 n, e = h.Write(l.data)
661 if size > LargeFileThreshold {
662 return ErrFileTooLarge
669 // UpdateRules updates the syntax rules and filetype for this buffer
670 // This is called when the colorscheme changes
671 func (b *Buffer) UpdateRules() {
675 ft := b.Settings["filetype"].(string)
681 var header *highlight.Header
682 // search for the syntax file in the user's custom syntax files
683 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
684 data, err := f.Data()
686 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
690 header, err = highlight.MakeHeaderYaml(data)
692 screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
694 file, err := highlight.ParseFile(data)
696 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
700 if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
701 syndef, err := highlight.ParseDef(file, header)
703 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
707 syntaxFile = f.Name()
713 // search in the default syntax files
714 for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
715 data, err := f.Data()
717 screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
721 header, err = highlight.MakeHeader(data)
723 screen.TermMessage("Error reading syntax header file", f.Name(), err)
727 if ft == "unknown" || ft == "" {
728 if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
729 syntaxFile = f.Name()
732 } else if header.FileType == ft {
733 syntaxFile = f.Name()
738 if syntaxFile != "" && !foundDef {
739 // we found a syntax file using a syntax header file
740 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
741 if f.Name() == syntaxFile {
742 data, err := f.Data()
744 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
748 file, err := highlight.ParseFile(data)
750 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
754 syndef, err := highlight.ParseDef(file, header)
756 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
765 if b.SyntaxDef != nil && highlight.HasIncludes(b.SyntaxDef) {
766 includes := highlight.GetIncludes(b.SyntaxDef)
768 var files []*highlight.File
769 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
770 data, err := f.Data()
772 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
775 header, err := highlight.MakeHeaderYaml(data)
777 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
781 for _, i := range includes {
782 if header.FileType == i {
783 file, err := highlight.ParseFile(data)
785 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
788 files = append(files, file)
792 if len(files) >= len(includes) {
797 highlight.ResolveIncludes(b.SyntaxDef, files)
800 if b.Highlighter == nil || syntaxFile != "" {
801 if b.SyntaxDef != nil {
802 b.Settings["filetype"] = b.SyntaxDef.FileType
805 b.SyntaxDef = &highlight.EmptyDef
808 if b.SyntaxDef != nil {
809 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
810 if b.Settings["syntax"].(bool) {
812 b.Highlighter.HighlightStates(b)
813 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
820 // ClearMatches clears all of the syntax highlighting for the buffer
821 func (b *Buffer) ClearMatches() {
822 for i := range b.lines {
828 // IndentString returns this buffer's indent method (a tabstop or n spaces
829 // depending on the settings)
830 func (b *Buffer) IndentString(tabsize int) string {
831 if b.Settings["tabstospaces"].(bool) {
832 return util.Spaces(tabsize)
837 // SetCursors resets this buffer's cursors to a new list
838 func (b *Buffer) SetCursors(c []*Cursor) {
840 b.EventHandler.cursors = b.cursors
841 b.EventHandler.active = b.curCursor
844 // AddCursor adds a new cursor to the list
845 func (b *Buffer) AddCursor(c *Cursor) {
846 b.cursors = append(b.cursors, c)
847 b.EventHandler.cursors = b.cursors
848 b.EventHandler.active = b.curCursor
852 // SetCurCursor sets the current cursor
853 func (b *Buffer) SetCurCursor(n int) {
857 // GetActiveCursor returns the main cursor in this buffer
858 func (b *Buffer) GetActiveCursor() *Cursor {
859 return b.cursors[b.curCursor]
862 // GetCursor returns the nth cursor
863 func (b *Buffer) GetCursor(n int) *Cursor {
867 // GetCursors returns the list of cursors in this buffer
868 func (b *Buffer) GetCursors() []*Cursor {
872 // NumCursors returns the number of cursors
873 func (b *Buffer) NumCursors() int {
874 return len(b.cursors)
877 // MergeCursors merges any cursors that are at the same position
879 func (b *Buffer) MergeCursors() {
880 var cursors []*Cursor
881 for i := 0; i < len(b.cursors); i++ {
884 for j := 0; j < len(b.cursors); j++ {
886 if c2 != nil && i != j && c1.Loc == c2.Loc {
890 cursors = append(cursors, c1)
896 for i := range b.cursors {
900 if b.curCursor >= len(b.cursors) {
901 b.curCursor = len(b.cursors) - 1
903 b.EventHandler.cursors = b.cursors
904 b.EventHandler.active = b.curCursor
907 // UpdateCursors updates all the cursors indicies
908 func (b *Buffer) UpdateCursors() {
909 b.EventHandler.cursors = b.cursors
910 b.EventHandler.active = b.curCursor
911 for i, c := range b.cursors {
916 func (b *Buffer) RemoveCursor(i int) {
917 copy(b.cursors[i:], b.cursors[i+1:])
918 b.cursors[len(b.cursors)-1] = nil
919 b.cursors = b.cursors[:len(b.cursors)-1]
920 b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
924 // ClearCursors removes all extra cursors
925 func (b *Buffer) ClearCursors() {
926 for i := 1; i < len(b.cursors); i++ {
929 b.cursors = b.cursors[:1]
932 b.GetActiveCursor().ResetSelection()
935 // MoveLinesUp moves the range of lines up one row
936 func (b *Buffer) MoveLinesUp(start int, end int) {
937 if start < 1 || start >= end || end > len(b.lines) {
940 l := string(b.LineBytes(start - 1))
941 if end == len(b.lines) {
944 util.CharacterCount(b.lines[end-1].data),
960 // MoveLinesDown moves the range of lines down one row
961 func (b *Buffer) MoveLinesDown(start int, end int) {
962 if start < 0 || start >= end || end >= len(b.lines) {
965 l := string(b.LineBytes(end))
977 var BracePairs = [][2]rune{
983 // FindMatchingBrace returns the location in the buffer of the matching bracket
984 // It is given a brace type containing the open and closing character, (for example
985 // '{' and '}') as well as the location to match from
986 // TODO: maybe can be more efficient with utf8 package
987 // returns the location of the matching brace
988 // if the boolean returned is true then the original matching brace is one character left
989 // of the starting location
990 func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, bool) {
991 curLine := []rune(string(b.LineBytes(start.Y)))
993 if start.X >= 0 && start.X < len(curLine) {
994 startChar = curLine[start.X]
997 if start.X-1 >= 0 && start.X-1 < len(curLine) {
998 leftChar = curLine[start.X-1]
1001 if startChar == braceType[0] || leftChar == braceType[0] {
1002 for y := start.Y; y < b.LinesNum(); y++ {
1003 l := []rune(string(b.LineBytes(y)))
1006 if startChar == braceType[0] {
1012 for x := xInit; x < len(l); x++ {
1014 if r == braceType[0] {
1016 } else if r == braceType[1] {
1019 if startChar == braceType[0] {
1020 return Loc{x, y}, false, true
1022 return Loc{x, y}, true, true
1027 } else if startChar == braceType[1] || leftChar == braceType[1] {
1028 for y := start.Y; y >= 0; y-- {
1029 l := []rune(string(b.lines[y].data))
1032 if leftChar == braceType[1] {
1038 for x := xInit; x >= 0; x-- {
1040 if r == braceType[0] {
1043 if leftChar == braceType[1] {
1044 return Loc{x, y}, true, true
1046 return Loc{x, y}, false, true
1048 } else if r == braceType[1] {
1054 return start, true, false
1057 // Retab changes all tabs to spaces or vice versa
1058 func (b *Buffer) Retab() {
1059 toSpaces := b.Settings["tabstospaces"].(bool)
1060 tabsize := util.IntOpt(b.Settings["tabsize"])
1063 for i := 0; i < b.LinesNum(); i++ {
1066 ws := util.GetLeadingWhitespace(l)
1069 ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
1071 ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
1075 l = bytes.TrimLeft(l, " \t")
1076 b.lines[i].data = append(ws, l...)
1077 b.MarkModified(i, i)
1081 b.isModified = dirty
1084 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
1086 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
1087 startpos := Loc{0, 0}
1090 // if no positions are available exit early
1091 if cursorPositions == nil {
1092 return startpos, errors.New("No cursor positions were provided.")
1095 startpos.Y, err = strconv.Atoi(cursorPositions[0])
1098 if len(cursorPositions) > 1 {
1099 startpos.X, err = strconv.Atoi(cursorPositions[1])
1106 return startpos, err
1109 // Line returns the string representation of the given line number
1110 func (b *Buffer) Line(i int) string {
1111 return string(b.LineBytes(i))
1114 func (b *Buffer) Write(bytes []byte) (n int, err error) {
1115 b.EventHandler.InsertBytes(b.End(), bytes)
1116 return len(bytes), nil
1119 func (b *Buffer) updateDiffSync() {
1121 defer b.diffLock.Unlock()
1123 b.diff = make(map[int]DiffStatus)
1125 if b.diffBase == nil {
1130 baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
1131 diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
1134 for _, diff := range diffs {
1135 lineCount := len([]rune(diff.Text))
1140 case dmp.DiffInsert:
1141 var status DiffStatus
1142 if b.diff[lineN] == DSDeletedAbove {
1147 for i := 0; i < lineCount; i++ {
1148 b.diff[lineN] = status
1151 case dmp.DiffDelete:
1152 b.diff[lineN] = DSDeletedAbove
1157 // UpdateDiff computes the diff between the diff base and the buffer content.
1158 // The update may be performed synchronously or asynchronously.
1159 // UpdateDiff calls the supplied callback when the update is complete.
1160 // The argument passed to the callback is set to true if and only if
1161 // the update was performed synchronously.
1162 // If an asynchronous update is already pending when UpdateDiff is called,
1163 // UpdateDiff does not schedule another update, in which case the callback
1165 func (b *Buffer) UpdateDiff(callback func(bool)) {
1166 if b.updateDiffTimer != nil {
1170 lineCount := b.LinesNum()
1171 if b.diffBaseLineCount > lineCount {
1172 lineCount = b.diffBaseLineCount
1175 if lineCount < 1000 {
1178 } else if lineCount < 30000 {
1179 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1180 b.updateDiffTimer = nil
1185 // Don't compute diffs for very large files
1187 b.diff = make(map[int]DiffStatus)
1193 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1194 func (b *Buffer) SetDiffBase(diffBase []byte) {
1195 b.diffBase = diffBase
1196 if diffBase == nil {
1197 b.diffBaseLineCount = 0
1199 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1201 b.UpdateDiff(func(synchronous bool) {
1206 // DiffStatus returns the diff status for a line in the buffer
1207 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1209 defer b.diffLock.RUnlock()
1210 // Note that the zero value for DiffStatus is equal to DSUnchanged
1211 return b.diff[lineN]
1214 // SearchMatch returns true if the given location is within a match of the last search.
1215 // It is used for search highlighting
1216 func (b *Buffer) SearchMatch(pos Loc) bool {
1217 return b.LineArray.SearchMatch(b, pos)
1220 // WriteLog writes a string to the log buffer
1221 func WriteLog(s string) {
1222 LogBuf.EventHandler.Insert(LogBuf.End(), s)
1225 // GetLogBuf returns the log buffer
1226 func GetLogBuf() *Buffer {