]> git.lizzy.rs Git - micro.git/blob - cmd/micro/buffer/serialize.go
Add some comments
[micro.git] / cmd / micro / buffer / serialize.go
1 package buffer
2
3 import (
4         "encoding/gob"
5         "errors"
6         "io"
7         "os"
8         "time"
9
10         "github.com/zyedidia/micro/cmd/micro/config"
11         . "github.com/zyedidia/micro/cmd/micro/util"
12 )
13
14 // The SerializedBuffer holds the types that get serialized when a buffer is saved
15 // These are used for the savecursor and saveundo options
16 type SerializedBuffer struct {
17         EventHandler *EventHandler
18         Cursor       Loc
19         ModTime      time.Time
20 }
21
22 func init() {
23         gob.Register(TextEvent{})
24         gob.Register(SerializedBuffer{})
25 }
26
27 // Serialize serializes the buffer to config.ConfigDir/buffers
28 func (b *Buffer) Serialize() error {
29         if !b.Settings["savecursor"].(bool) && !b.Settings["saveundo"].(bool) {
30                 return nil
31         }
32
33         name := config.ConfigDir + "/buffers/" + EscapePath(b.AbsPath)
34
35         return overwriteFile(name, func(file io.Writer) error {
36                 err := gob.NewEncoder(file).Encode(SerializedBuffer{
37                         b.EventHandler,
38                         b.GetActiveCursor().Loc,
39                         b.ModTime,
40                 })
41                 return err
42         })
43 }
44
45 func (b *Buffer) Unserialize() error {
46         // If either savecursor or saveundo is turned on, we need to load the serialized information
47         // from ~/.config/micro/buffers
48         file, err := os.Open(config.ConfigDir + "/buffers/" + EscapePath(b.AbsPath))
49         defer file.Close()
50         if err == nil {
51                 var buffer SerializedBuffer
52                 decoder := gob.NewDecoder(file)
53                 gob.Register(TextEvent{})
54                 err = decoder.Decode(&buffer)
55                 if err != nil {
56                         return errors.New(err.Error() + "\nYou 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.")
57                 }
58                 if b.Settings["savecursor"].(bool) {
59                         b.StartCursor = buffer.Cursor
60                 }
61
62                 if b.Settings["saveundo"].(bool) {
63                         // We should only use last time's eventhandler if the file wasn't modified by someone else in the meantime
64                         if b.ModTime == buffer.ModTime {
65                                 b.EventHandler = buffer.EventHandler
66                                 b.EventHandler.buf = b
67                         }
68                 }
69         }
70         return nil
71 }