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"
29 "golang.org/x/text/encoding/htmlindex"
30 "golang.org/x/text/encoding/unicode"
31 "golang.org/x/text/transform"
34 const backupTime = 8000
37 // OpenBuffers is a list of the currently open buffers
39 // LogBuf is a reference to the log buffer which can be opened with the
44 // The BufType defines what kind of buffer this is
47 Readonly bool // The buffer cannot be edited
48 Scratch bool // The buffer cannot be saved
49 Syntax bool // Syntax highlighting is enabled
53 // BTDefault is a default buffer
54 BTDefault = BufType{0, false, false, true}
55 // BTHelp is a help buffer
56 BTHelp = BufType{1, true, true, true}
57 // BTLog is a log buffer
58 BTLog = BufType{2, true, true, false}
59 // BTScratch is a buffer that cannot be saved (for scratch work)
60 BTScratch = BufType{3, false, true, false}
61 // BTRaw is is a buffer that shows raw terminal events
62 BTRaw = BufType{4, false, true, false}
63 // BTInfo is a buffer for inputting information
64 BTInfo = BufType{5, false, true, false}
65 // BTStdout is a buffer that only writes to stdout
67 BTStdout = BufType{6, false, true, true}
69 // ErrFileTooLarge is returned when the file is too large to hash
70 // (fastdirty is automatically enabled)
71 ErrFileTooLarge = errors.New("File is too large to hash")
74 // SharedBuffer is a struct containing info that is shared among buffers
75 // that have the same file open
76 type SharedBuffer struct {
78 // Stores the last modification time of the file the buffer is pointing to
80 // Type of the buffer (e.g. help, raw, scratch etc..)
83 // Path to the file on disk
85 // Absolute path to the file on disk
87 // Name of the buffer on the status line
92 // Settings customized by the user
93 Settings map[string]interface{}
101 updateDiffTimer *time.Timer
103 diffBaseLineCount int
104 diffLock sync.RWMutex
105 diff map[int]DiffStatus
109 // ReloadDisabled allows the user to disable reloads if they
110 // are viewing a file that is constantly changing
114 // Whether or not suggestions can be autocompleted must be shared because
115 // it changes based on how the buffer has changed
118 // The Highlighter struct actually performs the highlighting
119 Highlighter *highlight.Highlighter
120 // SyntaxDef represents the syntax highlighting definition being used
121 // This stores the highlighting rules and filetype detection info
122 SyntaxDef *highlight.Def
124 ModifiedThisFrame bool
126 // Hash of the original buffer -- empty if fastdirty is on
127 origHash [md5.Size]byte
130 func (b *SharedBuffer) insert(pos Loc, value []byte) {
132 b.HasSuggestions = false
133 b.LineArray.insert(pos, value)
135 inslines := bytes.Count(value, []byte{'\n'})
136 b.MarkModified(pos.Y, pos.Y+inslines)
138 func (b *SharedBuffer) remove(start, end Loc) []byte {
140 b.HasSuggestions = false
141 defer b.MarkModified(start.Y, end.Y)
142 return b.LineArray.remove(start, end)
145 // MarkModified marks the buffer as modified for this frame
146 // and performs rehighlighting if syntax highlighting is enabled
147 func (b *SharedBuffer) MarkModified(start, end int) {
148 b.ModifiedThisFrame = true
150 start = util.Clamp(start, 0, len(b.lines)-1)
151 end = util.Clamp(end, 0, len(b.lines)-1)
153 if b.Settings["syntax"].(bool) && b.SyntaxDef != nil {
155 for i := start; i <= end; i++ {
156 l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
158 b.Highlighter.HighlightMatches(b, start, l)
161 for i := start; i <= end; i++ {
162 b.LineArray.invalidateSearchMatches(i)
166 // DisableReload disables future reloads of this sharedbuffer
167 func (b *SharedBuffer) DisableReload() {
168 b.ReloadDisabled = true
180 // Buffer stores the main information about a currently open file including
181 // the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
182 // all the cursors, the syntax highlighting info, the settings for the buffer
183 // and some misc info about modification time and path location.
184 // The syntax highlighting info must be stored with the buffer because the syntax
185 // highlighter attaches information to each line of the buffer for optimization
186 // purposes so it doesn't have to rehighlight everything on every update.
187 // Likewise for the search highlighting.
197 // OptionCallback is called after a buffer option value is changed.
198 // The display module registers its OptionCallback to ensure the buffer window
199 // is properly updated when needed. This is a workaround for the fact that
200 // the buffer module cannot directly call the display's API (it would mean
201 // a circular dependency between packages).
202 OptionCallback func(option string, nativeValue interface{})
204 // The display module registers its own GetVisualX function for getting
205 // the correct visual x location of a cursor when softwrap is used.
206 // This is hacky. Maybe it would be better to move all the visual x logic
207 // from buffer to display, but it would require rewriting a lot of code.
208 GetVisualX func(loc Loc) int
210 // Last search stores the last successful search
213 // HighlightSearch enables highlighting all instances of the last successful search
217 type retabReader struct {
218 scanner *bufio.Scanner
224 func newRetabReader(from io.Reader, enc encoding.Encoding, autoretab bool, toSpaces bool, tabsize int) io.Reader {
228 r := new(retabReader)
229 r.scanner = bufio.NewScanner(bufio.NewReader(transform.NewReader(from, enc.NewDecoder())))
230 r.toSpaces = toSpaces
235 func (r *retabReader) fillBuffer(required int) error {
236 for len(r.buffer) < required {
237 if r.scanner.Scan() {
238 line := retabLine([]byte(r.scanner.Text()), r.toSpaces, r.tabsize)
240 r.buffer = append(r.buffer, line...)
241 r.buffer = append(r.buffer, "\n"...)
243 if err := r.scanner.Err(); err != nil {
255 func (r *retabReader) Read(into []byte) (n int, err error) {
256 err = r.fillBuffer(len(into))
257 n = copy(into, r.buffer)
259 r.buffer = r.buffer[n:]
263 func retabLine(l []byte, toSpaces bool, tabsize int) []byte {
264 ws := util.GetLeadingWhitespace(l)
267 ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
269 ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
273 l = bytes.TrimLeft(l, " \t")
274 return append(ws, l...)
277 // NewBufferFromFileAtLoc opens a new buffer with a given cursor location
278 // If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
279 // would otherwise be (start of file, or saved cursor position if `savecursor` is
281 func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
284 if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
285 var cursorPos []string
286 filename, cursorPos = util.GetPathAndCursorPosition(filename)
287 cursorLoc, err = ParseCursorLocation(cursorPos)
289 cursorLoc = Loc{-1, -1}
293 filename, err = util.ReplaceHome(filename)
298 f, err := os.OpenFile(filename, os.O_WRONLY, 0)
299 readonly := os.IsPermission(err)
302 fileInfo, serr := os.Stat(filename)
303 if serr != nil && !os.IsNotExist(serr) {
306 if serr == nil && fileInfo.IsDir() {
307 return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
310 file, err := os.Open(filename)
316 if os.IsNotExist(err) {
317 // File does not exist -- create an empty buffer with that name
318 buf = NewBufferFromString("", filename, btype)
319 } else if err != nil {
322 buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
324 return nil, errors.New("could not open file")
328 if readonly && prompt != nil {
329 prompt.Message(fmt.Sprintf("Warning: file is readonly - %s will be attempted when saving", config.GlobalSettings["sucmd"].(string)))
330 // buf.SetOptionNative("readonly", true)
336 // NewBufferFromFile opens a new buffer using the given path
337 // It will also automatically handle `~`, and line/column with filename:l:c
338 // It will return an empty buffer if the path does not exist
339 // and an error if the file is a directory
340 func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
341 return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
344 // NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
345 func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
346 return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
349 // NewBufferFromString creates a new buffer containing the given string
350 func NewBufferFromString(text, path string, btype BufType) *Buffer {
351 return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
354 // NewBuffer creates a new buffer from a given reader with a given path
355 // Ensure that ReadSettings and InitGlobalSettings have been called before creating
357 // Places the cursor at startcursor. If startcursor is -1, -1 places the
358 // cursor at an autodetected location (based on savecursor or :LINE:COL)
359 func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
360 absPath, err := filepath.Abs(path)
369 for _, buf := range OpenBuffers {
370 if buf.AbsPath == absPath && buf.Type != BTInfo {
372 b.SharedBuffer = buf.SharedBuffer
373 b.EventHandler = buf.EventHandler
380 b.SharedBuffer = new(SharedBuffer)
386 // this is a little messy since we need to know some settings to read
387 // the file properly, but some settings depend on the filetype, which
388 // we don't know until reading the file. We first read the settings
389 // into a local variable and then use that to determine the encoding,
390 // readonly, and fileformat necessary for reading the file and
391 // assigning the filetype.
392 settings := config.DefaultCommonSettings()
393 b.Settings = config.DefaultCommonSettings()
394 for k, v := range config.GlobalSettings {
395 if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
396 // make sure setting is not global-only
401 config.InitLocalSettings(settings, absPath)
402 b.Settings["readonly"] = settings["readonly"]
403 b.Settings["filetype"] = settings["filetype"]
404 b.Settings["syntax"] = settings["syntax"]
406 enc, err := htmlindex.Get(settings["encoding"].(string))
409 b.Settings["encoding"] = "utf-8"
413 hasBackup, ok = b.ApplyBackup(size)
416 return NewBufferFromString("", "", btype)
419 autoretab := b.Settings["autoretab"].(bool)
420 toSpaces := b.Settings["tabstospaces"].(bool)
421 tabsize := util.IntOpt(b.Settings["tabsize"])
423 reader := newRetabReader(r, enc, autoretab, toSpaces, tabsize)
425 var ff FileFormat = FFAuto
428 // for empty files, use the fileformat setting instead of
430 switch settings["fileformat"] {
438 b.LineArray = NewLineArray(uint64(size), ff, reader)
440 b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
442 // The last time this file was modified
446 if b.Settings["readonly"].(bool) && b.Type == BTDefault {
447 b.Type.Readonly = true
452 b.Settings["fileformat"] = "unix"
454 b.Settings["fileformat"] = "dos"
458 // init local settings again now that we know the filetype
459 config.InitLocalSettings(b.Settings, b.Path)
461 if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
462 os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
465 if startcursor.X != -1 && startcursor.Y != -1 {
466 b.StartCursor = startcursor
467 } else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
468 err := b.Unserialize()
470 screen.TermMessage(err)
474 b.AddCursor(NewCursor(b, b.StartCursor))
475 b.GetActiveCursor().Relocate()
477 if !b.Settings["fastdirty"].(bool) && !found {
478 if size > LargeFileThreshold {
479 // If the file is larger than LargeFileThreshold fastdirty needs to be on
480 b.Settings["fastdirty"] = true
481 } else if !hasBackup {
482 // since applying a backup does not save the applied backup to disk, we should
483 // not calculate the original hash based on the backup data
484 calcHash(b, &b.origHash)
488 err = config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
490 screen.TermMessage(err)
493 OpenBuffers = append(OpenBuffers, b)
498 // Close removes this buffer from the list of open buffers
499 func (b *Buffer) Close() {
500 for i, buf := range OpenBuffers {
503 copy(OpenBuffers[i:], OpenBuffers[i+1:])
504 OpenBuffers[len(OpenBuffers)-1] = nil
505 OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
511 // Fini should be called when a buffer is closed and performs
513 func (b *Buffer) Fini() {
519 if b.Type == BTStdout {
520 fmt.Fprint(util.Stdout, string(b.Bytes()))
523 atomic.StoreInt32(&(b.fini), int32(1))
526 // GetName returns the name that should be displayed in the statusline
528 func (b *Buffer) GetName() string {
536 if b.Settings["basename"].(bool) {
537 return path.Base(name)
542 //SetName changes the name for this buffer
543 func (b *Buffer) SetName(s string) {
547 // Insert inserts the given string of text at the start location
548 func (b *Buffer) Insert(start Loc, text string) {
549 if !b.Type.Readonly {
550 b.EventHandler.cursors = b.cursors
551 b.EventHandler.active = b.curCursor
552 b.EventHandler.Insert(start, text)
558 // Remove removes the characters between the start and end locations
559 func (b *Buffer) Remove(start, end Loc) {
560 if !b.Type.Readonly {
561 b.EventHandler.cursors = b.cursors
562 b.EventHandler.active = b.curCursor
563 b.EventHandler.Remove(start, end)
569 // FileType returns the buffer's filetype
570 func (b *Buffer) FileType() string {
571 return b.Settings["filetype"].(string)
574 // ExternallyModified returns whether the file being edited has
575 // been modified by some external process
576 func (b *Buffer) ExternallyModified() bool {
577 modTime, err := util.GetModTime(b.Path)
579 return modTime != b.ModTime
584 // UpdateModTime updates the modtime of this file
585 func (b *Buffer) UpdateModTime() (err error) {
586 b.ModTime, err = util.GetModTime(b.Path)
590 // ReOpen reloads the current buffer from disk
591 func (b *Buffer) ReOpen() error {
592 file, err := os.Open(b.Path)
597 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
602 autoretab := b.Settings["autoretab"].(bool)
603 toSpaces := b.Settings["tabstospaces"].(bool)
604 tabsize := util.IntOpt(b.Settings["tabsize"])
606 reader := newRetabReader(file, enc, autoretab, toSpaces, tabsize)
607 data, err := ioutil.ReadAll(reader)
613 b.EventHandler.ApplyDiff(txt)
615 err = b.UpdateModTime()
616 if !b.Settings["fastdirty"].(bool) {
617 calcHash(b, &b.origHash)
624 // RelocateCursors relocates all cursors (makes sure they are in the buffer)
625 func (b *Buffer) RelocateCursors() {
626 for _, c := range b.cursors {
631 // RuneAt returns the rune at a given location in the buffer
632 func (b *Buffer) RuneAt(loc Loc) rune {
633 line := b.LineBytes(loc.Y)
637 r, _, size := util.DecodeCharacter(line)
650 // WordAt returns the word around a given location in the buffer
651 func (b *Buffer) WordAt(loc Loc) []byte {
652 if len(b.LineBytes(loc.Y)) == 0 || !util.IsWordChar(b.RuneAt(loc)) {
657 end := loc.Move(1, b)
659 for start.X > 0 && util.IsWordChar(b.RuneAt(start.Move(-1, b))) {
663 lineLen := util.CharacterCount(b.LineBytes(loc.Y))
664 for end.X < lineLen && util.IsWordChar(b.RuneAt(end)) {
668 return b.Substr(start, end)
671 // Modified returns if this buffer has been modified since
673 func (b *Buffer) Modified() bool {
678 if b.Settings["fastdirty"].(bool) {
682 var buff [md5.Size]byte
685 return buff != b.origHash
688 // Size returns the number of bytes in the current buffer
689 func (b *Buffer) Size() int {
691 for i := 0; i < b.LinesNum(); i++ {
692 nb += len(b.LineBytes(i))
694 if i != b.LinesNum()-1 {
695 if b.Endings == FFDos {
696 nb++ // carriage return
704 // calcHash calculates md5 hash of all lines in the buffer
705 func calcHash(b *Buffer, out *[md5.Size]byte) error {
709 if len(b.lines) > 0 {
710 n, e := h.Write(b.lines[0].data)
716 for _, l := range b.lines[1:] {
717 n, e = h.Write([]byte{'\n'})
722 n, e = h.Write(l.data)
730 if size > LargeFileThreshold {
731 return ErrFileTooLarge
738 // UpdateRules updates the syntax rules and filetype for this buffer
739 // This is called when the colorscheme changes
740 func (b *Buffer) UpdateRules() {
744 ft := b.Settings["filetype"].(string)
750 var header *highlight.Header
751 // search for the syntax file in the user's custom syntax files
752 for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
753 data, err := f.Data()
755 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
759 header, err = highlight.MakeHeaderYaml(data)
761 screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
763 file, err := highlight.ParseFile(data)
765 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
769 if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
770 syndef, err := highlight.ParseDef(file, header)
772 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
776 syntaxFile = f.Name()
782 // search in the default syntax files
783 for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
784 data, err := f.Data()
786 screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
790 header, err = highlight.MakeHeader(data)
792 screen.TermMessage("Error reading syntax header file", f.Name(), err)
796 if ft == "unknown" || ft == "" {
797 if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
798 syntaxFile = f.Name()
801 } else if header.FileType == ft {
802 syntaxFile = f.Name()
807 if syntaxFile != "" && !foundDef {
808 // we found a syntax file using a syntax header file
809 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
810 if f.Name() == syntaxFile {
811 data, err := f.Data()
813 screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
817 file, err := highlight.ParseFile(data)
819 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
823 syndef, err := highlight.ParseDef(file, header)
825 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
834 if b.SyntaxDef != nil && highlight.HasIncludes(b.SyntaxDef) {
835 includes := highlight.GetIncludes(b.SyntaxDef)
837 var files []*highlight.File
838 for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
839 data, err := f.Data()
841 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
844 header, err := highlight.MakeHeaderYaml(data)
846 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
850 for _, i := range includes {
851 if header.FileType == i {
852 file, err := highlight.ParseFile(data)
854 screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
857 files = append(files, file)
861 if len(files) >= len(includes) {
866 highlight.ResolveIncludes(b.SyntaxDef, files)
869 if b.Highlighter == nil || syntaxFile != "" {
870 if b.SyntaxDef != nil {
871 b.Settings["filetype"] = b.SyntaxDef.FileType
874 b.SyntaxDef = &highlight.EmptyDef
877 if b.SyntaxDef != nil {
878 b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
879 if b.Settings["syntax"].(bool) {
881 b.Highlighter.HighlightStates(b)
882 b.Highlighter.HighlightMatches(b, 0, b.End().Y)
889 // ClearMatches clears all of the syntax highlighting for the buffer
890 func (b *Buffer) ClearMatches() {
891 for i := range b.lines {
897 // IndentString returns this buffer's indent method (a tabstop or n spaces
898 // depending on the settings)
899 func (b *Buffer) IndentString(tabsize int) string {
900 if b.Settings["tabstospaces"].(bool) {
901 return util.Spaces(tabsize)
906 // SetCursors resets this buffer's cursors to a new list
907 func (b *Buffer) SetCursors(c []*Cursor) {
909 b.EventHandler.cursors = b.cursors
910 b.EventHandler.active = b.curCursor
913 // AddCursor adds a new cursor to the list
914 func (b *Buffer) AddCursor(c *Cursor) {
915 b.cursors = append(b.cursors, c)
916 b.EventHandler.cursors = b.cursors
917 b.EventHandler.active = b.curCursor
921 // SetCurCursor sets the current cursor
922 func (b *Buffer) SetCurCursor(n int) {
926 // GetActiveCursor returns the main cursor in this buffer
927 func (b *Buffer) GetActiveCursor() *Cursor {
928 return b.cursors[b.curCursor]
931 // GetCursor returns the nth cursor
932 func (b *Buffer) GetCursor(n int) *Cursor {
936 // GetCursors returns the list of cursors in this buffer
937 func (b *Buffer) GetCursors() []*Cursor {
941 // NumCursors returns the number of cursors
942 func (b *Buffer) NumCursors() int {
943 return len(b.cursors)
946 // MergeCursors merges any cursors that are at the same position
948 func (b *Buffer) MergeCursors() {
949 var cursors []*Cursor
950 for i := 0; i < len(b.cursors); i++ {
953 for j := 0; j < len(b.cursors); j++ {
955 if c2 != nil && i != j && c1.Loc == c2.Loc {
959 cursors = append(cursors, c1)
965 for i := range b.cursors {
969 if b.curCursor >= len(b.cursors) {
970 b.curCursor = len(b.cursors) - 1
972 b.EventHandler.cursors = b.cursors
973 b.EventHandler.active = b.curCursor
976 // UpdateCursors updates all the cursors indicies
977 func (b *Buffer) UpdateCursors() {
978 b.EventHandler.cursors = b.cursors
979 b.EventHandler.active = b.curCursor
980 for i, c := range b.cursors {
985 func (b *Buffer) RemoveCursor(i int) {
986 copy(b.cursors[i:], b.cursors[i+1:])
987 b.cursors[len(b.cursors)-1] = nil
988 b.cursors = b.cursors[:len(b.cursors)-1]
989 b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
993 // ClearCursors removes all extra cursors
994 func (b *Buffer) ClearCursors() {
995 for i := 1; i < len(b.cursors); i++ {
998 b.cursors = b.cursors[:1]
1001 b.GetActiveCursor().ResetSelection()
1004 // MoveLinesUp moves the range of lines up one row
1005 func (b *Buffer) MoveLinesUp(start int, end int) {
1006 if start < 1 || start >= end || end > len(b.lines) {
1009 l := string(b.LineBytes(start - 1))
1010 if end == len(b.lines) {
1013 util.CharacterCount(b.lines[end-1].data),
1029 // MoveLinesDown moves the range of lines down one row
1030 func (b *Buffer) MoveLinesDown(start int, end int) {
1031 if start < 0 || start >= end || end >= len(b.lines) {
1034 l := string(b.LineBytes(end))
1046 var BracePairs = [][2]rune{
1052 // FindMatchingBrace returns the location in the buffer of the matching bracket
1053 // It is given a brace type containing the open and closing character, (for example
1054 // '{' and '}') as well as the location to match from
1055 // TODO: maybe can be more efficient with utf8 package
1056 // returns the location of the matching brace
1057 // if the boolean returned is true then the original matching brace is one character left
1058 // of the starting location
1059 func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, bool) {
1060 curLine := []rune(string(b.LineBytes(start.Y)))
1062 if start.X >= 0 && start.X < len(curLine) {
1063 startChar = curLine[start.X]
1066 if start.X-1 >= 0 && start.X-1 < len(curLine) {
1067 leftChar = curLine[start.X-1]
1070 if startChar == braceType[0] || leftChar == braceType[0] {
1071 for y := start.Y; y < b.LinesNum(); y++ {
1072 l := []rune(string(b.LineBytes(y)))
1075 if startChar == braceType[0] {
1081 for x := xInit; x < len(l); x++ {
1083 if r == braceType[0] {
1085 } else if r == braceType[1] {
1088 if startChar == braceType[0] {
1089 return Loc{x, y}, false, true
1091 return Loc{x, y}, true, true
1096 } else if startChar == braceType[1] || leftChar == braceType[1] {
1097 for y := start.Y; y >= 0; y-- {
1098 l := []rune(string(b.lines[y].data))
1101 if leftChar == braceType[1] {
1107 for x := xInit; x >= 0; x-- {
1109 if r == braceType[0] {
1112 if leftChar == braceType[1] {
1113 return Loc{x, y}, true, true
1115 return Loc{x, y}, false, true
1117 } else if r == braceType[1] {
1123 return start, true, false
1126 // Retab changes all tabs to spaces or vice versa
1127 func (b *Buffer) Retab() {
1128 toSpaces := b.Settings["tabstospaces"].(bool)
1129 tabsize := util.IntOpt(b.Settings["tabsize"])
1132 for i := 0; i < b.LinesNum(); i++ {
1133 b.lines[i].data = retabLine(b.LineBytes(i), toSpaces, tabsize)
1134 b.MarkModified(i, i)
1138 b.isModified = dirty
1141 // ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
1143 func ParseCursorLocation(cursorPositions []string) (Loc, error) {
1144 startpos := Loc{0, 0}
1147 // if no positions are available exit early
1148 if cursorPositions == nil {
1149 return startpos, errors.New("No cursor positions were provided.")
1152 startpos.Y, err = strconv.Atoi(cursorPositions[0])
1155 if len(cursorPositions) > 1 {
1156 startpos.X, err = strconv.Atoi(cursorPositions[1])
1163 return startpos, err
1166 // Line returns the string representation of the given line number
1167 func (b *Buffer) Line(i int) string {
1168 return string(b.LineBytes(i))
1171 func (b *Buffer) Write(bytes []byte) (n int, err error) {
1172 b.EventHandler.InsertBytes(b.End(), bytes)
1173 return len(bytes), nil
1176 func (b *Buffer) updateDiffSync() {
1178 defer b.diffLock.Unlock()
1180 b.diff = make(map[int]DiffStatus)
1182 if b.diffBase == nil {
1187 baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
1188 diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
1191 for _, diff := range diffs {
1192 lineCount := len([]rune(diff.Text))
1197 case dmp.DiffInsert:
1198 var status DiffStatus
1199 if b.diff[lineN] == DSDeletedAbove {
1204 for i := 0; i < lineCount; i++ {
1205 b.diff[lineN] = status
1208 case dmp.DiffDelete:
1209 b.diff[lineN] = DSDeletedAbove
1214 // UpdateDiff computes the diff between the diff base and the buffer content.
1215 // The update may be performed synchronously or asynchronously.
1216 // UpdateDiff calls the supplied callback when the update is complete.
1217 // The argument passed to the callback is set to true if and only if
1218 // the update was performed synchronously.
1219 // If an asynchronous update is already pending when UpdateDiff is called,
1220 // UpdateDiff does not schedule another update, in which case the callback
1222 func (b *Buffer) UpdateDiff(callback func(bool)) {
1223 if b.updateDiffTimer != nil {
1227 lineCount := b.LinesNum()
1228 if b.diffBaseLineCount > lineCount {
1229 lineCount = b.diffBaseLineCount
1232 if lineCount < 1000 {
1235 } else if lineCount < 30000 {
1236 b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
1237 b.updateDiffTimer = nil
1242 // Don't compute diffs for very large files
1244 b.diff = make(map[int]DiffStatus)
1250 // SetDiffBase sets the text that is used as the base for diffing the buffer content
1251 func (b *Buffer) SetDiffBase(diffBase []byte) {
1252 b.diffBase = diffBase
1253 if diffBase == nil {
1254 b.diffBaseLineCount = 0
1256 b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
1258 b.UpdateDiff(func(synchronous bool) {
1263 // DiffStatus returns the diff status for a line in the buffer
1264 func (b *Buffer) DiffStatus(lineN int) DiffStatus {
1266 defer b.diffLock.RUnlock()
1267 // Note that the zero value for DiffStatus is equal to DSUnchanged
1268 return b.diff[lineN]
1271 // SearchMatch returns true if the given location is within a match of the last search.
1272 // It is used for search highlighting
1273 func (b *Buffer) SearchMatch(pos Loc) bool {
1274 return b.LineArray.SearchMatch(b, pos)
1277 // WriteLog writes a string to the log buffer
1278 func WriteLog(s string) {
1279 LogBuf.EventHandler.Insert(LogBuf.End(), s)
1282 // GetLogBuf returns the log buffer
1283 func GetLogBuf() *Buffer {