]> git.lizzy.rs Git - micro.git/blob - src/buffer.go
Add messaging system
[micro.git] / src / buffer.go
1 package main
2
3 import (
4         "io/ioutil"
5         "strings"
6 )
7
8 // Buffer stores the text for files that are loaded into the text editor
9 // It uses a rope to efficiently store the string and contains some
10 // simple functions for saving and wrapper functions for modifying the rope
11 type Buffer struct {
12         // Stores the text of the buffer
13         r *Rope
14
15         // Path to the file on disk
16         path string
17         // Name of the buffer on the status line
18         name string
19
20         // This is the text stored every time the buffer is saved to check if the buffer is modified
21         savedText string
22
23         // Provide efficient and easy access to text and lines so the rope String does not
24         // need to be constantly recalculated
25         // These variables are updated in the update() function
26         text  string
27         lines []string
28
29         // Syntax highlighting rules
30         rules string
31         // File type of the buffer
32         filetype string
33 }
34
35 // NewBuffer creates a new buffer from `txt` with path and name `path`
36 func NewBuffer(txt, path string) *Buffer {
37         b := new(Buffer)
38         b.r = NewRope(txt)
39         b.path = path
40         b.name = path
41         b.savedText = txt
42
43         b.Update()
44
45         b.rules, b.filetype = GetRules(b)
46
47         return b
48 }
49
50 // Update fetches the string from the rope and updates the `text` and `lines` in the buffer
51 func (b *Buffer) Update() {
52         b.text = b.r.String()
53         b.lines = strings.Split(b.text, "\n")
54 }
55
56 // Save saves the buffer to its default path
57 func (b *Buffer) Save() error {
58         return b.SaveAs(b.path)
59 }
60
61 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
62 func (b *Buffer) SaveAs(filename string) error {
63         err := ioutil.WriteFile(filename, []byte(b.text), 0644)
64         if err == nil {
65                 b.savedText = b.text
66         }
67         return err
68 }
69
70 // Insert a string into the rope
71 func (b *Buffer) Insert(idx int, value string) {
72         b.r.Insert(idx, value)
73         b.Update()
74 }
75
76 // Remove a slice of the rope from start to end (exclusive)
77 // Returns the string that was removed
78 func (b *Buffer) Remove(start, end int) string {
79         removed := b.text[start:end]
80         b.r.Remove(start, end)
81         b.Update()
82         return removed
83 }
84
85 // Len gives the length of the buffer
86 func (b *Buffer) Len() int {
87         return b.r.len
88 }