]> git.lizzy.rs Git - micro.git/blob - internal/buffer/line_array.go
Support csharp-script syntax. (#1425)
[micro.git] / internal / buffer / line_array.go
1 package buffer
2
3 import (
4         "bufio"
5         "bytes"
6         "io"
7         "sync"
8         "unicode/utf8"
9
10         "github.com/zyedidia/micro/pkg/highlight"
11 )
12
13 // Finds the byte index of the nth rune in a byte slice
14 func runeToByteIndex(n int, txt []byte) int {
15         if n == 0 {
16                 return 0
17         }
18
19         count := 0
20         i := 0
21         for len(txt) > 0 {
22                 _, size := utf8.DecodeRune(txt)
23
24                 txt = txt[size:]
25                 count += size
26                 i++
27
28                 if i == n {
29                         break
30                 }
31         }
32         return count
33 }
34
35 // A Line contains the data in bytes as well as a highlight state, match
36 // and a flag for whether the highlighting needs to be updated
37 type Line struct {
38         data []byte
39
40         state       highlight.State
41         match       highlight.LineMatch
42         rehighlight bool
43         lock        sync.Mutex
44 }
45
46 const (
47         // Line ending file formats
48         FFAuto = 0 // Autodetect format
49         FFUnix = 1 // LF line endings (unix style '\n')
50         FFDos  = 2 // CRLF line endings (dos style '\r\n')
51 )
52
53 type FileFormat byte
54
55 // A LineArray simply stores and array of lines and makes it easy to insert
56 // and delete in it
57 type LineArray struct {
58         lines    []Line
59         Endings  FileFormat
60         initsize uint64
61 }
62
63 // Append efficiently appends lines together
64 // It allocates an additional 10000 lines if the original estimate
65 // is incorrect
66 func Append(slice []Line, data ...Line) []Line {
67         l := len(slice)
68         if l+len(data) > cap(slice) { // reallocate
69                 newSlice := make([]Line, (l+len(data))+10000)
70                 copy(newSlice, slice)
71                 slice = newSlice
72         }
73         slice = slice[0 : l+len(data)]
74         for i, c := range data {
75                 slice[l+i] = c
76         }
77         return slice
78 }
79
80 // NewLineArray returns a new line array from an array of bytes
81 func NewLineArray(size uint64, endings FileFormat, reader io.Reader) *LineArray {
82         la := new(LineArray)
83
84         la.lines = make([]Line, 0, 1000)
85         la.initsize = size
86
87         br := bufio.NewReader(reader)
88         var loaded int
89
90         n := 0
91         for {
92                 data, err := br.ReadBytes('\n')
93                 // Detect the line ending by checking to see if there is a '\r' char
94                 // before the '\n'
95                 // Even if the file format is set to DOS, the '\r' is removed so
96                 // that all lines end with '\n'
97                 dlen := len(data)
98                 if dlen > 1 && data[dlen-2] == '\r' {
99                         data = append(data[:dlen-2], '\n')
100                         if endings == FFAuto {
101                                 la.Endings = FFDos
102                         }
103                         dlen = len(data)
104                 } else if dlen > 0 {
105                         if endings == FFAuto {
106                                 la.Endings = FFUnix
107                         }
108                 }
109
110                 // If we are loading a large file (greater than 1000) we use the file
111                 // size and the length of the first 1000 lines to try to estimate
112                 // how many lines will need to be allocated for the rest of the file
113                 // We add an extra 10000 to the original estimate to be safe and give
114                 // plenty of room for expansion
115                 if n >= 1000 && loaded >= 0 {
116                         totalLinesNum := int(float64(size) * (float64(n) / float64(loaded)))
117                         newSlice := make([]Line, len(la.lines), totalLinesNum+10000)
118                         copy(newSlice, la.lines)
119                         la.lines = newSlice
120                         loaded = -1
121                 }
122
123                 // Counter for the number of bytes in the first 1000 lines
124                 if loaded >= 0 {
125                         loaded += dlen
126                 }
127
128                 if err != nil {
129                         if err == io.EOF {
130                                 la.lines = Append(la.lines, Line{
131                                         data:        data[:],
132                                         state:       nil,
133                                         match:       nil,
134                                         rehighlight: false,
135                                 })
136                         }
137                         // Last line was read
138                         break
139                 } else {
140                         la.lines = Append(la.lines, Line{
141                                 data:        data[:dlen-1],
142                                 state:       nil,
143                                 match:       nil,
144                                 rehighlight: false,
145                         })
146                 }
147                 n++
148         }
149
150         return la
151 }
152
153 // Bytes returns the string that should be written to disk when
154 // the line array is saved
155 func (la *LineArray) Bytes() []byte {
156         b := new(bytes.Buffer)
157         // initsize should provide a good estimate
158         b.Grow(int(la.initsize + 4096))
159         for i, l := range la.lines {
160                 b.Write(l.data)
161                 if i != len(la.lines)-1 {
162                         if la.Endings == FFDos {
163                                 b.WriteByte('\r')
164                         }
165                         b.WriteByte('\n')
166                 }
167         }
168         return b.Bytes()
169 }
170
171 // newlineBelow adds a newline below the given line number
172 func (la *LineArray) newlineBelow(y int) {
173         la.lines = append(la.lines, Line{
174                 data:        []byte{' '},
175                 state:       nil,
176                 match:       nil,
177                 rehighlight: false,
178         })
179         copy(la.lines[y+2:], la.lines[y+1:])
180         la.lines[y+1] = Line{
181                 data:        []byte{},
182                 state:       la.lines[y].state,
183                 match:       nil,
184                 rehighlight: false,
185         }
186 }
187
188 // Inserts a byte array at a given location
189 func (la *LineArray) insert(pos Loc, value []byte) {
190         x, y := runeToByteIndex(pos.X, la.lines[pos.Y].data), pos.Y
191         for i := 0; i < len(value); i++ {
192                 if value[i] == '\n' {
193                         la.split(Loc{x, y})
194                         x = 0
195                         y++
196                         continue
197                 }
198                 la.insertByte(Loc{x, y}, value[i])
199                 x++
200         }
201 }
202
203 // InsertByte inserts a byte at a given location
204 func (la *LineArray) insertByte(pos Loc, value byte) {
205         la.lines[pos.Y].data = append(la.lines[pos.Y].data, 0)
206         copy(la.lines[pos.Y].data[pos.X+1:], la.lines[pos.Y].data[pos.X:])
207         la.lines[pos.Y].data[pos.X] = value
208 }
209
210 // joinLines joins the two lines a and b
211 func (la *LineArray) joinLines(a, b int) {
212         la.insert(Loc{len(la.lines[a].data), a}, la.lines[b].data)
213         la.deleteLine(b)
214 }
215
216 // split splits a line at a given position
217 func (la *LineArray) split(pos Loc) {
218         la.newlineBelow(pos.Y)
219         la.insert(Loc{0, pos.Y + 1}, la.lines[pos.Y].data[pos.X:])
220         la.lines[pos.Y+1].state = la.lines[pos.Y].state
221         la.lines[pos.Y].state = nil
222         la.lines[pos.Y].match = nil
223         la.lines[pos.Y+1].match = nil
224         la.lines[pos.Y].rehighlight = true
225         la.deleteToEnd(Loc{pos.X, pos.Y})
226 }
227
228 // removes from start to end
229 func (la *LineArray) remove(start, end Loc) []byte {
230         sub := la.Substr(start, end)
231         startX := runeToByteIndex(start.X, la.lines[start.Y].data)
232         endX := runeToByteIndex(end.X, la.lines[end.Y].data)
233         if start.Y == end.Y {
234                 la.lines[start.Y].data = append(la.lines[start.Y].data[:startX], la.lines[start.Y].data[endX:]...)
235         } else {
236                 la.deleteLines(start.Y+1, end.Y-1)
237                 la.deleteToEnd(Loc{startX, start.Y})
238                 la.deleteFromStart(Loc{endX - 1, start.Y + 1})
239                 la.joinLines(start.Y, start.Y+1)
240         }
241         return sub
242 }
243
244 // deleteToEnd deletes from the end of a line to the position
245 func (la *LineArray) deleteToEnd(pos Loc) {
246         la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X]
247 }
248
249 // deleteFromStart deletes from the start of a line to the position
250 func (la *LineArray) deleteFromStart(pos Loc) {
251         la.lines[pos.Y].data = la.lines[pos.Y].data[pos.X+1:]
252 }
253
254 // deleteLine deletes the line number
255 func (la *LineArray) deleteLine(y int) {
256         la.lines = la.lines[:y+copy(la.lines[y:], la.lines[y+1:])]
257 }
258
259 func (la *LineArray) deleteLines(y1, y2 int) {
260         la.lines = la.lines[:y1+copy(la.lines[y1:], la.lines[y2+1:])]
261 }
262
263 // DeleteByte deletes the byte at a position
264 func (la *LineArray) deleteByte(pos Loc) {
265         la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X+copy(la.lines[pos.Y].data[pos.X:], la.lines[pos.Y].data[pos.X+1:])]
266 }
267
268 // Substr returns the string representation between two locations
269 func (la *LineArray) Substr(start, end Loc) []byte {
270         startX := runeToByteIndex(start.X, la.lines[start.Y].data)
271         endX := runeToByteIndex(end.X, la.lines[end.Y].data)
272         if start.Y == end.Y {
273                 src := la.lines[start.Y].data[startX:endX]
274                 dest := make([]byte, len(src))
275                 copy(dest, src)
276                 return dest
277         }
278         str := make([]byte, 0, len(la.lines[start.Y+1].data)*(end.Y-start.Y))
279         str = append(str, la.lines[start.Y].data[startX:]...)
280         str = append(str, '\n')
281         for i := start.Y + 1; i <= end.Y-1; i++ {
282                 str = append(str, la.lines[i].data...)
283                 str = append(str, '\n')
284         }
285         str = append(str, la.lines[end.Y].data[:endX]...)
286         return str
287 }
288
289 // LinesNum returns the number of lines in the buffer
290 func (la *LineArray) LinesNum() int {
291         return len(la.lines)
292 }
293
294 // Start returns the start of the buffer
295 func (la *LineArray) Start() Loc {
296         return Loc{0, 0}
297 }
298
299 // End returns the location of the last character in the buffer
300 func (la *LineArray) End() Loc {
301         numlines := len(la.lines)
302         return Loc{utf8.RuneCount(la.lines[numlines-1].data), numlines - 1}
303 }
304
305 // LineBytes returns line n as an array of bytes
306 func (la *LineArray) LineBytes(n int) []byte {
307         if n >= len(la.lines) || n < 0 {
308                 return []byte{}
309         }
310         return la.lines[n].data
311 }
312
313 // State gets the highlight state for the given line number
314 func (la *LineArray) State(lineN int) highlight.State {
315         la.lines[lineN].lock.Lock()
316         defer la.lines[lineN].lock.Unlock()
317         return la.lines[lineN].state
318 }
319
320 // SetState sets the highlight state at the given line number
321 func (la *LineArray) SetState(lineN int, s highlight.State) {
322         la.lines[lineN].lock.Lock()
323         defer la.lines[lineN].lock.Unlock()
324         la.lines[lineN].state = s
325 }
326
327 // SetMatch sets the match at the given line number
328 func (la *LineArray) SetMatch(lineN int, m highlight.LineMatch) {
329         la.lines[lineN].lock.Lock()
330         defer la.lines[lineN].lock.Unlock()
331         la.lines[lineN].match = m
332 }
333
334 // Match retrieves the match for the given line number
335 func (la *LineArray) Match(lineN int) highlight.LineMatch {
336         la.lines[lineN].lock.Lock()
337         defer la.lines[lineN].lock.Unlock()
338         return la.lines[lineN].match
339 }
340
341 func (la *LineArray) Rehighlight(lineN int) bool {
342         la.lines[lineN].lock.Lock()
343         defer la.lines[lineN].lock.Unlock()
344         return la.lines[lineN].rehighlight
345 }
346
347 func (la *LineArray) SetRehighlight(lineN int, on bool) {
348         la.lines[lineN].lock.Lock()
349         defer la.lines[lineN].lock.Unlock()
350         la.lines[lineN].rehighlight = on
351 }