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 // Stores the text of the buffer
16 // Path to the file on disk
18 // Name of the buffer on the status line
21 // This is the text stored every time the buffer is saved to check if the buffer is modified
24 dirtySinceLastCheck bool
26 // Provide efficient and easy access to text and lines so the rope String does not
27 // need to be constantly recalculated
28 // These variables are updated in the update() function
32 // Syntax highlighting rules
34 // The buffer's filetype
38 // NewBuffer creates a new buffer from `txt` with path and name `path`
39 func NewBuffer(txt, path string) *Buffer {
56 // UpdateRules updates the syntax rules and filetype for this buffer
57 // This is called when the colorscheme changes
58 func (b *Buffer) UpdateRules() {
59 b.rules, b.filetype = GetRules(b)
62 // Update fetches the string from the rope and updates the `text` and `lines` in the buffer
63 func (b *Buffer) Update() {
69 b.lines = strings.Split(b.text, "\n")
72 // Save saves the buffer to its default path
73 func (b *Buffer) Save() error {
74 return b.SaveAs(b.path)
77 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
78 func (b *Buffer) SaveAs(filename string) error {
80 err := ioutil.WriteFile(filename, []byte(b.text), 0644)
88 // IsDirty returns whether or not the buffer has been modified compared to the one on disk
89 func (b *Buffer) IsDirty() bool {
90 if !b.dirtySinceLastCheck {
93 if b.netInsertions == 0 {
94 isDirty := b.savedText != b.text
95 b.dirtySinceLastCheck = isDirty
101 // Insert a string into the rope
102 func (b *Buffer) Insert(idx int, value string) {
103 b.dirtySinceLastCheck = true
104 b.netInsertions += len(value)
105 b.r = b.r.Insert(idx, value)
109 // Remove a slice of the rope from start to end (exclusive)
110 // Returns the string that was removed
111 func (b *Buffer) Remove(start, end int) string {
112 b.dirtySinceLastCheck = true
113 b.netInsertions -= end - start
120 removed := b.text[start:end]
121 // The rope implenentation I am using wants indicies starting at 1 instead of 0
124 b.r = b.r.Delete(start, end-start)
129 // Len gives the length of the buffer
130 func (b *Buffer) Len() int {