17 "github.com/mitchellh/go-homedir"
20 // Buffer stores the text for files that are loaded into the text editor
21 // It uses a rope to efficiently store the string and contains some
22 // simple functions for saving and wrapper functions for modifying the rope
24 // The eventhandler for undo/redo
26 // This stores all the text in the buffer as an array of lines
31 // Path to the file on disk
33 // Absolute path to the file on disk
35 // Name of the buffer on the status line
38 // Whether or not the buffer has been modified since it was opened
41 // Stores the last modification time of the file the buffer is pointing to
46 // Syntax highlighting rules
49 // Buffer local settings
50 Settings map[string]interface{}
53 // The SerializedBuffer holds the types that get serialized when a buffer is saved
54 // These are used for the savecursor and saveundo options
55 type SerializedBuffer struct {
56 EventHandler *EventHandler
61 func NewBufferFromString(text, path string) *Buffer {
62 return NewBuffer(strings.NewReader(text), path)
65 // NewBuffer creates a new buffer from a given reader with a given path
66 func NewBuffer(reader io.Reader, path string) *Buffer {
68 for _, tab := range tabs {
69 for _, view := range tab.views {
70 if view.Buf.Path == path {
78 b.LineArray = NewLineArray(reader)
80 b.Settings = DefaultLocalSettings()
81 for k, v := range globalSettings {
82 if _, ok := b.Settings[k]; ok {
87 absPath, _ := filepath.Abs(path)
92 // The last time this file was modified
93 b.ModTime, _ = GetModTime(b.Path)
95 b.EventHandler = NewEventHandler(b)
101 if _, err := os.Stat(configDir + "/buffers/"); os.IsNotExist(err) {
102 os.Mkdir(configDir+"/buffers/", os.ModePerm)
105 // Put the cursor at the first spot
108 // If -startpos LINE,COL was passed, use start position LINE,COL
109 if len(*flagStartPos) > 0 {
110 positions := strings.Split(*flagStartPos, ",")
111 if len(positions) == 2 {
112 lineNum, errPos1 := strconv.Atoi(positions[0])
113 colNum, errPos2 := strconv.Atoi(positions[1])
114 if errPos1 == nil && errPos2 == nil {
115 cursorStartX = colNum
116 cursorStartY = lineNum - 1
117 // Check to avoid line overflow
118 if cursorStartY > b.NumLines {
119 cursorStartY = b.NumLines - 1
120 } else if cursorStartY < 0 {
123 // Check to avoid column overflow
124 if cursorStartX > len(b.Line(cursorStartY)) {
125 cursorStartX = len(b.Line(cursorStartY))
126 } else if cursorStartX < 0 {
142 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
143 // If either savecursor or saveundo is turned on, we need to load the serialized information
144 // from ~/.config/micro/buffers
145 file, err := os.Open(configDir + "/buffers/" + EscapePath(b.AbsPath))
147 var buffer SerializedBuffer
148 decoder := gob.NewDecoder(file)
149 gob.Register(TextEvent{})
150 err = decoder.Decode(&buffer)
152 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.")
154 if b.Settings["savecursor"].(bool) {
155 b.Cursor = buffer.Cursor
160 if b.Settings["saveundo"].(bool) {
161 // We should only use last time's eventhandler if the file wasn't by someone else in the meantime
162 if b.ModTime == buffer.ModTime {
163 b.EventHandler = buffer.EventHandler
164 b.EventHandler.buf = b
174 func (b *Buffer) GetName() string {
184 // UpdateRules updates the syntax rules and filetype for this buffer
185 // This is called when the colorscheme changes
186 func (b *Buffer) UpdateRules() {
187 b.rules = GetRules(b)
190 // FindFileType identifies this buffer's filetype based on the extension or header
191 func (b *Buffer) FindFileType() {
192 b.Settings["filetype"] = FindFileType(b)
195 // FileType returns the buffer's filetype
196 func (b *Buffer) FileType() string {
197 return b.Settings["filetype"].(string)
200 // IndentString returns a string representing one level of indentation
201 func (b *Buffer) IndentString() string {
202 if b.Settings["tabstospaces"].(bool) {
203 return Spaces(int(b.Settings["tabsize"].(float64)))
208 // CheckModTime makes sure that the file this buffer points to hasn't been updated
209 // by an external program since it was last read
210 // If it has, we ask the user if they would like to reload the file
211 func (b *Buffer) CheckModTime() {
212 modTime, ok := GetModTime(b.Path)
214 if modTime != b.ModTime {
215 choice, canceled := messenger.YesNoPrompt("The file has changed since it was last read. Reload file? (y,n)")
218 if !choice || canceled {
219 // Don't load new changes -- do nothing
220 b.ModTime, _ = GetModTime(b.Path)
229 // ReOpen reloads the current buffer from disk
230 func (b *Buffer) ReOpen() {
231 data, err := ioutil.ReadFile(b.Path)
235 messenger.Error(err.Error())
238 b.EventHandler.ApplyDiff(txt)
240 b.ModTime, _ = GetModTime(b.Path)
246 // Update fetches the string from the rope and updates the `text` and `lines` in the buffer
247 func (b *Buffer) Update() {
248 b.NumLines = len(b.lines)
251 // Save saves the buffer to its default path
252 func (b *Buffer) Save() error {
253 return b.SaveAs(b.Path)
256 // SaveWithSudo saves the buffer to the default path with sudo
257 func (b *Buffer) SaveWithSudo() error {
258 return b.SaveAsWithSudo(b.Path)
261 // Serialize serializes the buffer to configDir/buffers
262 func (b *Buffer) Serialize() error {
263 if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
264 file, err := os.Create(configDir + "/buffers/" + EscapePath(b.AbsPath))
266 enc := gob.NewEncoder(file)
267 gob.Register(TextEvent{})
268 err = enc.Encode(SerializedBuffer{
280 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
281 func (b *Buffer) SaveAs(filename string) error {
284 dir, _ := homedir.Dir()
285 b.Path = strings.Replace(filename, "~", dir, 1)
287 if b.Settings["eofnewline"].(bool) {
289 if b.RuneAt(Loc{end.X - 1, end.Y}) != '\n' {
294 err := ioutil.WriteFile(filename, data, 0644)
297 b.ModTime, _ = GetModTime(filename)
300 b.ModTime, _ = GetModTime(filename)
304 // SaveAsWithSudo is the same as SaveAs except it uses a neat trick
305 // with tee to use sudo so the user doesn't have to reopen micro with sudo
306 func (b *Buffer) SaveAsWithSudo(filename string) error {
311 // The user may have already used sudo in which case we won't need the password
312 // It's a bit nicer for them if they don't have to enter the password every time
313 _, err := RunShellCommand("sudo -v")
314 needPassword := err != nil
316 // If we need the password, we have to close the screen and ask using the shell
318 // Shut down the screen because we're going to interact directly with the shell
323 // Set up everything for the command
324 cmd := exec.Command("sudo", "tee", filename)
325 cmd.Stdin = bytes.NewBufferString(b.String())
327 // This is a trap for Ctrl-C so that it doesn't kill micro
328 // Instead we trap Ctrl-C to kill the program we're running
329 c := make(chan os.Signal, 1)
330 signal.Notify(c, os.Interrupt)
341 // If we needed the password, we closed the screen, so we have to initialize it again
343 // Start the screen back up
348 b.ModTime, _ = GetModTime(filename)
354 func (b *Buffer) insert(pos Loc, value []byte) {
356 b.LineArray.insert(pos, value)
359 func (b *Buffer) remove(start, end Loc) string {
361 sub := b.LineArray.remove(start, end)
366 // Start returns the location of the first character in the buffer
367 func (b *Buffer) Start() Loc {
371 // End returns the location of the last character in the buffer
372 func (b *Buffer) End() Loc {
373 return Loc{utf8.RuneCount(b.lines[b.NumLines-1]), b.NumLines - 1}
376 // RuneAt returns the rune at a given location in the buffer
377 func (b *Buffer) RuneAt(loc Loc) rune {
378 line := []rune(b.Line(loc.Y))
385 // Line returns a single line
386 func (b *Buffer) Line(n int) string {
387 if n >= len(b.lines) {
390 return string(b.lines[n])
393 // Lines returns an array of strings containing the lines from start to end
394 func (b *Buffer) Lines(start, end int) []string {
395 lines := b.lines[start:end]
397 for _, line := range lines {
398 slice = append(slice, string(line))
403 // Len gives the length of the buffer
404 func (b *Buffer) Len() int {
405 return Count(b.String())
408 // MoveLinesUp moves the range of lines up one row
409 func (b *Buffer) MoveLinesUp(start int, end int) {
410 // 0 < start < end <= len(b.lines)
411 if start < 1 || start >= end || end > len(b.lines) {
412 return // what to do? FIXME
414 if end == len(b.lines) {
417 utf8.RuneCount(b.lines[end-1]),
420 "\n"+b.Line(start-1),
425 b.Line(start-1)+"\n",
434 // MoveLinesDown moves the range of lines down one row
435 func (b *Buffer) MoveLinesDown(start int, end int) {
436 // 0 <= start < end < len(b.lines)
437 // if end == len(b.lines), we can't do anything here because the
438 // last line is unaccessible, FIXME
439 if start < 0 || start >= end || end >= len(b.lines)-1 {
440 return // what to do? FIXME