16 // Buffer stores the text for files that are loaded into the text editor
17 // It uses a rope to efficiently store the string and contains some
18 // simple functions for saving and wrapper functions for modifying the rope
20 // The eventhandler for undo/redo
22 // This stores all the text in the buffer as an array of lines
27 // Path to the file on disk
29 // Name of the buffer on the status line
32 // Whether or not the buffer has been modified since it was opened
35 // Stores the last modification time of the file the buffer is pointing to
40 // Syntax highlighting rules
43 // Buffer local settings
44 Settings map[string]interface{}
47 // The SerializedBuffer holds the types that get serialized when a buffer is saved
48 // These are used for the savecursor and saveundo options
49 type SerializedBuffer struct {
50 EventHandler *EventHandler
55 // NewBuffer creates a new buffer from `txt` with path and name `path`
56 func NewBuffer(txt []byte, path string) *Buffer {
58 b.LineArray = NewLineArray(txt)
60 b.Settings = DefaultLocalSettings()
61 for k, v := range globalSettings {
62 if _, ok := b.Settings[k]; ok {
70 // If the file doesn't have a path to disk then we give it no name
75 // The last time this file was modified
76 b.ModTime, _ = GetModTime(b.Path)
78 b.EventHandler = NewEventHandler(b)
84 if _, err := os.Stat(configDir + "/buffers/"); os.IsNotExist(err) {
85 os.Mkdir(configDir+"/buffers/", os.ModePerm)
88 // Put the cursor at the first spot
97 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
98 // If either savecursor or saveundo is turned on, we need to load the serialized information
99 // from ~/.config/micro/buffers
100 absPath, _ := filepath.Abs(b.Path)
101 file, err := os.Open(configDir + "/buffers/" + EscapePath(absPath))
103 var buffer SerializedBuffer
104 decoder := gob.NewDecoder(file)
105 gob.Register(TextEvent{})
106 err = decoder.Decode(&buffer)
108 TermMessage(err.Error(), "\n", "You may want to remove the files in ~/.config/micro/buffers (these files store the information for the 'saveundo' and 'savecursor' options) if this problem persists.")
110 if b.Settings["savecursor"].(bool) {
111 b.Cursor = buffer.Cursor
116 if b.Settings["saveundo"].(bool) {
117 // We should only use last time's eventhandler if the file wasn't by someone else in the meantime
118 if b.ModTime == buffer.ModTime {
119 b.EventHandler = buffer.EventHandler
120 b.EventHandler.buf = b
127 _, err := Call("onBufferOpen", b)
128 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
135 // UpdateRules updates the syntax rules and filetype for this buffer
136 // This is called when the colorscheme changes
137 func (b *Buffer) UpdateRules() {
138 b.rules = GetRules(b)
141 // FindFileType identifies this buffer's filetype based on the extension or header
142 func (b *Buffer) FindFileType() {
143 b.Settings["filetype"] = FindFileType(b)
146 // FileType returns the buffer's filetype
147 func (b *Buffer) FileType() string {
148 return b.Settings["filetype"].(string)
151 // CheckModTime makes sure that the file this buffer points to hasn't been updated
152 // by an external program since it was last read
153 // If it has, we ask the user if they would like to reload the file
154 func (b *Buffer) CheckModTime() {
155 modTime, ok := GetModTime(b.Path)
157 if modTime != b.ModTime {
158 choice, canceled := messenger.YesNoPrompt("The file has changed since it was last read. Reload file? (y,n)")
161 if !choice || canceled {
162 // Don't load new changes -- do nothing
163 b.ModTime, _ = GetModTime(b.Path)
172 // ReOpen reloads the current buffer from disk
173 func (b *Buffer) ReOpen() {
174 data, err := ioutil.ReadFile(b.Path)
178 messenger.Error(err.Error())
181 b.EventHandler.ApplyDiff(txt)
183 b.ModTime, _ = GetModTime(b.Path)
189 // Update fetches the string from the rope and updates the `text` and `lines` in the buffer
190 func (b *Buffer) Update() {
191 b.NumLines = len(b.lines)
194 // Save saves the buffer to its default path
195 func (b *Buffer) Save() error {
196 return b.SaveAs(b.Path)
199 // SaveWithSudo saves the buffer to the default path with sudo
200 func (b *Buffer) SaveWithSudo() error {
201 return b.SaveAsWithSudo(b.Path)
204 // Serialize serializes the buffer to configDir/buffers
205 func (b *Buffer) Serialize() error {
206 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
207 absPath, _ := filepath.Abs(b.Path)
208 file, err := os.Create(configDir + "/buffers/" + EscapePath(absPath))
210 enc := gob.NewEncoder(file)
211 gob.Register(TextEvent{})
212 err = enc.Encode(SerializedBuffer{
224 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
225 func (b *Buffer) SaveAs(filename string) error {
229 data := []byte(b.String())
230 err := ioutil.WriteFile(filename, data, 0644)
233 b.ModTime, _ = GetModTime(filename)
239 // SaveAsWithSudo is the same as SaveAs except it uses a neat trick
240 // with tee to use sudo so the user doesn't have to reopen micro with sudo
241 func (b *Buffer) SaveAsWithSudo(filename string) error {
246 // The user may have already used sudo in which case we won't need the password
247 // It's a bit nicer for them if they don't have to enter the password every time
248 _, err := RunShellCommand("sudo -v")
249 needPassword := err != nil
251 // If we need the password, we have to close the screen and ask using the shell
253 // Shut down the screen because we're going to interact directly with the shell
258 // Set up everything for the command
259 cmd := exec.Command("sudo", "tee", filename)
260 cmd.Stdin = bytes.NewBufferString(b.String())
262 // This is a trap for Ctrl-C so that it doesn't kill micro
263 // Instead we trap Ctrl-C to kill the program we're running
264 c := make(chan os.Signal, 1)
265 signal.Notify(c, os.Interrupt)
276 // If we needed the password, we closed the screen, so we have to initialize it again
278 // Start the screen back up
283 b.ModTime, _ = GetModTime(filename)
289 func (b *Buffer) insert(pos Loc, value []byte) {
291 b.LineArray.insert(pos, value)
294 func (b *Buffer) remove(start, end Loc) string {
296 sub := b.LineArray.remove(start, end)
301 // Start returns the location of the first character in the buffer
302 func (b *Buffer) Start() Loc {
306 // End returns the location of the last character in the buffer
307 func (b *Buffer) End() Loc {
308 return Loc{utf8.RuneCount(b.lines[b.NumLines-1]), b.NumLines - 1}
311 // Line returns a single line
312 func (b *Buffer) Line(n int) string {
313 return string(b.lines[n])
316 // Lines returns an array of strings containing the lines from start to end
317 func (b *Buffer) Lines(start, end int) []string {
318 lines := b.lines[start:end]
320 for _, line := range lines {
321 slice = append(slice, string(line))
326 // Len gives the length of the buffer
327 func (b *Buffer) Len() int {
328 return Count(b.String())