9 "github.com/zyedidia/micro/v2/internal/util"
10 "github.com/zyedidia/micro/v2/pkg/highlight"
13 // Finds the byte index of the nth rune in a byte slice
14 func runeToByteIndex(n int, txt []byte) int {
22 _, _, size := util.DecodeCharacter(txt)
35 // A searchState contains the search match info for a single line
36 type searchState struct {
44 // A Line contains the data in bytes as well as a highlight state, match
45 // and a flag for whether the highlighting needs to be updated
50 match highlight.LineMatch
54 // The search states for the line, used for highlighting of search matches,
55 // separately from the syntax highlighting.
56 // A map is used because the line array may be shared between multiple buffers
57 // (multiple instances of the same file opened in different edit panes)
58 // which have distinct searches, so in the general case there are multiple
59 // searches per a line, one search per a Buffer containing this line.
60 search map[*Buffer]*searchState
64 // Line ending file formats
65 FFAuto = 0 // Autodetect format
66 FFUnix = 1 // LF line endings (unix style '\n')
67 FFDos = 2 // CRLF line endings (dos style '\r\n')
72 // A LineArray simply stores and array of lines and makes it easy to insert
74 type LineArray struct {
80 // Append efficiently appends lines together
81 // It allocates an additional 10000 lines if the original estimate
83 func Append(slice []Line, data ...Line) []Line {
85 if l+len(data) > cap(slice) { // reallocate
86 newSlice := make([]Line, (l+len(data))+10000)
90 slice = slice[0 : l+len(data)]
91 for i, c := range data {
97 // NewLineArray returns a new line array from an array of bytes
98 func NewLineArray(size uint64, endings FileFormat, reader io.Reader) *LineArray {
101 la.lines = make([]Line, 0, 1000)
104 br := bufio.NewReader(reader)
111 data, err := br.ReadBytes('\n')
112 // Detect the line ending by checking to see if there is a '\r' char
114 // Even if the file format is set to DOS, the '\r' is removed so
115 // that all lines end with '\n'
117 if dlen > 1 && data[dlen-2] == '\r' {
118 data = append(data[:dlen-2], '\n')
119 if endings == FFAuto {
124 if endings == FFAuto {
129 // If we are loading a large file (greater than 1000) we use the file
130 // size and the length of the first 1000 lines to try to estimate
131 // how many lines will need to be allocated for the rest of the file
132 // We add an extra 10000 to the original estimate to be safe and give
133 // plenty of room for expansion
134 if n >= 1000 && loaded >= 0 {
135 totalLinesNum := int(float64(size) * (float64(n) / float64(loaded)))
136 newSlice := make([]Line, len(la.lines), totalLinesNum+10000)
137 copy(newSlice, la.lines)
142 // Counter for the number of bytes in the first 1000 lines
149 la.lines = Append(la.lines, Line{
156 // Last line was read
159 la.lines = Append(la.lines, Line{
172 // Bytes returns the string that should be written to disk when
173 // the line array is saved
174 func (la *LineArray) Bytes() []byte {
175 b := new(bytes.Buffer)
176 // initsize should provide a good estimate
177 b.Grow(int(la.initsize + 4096))
178 for i, l := range la.lines {
180 if i != len(la.lines)-1 {
181 if la.Endings == FFDos {
190 // newlineBelow adds a newline below the given line number
191 func (la *LineArray) newlineBelow(y int) {
192 la.lines = append(la.lines, Line{
198 copy(la.lines[y+2:], la.lines[y+1:])
199 la.lines[y+1] = Line{
201 state: la.lines[y].state,
207 // Inserts a byte array at a given location
208 func (la *LineArray) insert(pos Loc, value []byte) {
209 x, y := runeToByteIndex(pos.X, la.lines[pos.Y].data), pos.Y
210 for i := 0; i < len(value); i++ {
211 if value[i] == '\n' || (value[i] == '\r' && i < len(value)-1 && value[i+1] == '\n') {
216 if value[i] == '\r' {
222 la.insertByte(Loc{x, y}, value[i])
227 // InsertByte inserts a byte at a given location
228 func (la *LineArray) insertByte(pos Loc, value byte) {
229 la.lines[pos.Y].data = append(la.lines[pos.Y].data, 0)
230 copy(la.lines[pos.Y].data[pos.X+1:], la.lines[pos.Y].data[pos.X:])
231 la.lines[pos.Y].data[pos.X] = value
234 // joinLines joins the two lines a and b
235 func (la *LineArray) joinLines(a, b int) {
236 la.insert(Loc{len(la.lines[a].data), a}, la.lines[b].data)
240 // split splits a line at a given position
241 func (la *LineArray) split(pos Loc) {
242 la.newlineBelow(pos.Y)
243 la.insert(Loc{0, pos.Y + 1}, la.lines[pos.Y].data[pos.X:])
244 la.lines[pos.Y+1].state = la.lines[pos.Y].state
245 la.lines[pos.Y].state = nil
246 la.lines[pos.Y].match = nil
247 la.lines[pos.Y+1].match = nil
248 la.lines[pos.Y].rehighlight = true
249 la.deleteToEnd(Loc{pos.X, pos.Y})
252 // removes from start to end
253 func (la *LineArray) remove(start, end Loc) []byte {
254 sub := la.Substr(start, end)
255 startX := runeToByteIndex(start.X, la.lines[start.Y].data)
256 endX := runeToByteIndex(end.X, la.lines[end.Y].data)
257 if start.Y == end.Y {
258 la.lines[start.Y].data = append(la.lines[start.Y].data[:startX], la.lines[start.Y].data[endX:]...)
260 la.deleteLines(start.Y+1, end.Y-1)
261 la.deleteToEnd(Loc{startX, start.Y})
262 la.deleteFromStart(Loc{endX - 1, start.Y + 1})
263 la.joinLines(start.Y, start.Y+1)
268 // deleteToEnd deletes from the end of a line to the position
269 func (la *LineArray) deleteToEnd(pos Loc) {
270 la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X]
273 // deleteFromStart deletes from the start of a line to the position
274 func (la *LineArray) deleteFromStart(pos Loc) {
275 la.lines[pos.Y].data = la.lines[pos.Y].data[pos.X+1:]
278 // deleteLine deletes the line number
279 func (la *LineArray) deleteLine(y int) {
280 la.lines = la.lines[:y+copy(la.lines[y:], la.lines[y+1:])]
283 func (la *LineArray) deleteLines(y1, y2 int) {
284 la.lines = la.lines[:y1+copy(la.lines[y1:], la.lines[y2+1:])]
287 // DeleteByte deletes the byte at a position
288 func (la *LineArray) deleteByte(pos Loc) {
289 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:])]
292 // Substr returns the string representation between two locations
293 func (la *LineArray) Substr(start, end Loc) []byte {
294 startX := runeToByteIndex(start.X, la.lines[start.Y].data)
295 endX := runeToByteIndex(end.X, la.lines[end.Y].data)
296 if start.Y == end.Y {
297 src := la.lines[start.Y].data[startX:endX]
298 dest := make([]byte, len(src))
302 str := make([]byte, 0, len(la.lines[start.Y+1].data)*(end.Y-start.Y))
303 str = append(str, la.lines[start.Y].data[startX:]...)
304 str = append(str, '\n')
305 for i := start.Y + 1; i <= end.Y-1; i++ {
306 str = append(str, la.lines[i].data...)
307 str = append(str, '\n')
309 str = append(str, la.lines[end.Y].data[:endX]...)
313 // LinesNum returns the number of lines in the buffer
314 func (la *LineArray) LinesNum() int {
318 // Start returns the start of the buffer
319 func (la *LineArray) Start() Loc {
323 // End returns the location of the last character in the buffer
324 func (la *LineArray) End() Loc {
325 numlines := len(la.lines)
326 return Loc{util.CharacterCount(la.lines[numlines-1].data), numlines - 1}
329 // LineBytes returns line n as an array of bytes
330 func (la *LineArray) LineBytes(n int) []byte {
331 if n >= len(la.lines) || n < 0 {
334 return la.lines[n].data
337 // State gets the highlight state for the given line number
338 func (la *LineArray) State(lineN int) highlight.State {
339 la.lines[lineN].lock.Lock()
340 defer la.lines[lineN].lock.Unlock()
341 return la.lines[lineN].state
344 // SetState sets the highlight state at the given line number
345 func (la *LineArray) SetState(lineN int, s highlight.State) {
346 la.lines[lineN].lock.Lock()
347 defer la.lines[lineN].lock.Unlock()
348 la.lines[lineN].state = s
351 // SetMatch sets the match at the given line number
352 func (la *LineArray) SetMatch(lineN int, m highlight.LineMatch) {
353 la.lines[lineN].lock.Lock()
354 defer la.lines[lineN].lock.Unlock()
355 la.lines[lineN].match = m
358 // Match retrieves the match for the given line number
359 func (la *LineArray) Match(lineN int) highlight.LineMatch {
360 la.lines[lineN].lock.Lock()
361 defer la.lines[lineN].lock.Unlock()
362 return la.lines[lineN].match
365 func (la *LineArray) Rehighlight(lineN int) bool {
366 la.lines[lineN].lock.Lock()
367 defer la.lines[lineN].lock.Unlock()
368 return la.lines[lineN].rehighlight
371 func (la *LineArray) SetRehighlight(lineN int, on bool) {
372 la.lines[lineN].lock.Lock()
373 defer la.lines[lineN].lock.Unlock()
374 la.lines[lineN].rehighlight = on
377 // SearchMatch returns true if the location `pos` is within a match
378 // of the last search for the buffer `b`.
379 // It is used for efficient highlighting of search matches (separately
380 // from the syntax highlighting).
381 // SearchMatch searches for the matches if it is called first time
382 // for the given line or if the line was modified. Otherwise the
383 // previously found matches are used.
385 // The buffer `b` needs to be passed because the line array may be shared
386 // between multiple buffers (multiple instances of the same file opened
387 // in different edit panes) which have distinct searches, so SearchMatch
388 // needs to know which search to match against.
389 func (la *LineArray) SearchMatch(b *Buffer, pos Loc) bool {
390 if b.LastSearch == "" {
395 if la.lines[lineN].search == nil {
396 la.lines[lineN].search = make(map[*Buffer]*searchState)
398 s, ok := la.lines[lineN].search[b]
400 // Note: here is a small harmless leak: when the buffer `b` is closed,
401 // `s` is not deleted from the map. It means that the buffer
402 // will not be garbage-collected until the line array is garbage-collected,
403 // i.e. until all the buffers sharing this file are closed.
405 la.lines[lineN].search[b] = s
407 if !ok || s.search != b.LastSearch || s.useRegex != b.LastSearchRegex ||
408 s.ignorecase != b.Settings["ignorecase"].(bool) {
409 s.search = b.LastSearch
410 s.useRegex = b.LastSearchRegex
411 s.ignorecase = b.Settings["ignorecase"].(bool)
417 start := Loc{0, lineN}
418 end := Loc{util.CharacterCount(la.lines[lineN].data), lineN}
419 for start.X < end.X {
420 m, found, _ := b.FindNext(b.LastSearch, start, end, start, true, b.LastSearchRegex)
424 s.match = append(s.match, [2]int{m[0].X, m[1].X})
427 if m[1].X == m[0].X {
435 for _, m := range s.match {
436 if pos.X >= m[0] && pos.X < m[1] {
443 // invalidateSearchMatches marks search matches for the given line as outdated.
444 // It is called when the line is modified.
445 func (la *LineArray) invalidateSearchMatches(lineN int) {
446 if la.lines[lineN].search != nil {
447 for _, s := range la.lines[lineN].search {