4 "github.com/vinzmay/go-rope"
9 // Buffer stores the text for files that are loaded into the text editor
10 // It uses a rope to efficiently store the string and contains some
11 // simple functions for saving and wrapper functions for modifying the rope
13 // The eventhandler for undo/redo
16 // Stores the text of the buffer
21 // Path to the file on disk
23 // Name of the buffer on the status line
28 // Provide efficient and easy access to text and lines so the rope String does not
29 // need to be constantly recalculated
30 // These variables are updated in the update() function
34 // Syntax highlighting rules
36 // The buffer's filetype
40 // NewBuffer creates a new buffer from `txt` with path and name `path`
41 func NewBuffer(txt, path string) *Buffer {
51 // Put the cursor at the first spot
58 b.EventHandler = NewEventHandler(b)
66 // UpdateRules updates the syntax rules and filetype for this buffer
67 // This is called when the colorscheme changes
68 func (b *Buffer) UpdateRules() {
69 b.rules, b.FileType = GetRules(b)
72 func (b *Buffer) String() string {
79 // Update fetches the string from the rope and updates the `text` and `lines` in the buffer
80 func (b *Buffer) Update() {
81 b.Lines = strings.Split(b.String(), "\n")
82 b.NumLines = len(b.Lines)
85 // Save saves the buffer to its default path
86 func (b *Buffer) Save() error {
87 return b.SaveAs(b.Path)
90 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
91 func (b *Buffer) SaveAs(filename string) error {
93 data := []byte(b.String())
94 err := ioutil.WriteFile(filename, data, 0644)
101 // This directly inserts value at idx, bypassing all undo/redo
102 func (b *Buffer) insert(idx int, value string) {
104 b.r = b.r.Insert(idx, value)
108 // Remove a slice of the rope from start to end (exclusive)
109 // Returns the string that was removed
110 // This directly removes from start to end from the buffer, bypassing all undo/redo
111 func (b *Buffer) remove(start, end int) string {
122 removed := b.Substr(start, end)
123 // The rope implenentation I am using wants indicies starting at 1 instead of 0
126 b.r = b.r.Delete(start, end-start)
131 // Substr returns the substring of the rope from start to end
132 func (b *Buffer) Substr(start, end int) string {
133 return b.r.Substr(start+1, end-start).String()
136 // Len gives the length of the buffer
137 func (b *Buffer) Len() int {