17 // Buffer stores the text for files that are loaded into the text editor
18 // It uses a rope to efficiently store the string and contains some
19 // simple functions for saving and wrapper functions for modifying the rope
21 // The eventhandler for undo/redo
23 // This stores all the text in the buffer as an array of lines
28 // Path to the file on disk
30 // Name of the buffer on the status line
33 // Whether or not the buffer has been modified since it was opened
36 // Stores the last modification time of the file the buffer is pointing to
41 // Syntax highlighting rules
44 // Buffer local settings
45 Settings map[string]interface{}
48 // The SerializedBuffer holds the types that get serialized when a buffer is saved
49 // These are used for the savecursor and saveundo options
50 type SerializedBuffer struct {
51 EventHandler *EventHandler
56 // NewBuffer creates a new buffer from `txt` with path and name `path`
57 func NewBuffer(txt []byte, path string) *Buffer {
59 b.LineArray = NewLineArray(txt)
61 b.Settings = DefaultLocalSettings()
62 for k, v := range globalSettings {
63 if _, ok := b.Settings[k]; ok {
71 // If the file doesn't have a path to disk then we give it no name
76 // The last time this file was modified
77 b.ModTime, _ = GetModTime(b.Path)
79 b.EventHandler = NewEventHandler(b)
85 if _, err := os.Stat(configDir + "/buffers/"); os.IsNotExist(err) {
86 os.Mkdir(configDir+"/buffers/", os.ModePerm)
89 // Put the cursor at the first spot
92 // If -cursor LINE,COL was passed, use start position LINE,COL
93 if len(*flagLineColumn) > 0 {
94 positions := strings.Split(*flagLineColumn, ",")
95 if len(positions) == 2 {
96 lineNum, errPos1 := strconv.Atoi(positions[0])
97 colNum, errPos2 := strconv.Atoi(positions[1])
98 if errPos1 == nil && errPos2 == nil {
100 cursorStartY = lineNum - 1
101 // Check to avoid line overflow
102 if cursorStartY > b.NumLines {
103 cursorStartY = b.NumLines - 1
104 } else if cursorStartY < 0 {
107 // Check to avoid column overflow
108 if cursorStartX > len(b.Line(cursorStartY)) {
109 cursorStartX = len(b.Line(cursorStartY))
110 } else if cursorStartX < 0 {
126 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
127 // If either savecursor or saveundo is turned on, we need to load the serialized information
128 // from ~/.config/micro/buffers
129 absPath, _ := filepath.Abs(b.Path)
130 file, err := os.Open(configDir + "/buffers/" + EscapePath(absPath))
132 var buffer SerializedBuffer
133 decoder := gob.NewDecoder(file)
134 gob.Register(TextEvent{})
135 err = decoder.Decode(&buffer)
137 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.")
139 if b.Settings["savecursor"].(bool) {
140 b.Cursor = buffer.Cursor
145 if b.Settings["saveundo"].(bool) {
146 // We should only use last time's eventhandler if the file wasn't by someone else in the meantime
147 if b.ModTime == buffer.ModTime {
148 b.EventHandler = buffer.EventHandler
149 b.EventHandler.buf = b
159 // UpdateRules updates the syntax rules and filetype for this buffer
160 // This is called when the colorscheme changes
161 func (b *Buffer) UpdateRules() {
162 b.rules = GetRules(b)
165 // FindFileType identifies this buffer's filetype based on the extension or header
166 func (b *Buffer) FindFileType() {
167 b.Settings["filetype"] = FindFileType(b)
170 // FileType returns the buffer's filetype
171 func (b *Buffer) FileType() string {
172 return b.Settings["filetype"].(string)
175 // CheckModTime makes sure that the file this buffer points to hasn't been updated
176 // by an external program since it was last read
177 // If it has, we ask the user if they would like to reload the file
178 func (b *Buffer) CheckModTime() {
179 modTime, ok := GetModTime(b.Path)
181 if modTime != b.ModTime {
182 choice, canceled := messenger.YesNoPrompt("The file has changed since it was last read. Reload file? (y,n)")
185 if !choice || canceled {
186 // Don't load new changes -- do nothing
187 b.ModTime, _ = GetModTime(b.Path)
196 // ReOpen reloads the current buffer from disk
197 func (b *Buffer) ReOpen() {
198 data, err := ioutil.ReadFile(b.Path)
202 messenger.Error(err.Error())
205 b.EventHandler.ApplyDiff(txt)
207 b.ModTime, _ = GetModTime(b.Path)
213 // Update fetches the string from the rope and updates the `text` and `lines` in the buffer
214 func (b *Buffer) Update() {
215 b.NumLines = len(b.lines)
218 // Save saves the buffer to its default path
219 func (b *Buffer) Save() error {
220 return b.SaveAs(b.Path)
223 // SaveWithSudo saves the buffer to the default path with sudo
224 func (b *Buffer) SaveWithSudo() error {
225 return b.SaveAsWithSudo(b.Path)
228 // Serialize serializes the buffer to configDir/buffers
229 func (b *Buffer) Serialize() error {
230 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
231 absPath, _ := filepath.Abs(b.Path)
232 file, err := os.Create(configDir + "/buffers/" + EscapePath(absPath))
234 enc := gob.NewEncoder(file)
235 gob.Register(TextEvent{})
236 err = enc.Encode(SerializedBuffer{
248 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
249 func (b *Buffer) SaveAs(filename string) error {
253 data := []byte(b.String())
254 err := ioutil.WriteFile(filename, data, 0644)
257 b.ModTime, _ = GetModTime(filename)
263 // SaveAsWithSudo is the same as SaveAs except it uses a neat trick
264 // with tee to use sudo so the user doesn't have to reopen micro with sudo
265 func (b *Buffer) SaveAsWithSudo(filename string) error {
270 // The user may have already used sudo in which case we won't need the password
271 // It's a bit nicer for them if they don't have to enter the password every time
272 _, err := RunShellCommand("sudo -v")
273 needPassword := err != nil
275 // If we need the password, we have to close the screen and ask using the shell
277 // Shut down the screen because we're going to interact directly with the shell
282 // Set up everything for the command
283 cmd := exec.Command("sudo", "tee", filename)
284 cmd.Stdin = bytes.NewBufferString(b.String())
286 // This is a trap for Ctrl-C so that it doesn't kill micro
287 // Instead we trap Ctrl-C to kill the program we're running
288 c := make(chan os.Signal, 1)
289 signal.Notify(c, os.Interrupt)
300 // If we needed the password, we closed the screen, so we have to initialize it again
302 // Start the screen back up
307 b.ModTime, _ = GetModTime(filename)
313 func (b *Buffer) insert(pos Loc, value []byte) {
315 b.LineArray.insert(pos, value)
318 func (b *Buffer) remove(start, end Loc) string {
320 sub := b.LineArray.remove(start, end)
325 // Start returns the location of the first character in the buffer
326 func (b *Buffer) Start() Loc {
330 // End returns the location of the last character in the buffer
331 func (b *Buffer) End() Loc {
332 return Loc{utf8.RuneCount(b.lines[b.NumLines-1]), b.NumLines - 1}
335 // Line returns a single line
336 func (b *Buffer) Line(n int) string {
337 return string(b.lines[n])
340 // Lines returns an array of strings containing the lines from start to end
341 func (b *Buffer) Lines(start, end int) []string {
342 lines := b.lines[start:end]
344 for _, line := range lines {
345 slice = append(slice, string(line))
350 // Len gives the length of the buffer
351 func (b *Buffer) Len() int {
352 return Count(b.String())