16 "github.com/zyedidia/micro/internal/config"
17 "github.com/zyedidia/micro/internal/screen"
18 "github.com/zyedidia/micro/internal/util"
19 "golang.org/x/text/encoding"
20 "golang.org/x/text/encoding/htmlindex"
21 "golang.org/x/text/transform"
24 // LargeFileThreshold is the number of bytes when fastdirty is forced
25 // because hashing is too slow
26 const LargeFileThreshold = 50000
28 // overwriteFile opens the given file for writing, truncating if one exists, and then calls
29 // the supplied function with the file as io.Writer object, also making sure the file is
31 func overwriteFile(name string, enc encoding.Encoding, fn func(io.Writer) error, withSudo bool) (err error) {
32 var writeCloser io.WriteCloser
35 cmd := exec.Command(config.GlobalSettings["sucmd"].(string), "dd", "bs=4k", "of="+name)
37 if writeCloser, err = cmd.StdinPipe(); err != nil {
41 c := make(chan os.Signal, 1)
42 signal.Notify(c, os.Interrupt)
49 screenb := screen.TempFini()
50 if e := cmd.Run(); e != nil && err == nil {
53 screen.TempStart(screenb)
55 } else if writeCloser, err = os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
59 w := bufio.NewWriter(transform.NewWriter(writeCloser, enc.NewEncoder()))
63 if e := writeCloser.Close(); e != nil && err == nil {
70 // Save saves the buffer to its default path
71 func (b *Buffer) Save() error {
72 return b.SaveAs(b.Path)
75 // SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
76 func (b *Buffer) SaveAs(filename string) error {
77 return b.saveToFile(filename, false)
80 func (b *Buffer) SaveWithSudo() error {
81 return b.SaveAsWithSudo(b.Path)
84 func (b *Buffer) SaveAsWithSudo(filename string) error {
85 return b.saveToFile(filename, true)
88 func (b *Buffer) saveToFile(filename string, withSudo bool) error {
91 return errors.New("Cannot save readonly buffer")
94 return errors.New("Cannot save scratch buffer")
96 if withSudo && runtime.GOOS == "windows" {
97 return errors.New("Save with sudo not supported on Windows")
101 if b.Settings["rmtrailingws"].(bool) {
102 for i, l := range b.lines {
103 leftover := utf8.RuneCount(bytes.TrimRightFunc(l.data, unicode.IsSpace))
105 linelen := utf8.RuneCount(l.data)
106 b.Remove(Loc{leftover, i}, Loc{linelen, i})
112 if b.Settings["eofnewline"].(bool) {
114 if b.RuneAt(Loc{end.X, end.Y}) != '\n' {
115 b.insert(end, []byte{'\n'})
119 // Update the last time this file was updated after saving
121 b.ModTime, _ = util.GetModTime(filename)
125 // Removes any tilde and replaces with the absolute path to home
126 absFilename, _ := util.ReplaceHome(filename)
128 // Get the leading path to the file | "." is returned if there's no leading path provided
129 if dirname := filepath.Dir(absFilename); dirname != "." {
130 // Check if the parent dirs don't exist
131 if _, statErr := os.Stat(dirname); os.IsNotExist(statErr) {
132 // Prompt to make sure they want to create the dirs that are missing
133 if b.Settings["mkparents"].(bool) {
134 // Create all leading dir(s) since they don't exist
135 if mkdirallErr := os.MkdirAll(dirname, os.ModePerm); mkdirallErr != nil {
136 // If there was an error creating the dirs
140 return errors.New("Parent dirs don't exist, enable 'mkparents' for auto creation")
147 enc, err := htmlindex.Get(b.Settings["encoding"].(string))
152 fwriter := func(file io.Writer) (e error) {
153 if len(b.lines) == 0 {
159 if b.Endings == FFDos {
160 eol = []byte{'\r', '\n'}
166 if fileSize, e = file.Write(b.lines[0].data); e != nil {
170 for _, l := range b.lines[1:] {
171 if _, e = file.Write(eol); e != nil {
174 if _, e = file.Write(l.data); e != nil {
177 fileSize += len(eol) + len(l.data)
182 if err = overwriteFile(absFilename, enc, fwriter, withSudo); err != nil {
186 if !b.Settings["fastdirty"].(bool) {
187 if fileSize > LargeFileThreshold {
188 // For large files 'fastdirty' needs to be on
189 b.Settings["fastdirty"] = true
191 calcHash(b, &b.origHash)
196 absPath, _ := filepath.Abs(filename)