| 1 |
package buffer |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
"io" |
| 7 |
"sync" |
| 8 |
|
| 9 |
"github.com/zyedidia/micro/v2/internal/util" |
| 10 |
"github.com/zyedidia/micro/v2/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 := util.DecodeCharacter(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 searchState contains the search match info for a single line |
| 36 |
type searchState struct { |
| 37 |
search string |
| 38 |
useRegex bool |
| 39 |
ignorecase bool |
| 40 |
match [][2]int |
| 41 |
done bool |
| 42 |
} |
| 43 |
|
| 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 |
| 46 |
type Line struct { |
| 47 |
data []byte |
| 48 |
|
| 49 |
state highlight.State |
| 50 |
match highlight.LineMatch |
| 51 |
lock sync.Mutex |
| 52 |
|
| 53 |
// The search states for the line, used for highlighting of search matches, |
| 54 |
// separately from the syntax highlighting. |
| 55 |
// A map is used because the line array may be shared between multiple buffers |
| 56 |
// (multiple instances of the same file opened in different edit panes) |
| 57 |
// which have distinct searches, so in the general case there are multiple |
| 58 |
// searches per a line, one search per a Buffer containing this line. |
| 59 |
search map[*Buffer]*searchState |
| 60 |
} |
| 61 |
|
| 62 |
const ( |
| 63 |
// Line ending file formats |
| 64 |
FFAuto = 0 // Autodetect format |
| 65 |
FFUnix = 1 // LF line endings (unix style '\n') |
| 66 |
FFDos = 2 // CRLF line endings (dos style '\r\n') |
| 67 |
) |
| 68 |
|
| 69 |
type FileFormat byte |
| 70 |
|
| 71 |
// A LineArray simply stores and array of lines and makes it easy to insert |
| 72 |
// and delete in it |
| 73 |
type LineArray struct { |
| 74 |
lines []Line |
| 75 |
Endings FileFormat |
| 76 |
initsize uint64 |
| 77 |
lock sync.Mutex |
| 78 |
} |
| 79 |
|
| 80 |
// Append efficiently appends lines together |
| 81 |
// It allocates an additional 10000 lines if the original estimate |
| 82 |
// is incorrect |
| 83 |
func Append(slice []Line, data ...Line) []Line { |
| 84 |
l := len(slice) |
| 85 |
if l+len(data) > cap(slice) { // reallocate |
| 86 |
newSlice := make([]Line, (l+len(data))+10000) |
| 87 |
copy(newSlice, slice) |
| 88 |
slice = newSlice |
| 89 |
} |
| 90 |
slice = slice[0 : l+len(data)] |
| 91 |
for i, c := range data { |
| 92 |
slice[l+i] = c |
| 93 |
} |
| 94 |
return slice |
| 95 |
} |
| 96 |
|
| 97 |
// NewLineArray returns a new line array from an array of bytes |
| 98 |
func NewLineArray(size uint64, endings FileFormat, reader io.Reader) *LineArray { |
| 99 |
la := new(LineArray) |
| 100 |
|
| 101 |
la.lines = make([]Line, 0, 1000) |
| 102 |
la.initsize = size |
| 103 |
|
| 104 |
br := bufio.NewReader(reader) |
| 105 |
var loaded int |
| 106 |
|
| 107 |
la.Endings = endings |
| 108 |
|
| 109 |
n := 0 |
| 110 |
for { |
| 111 |
data, err := br.ReadBytes('\n') |
| 112 |
// Detect the line ending by checking to see if there is a '\r' char |
| 113 |
// before the '\n' |
| 114 |
// Even if the file format is set to DOS, the '\r' is removed so |
| 115 |
// that all lines end with '\n' |
| 116 |
dlen := len(data) |
| 117 |
if dlen > 1 && data[dlen-2] == '\r' { |
| 118 |
data = append(data[:dlen-2], '\n') |
| 119 |
if la.Endings == FFAuto { |
| 120 |
la.Endings = FFDos |
| 121 |
} |
| 122 |
dlen = len(data) |
| 123 |
} else if dlen > 0 { |
| 124 |
if la.Endings == FFAuto { |
| 125 |
la.Endings = FFUnix |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 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) |
| 138 |
la.lines = newSlice |
| 139 |
loaded = -1 |
| 140 |
} |
| 141 |
|
| 142 |
// Counter for the number of bytes in the first 1000 lines |
| 143 |
if loaded >= 0 { |
| 144 |
loaded += dlen |
| 145 |
} |
| 146 |
|
| 147 |
if err != nil { |
| 148 |
if err == io.EOF { |
| 149 |
la.lines = Append(la.lines, Line{ |
| 150 |
data: data, |
| 151 |
state: nil, |
| 152 |
match: nil, |
| 153 |
}) |
| 154 |
} |
| 155 |
// Last line was read |
| 156 |
break |
| 157 |
} else { |
| 158 |
la.lines = Append(la.lines, Line{ |
| 159 |
data: data[:dlen-1], |
| 160 |
state: nil, |
| 161 |
match: nil, |
| 162 |
}) |
| 163 |
} |
| 164 |
n++ |
| 165 |
} |
| 166 |
|
| 167 |
return la |
| 168 |
} |
| 169 |
|
| 170 |
// Bytes returns the string that should be written to disk when |
| 171 |
// the line array is saved |
| 172 |
func (la *LineArray) Bytes() []byte { |
| 173 |
b := new(bytes.Buffer) |
| 174 |
// initsize should provide a good estimate |
| 175 |
b.Grow(int(la.initsize + 4096)) |
| 176 |
for i, l := range la.lines { |
| 177 |
b.Write(l.data) |
| 178 |
if i != len(la.lines)-1 { |
| 179 |
if la.Endings == FFDos { |
| 180 |
b.WriteByte('\r') |
| 181 |
} |
| 182 |
b.WriteByte('\n') |
| 183 |
} |
| 184 |
} |
| 185 |
return b.Bytes() |
| 186 |
} |
| 187 |
|
| 188 |
// newlineBelow adds a newline below the given line number |
| 189 |
func (la *LineArray) newlineBelow(y int) { |
| 190 |
la.lines = append(la.lines, Line{ |
| 191 |
data: []byte{' '}, |
| 192 |
state: nil, |
| 193 |
match: nil, |
| 194 |
}) |
| 195 |
copy(la.lines[y+2:], la.lines[y+1:]) |
| 196 |
la.lines[y+1] = Line{ |
| 197 |
data: []byte{}, |
| 198 |
state: la.lines[y].state, |
| 199 |
match: nil, |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
// Inserts a byte array at a given location |
| 204 |
func (la *LineArray) insert(pos Loc, value []byte) { |
| 205 |
la.lock.Lock() |
| 206 |
defer la.lock.Unlock() |
| 207 |
|
| 208 |
x, y := runeToByteIndex(pos.X, la.lines[pos.Y].data), pos.Y |
| 209 |
for i := 0; i < len(value); i++ { |
| 210 |
if value[i] == '\n' || (value[i] == '\r' && i < len(value)-1 && value[i+1] == '\n') { |
| 211 |
la.split(Loc{x, y}) |
| 212 |
x = 0 |
| 213 |
y++ |
| 214 |
|
| 215 |
if value[i] == '\r' { |
| 216 |
i++ |
| 217 |
} |
| 218 |
|
| 219 |
continue |
| 220 |
} |
| 221 |
la.insertByte(Loc{x, y}, value[i]) |
| 222 |
x++ |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
// InsertByte inserts a byte at a given location |
| 227 |
func (la *LineArray) insertByte(pos Loc, value byte) { |
| 228 |
la.lines[pos.Y].data = append(la.lines[pos.Y].data, 0) |
| 229 |
copy(la.lines[pos.Y].data[pos.X+1:], la.lines[pos.Y].data[pos.X:]) |
| 230 |
la.lines[pos.Y].data[pos.X] = value |
| 231 |
} |
| 232 |
|
| 233 |
// joinLines joins the two lines a and b |
| 234 |
func (la *LineArray) joinLines(a, b int) { |
| 235 |
la.lines[a].data = append(la.lines[a].data, la.lines[b].data...) |
| 236 |
la.deleteLine(b) |
| 237 |
} |
| 238 |
|
| 239 |
// split splits a line at a given position |
| 240 |
func (la *LineArray) split(pos Loc) { |
| 241 |
la.newlineBelow(pos.Y) |
| 242 |
la.lines[pos.Y+1].data = append(la.lines[pos.Y+1].data, la.lines[pos.Y].data[pos.X:]...) |
| 243 |
la.lines[pos.Y+1].state = la.lines[pos.Y].state |
| 244 |
la.lines[pos.Y].state = nil |
| 245 |
la.lines[pos.Y].match = nil |
| 246 |
la.lines[pos.Y+1].match = nil |
| 247 |
la.deleteToEnd(Loc{pos.X, pos.Y}) |
| 248 |
} |
| 249 |
|
| 250 |
// removes from start to end |
| 251 |
func (la *LineArray) remove(start, end Loc) []byte { |
| 252 |
la.lock.Lock() |
| 253 |
defer la.lock.Unlock() |
| 254 |
|
| 255 |
sub := la.Substr(start, end) |
| 256 |
startX := runeToByteIndex(start.X, la.lines[start.Y].data) |
| 257 |
endX := runeToByteIndex(end.X, la.lines[end.Y].data) |
| 258 |
if start.Y == end.Y { |
| 259 |
la.lines[start.Y].data = append(la.lines[start.Y].data[:startX], la.lines[start.Y].data[endX:]...) |
| 260 |
} else { |
| 261 |
la.deleteLines(start.Y+1, end.Y-1) |
| 262 |
la.deleteToEnd(Loc{startX, start.Y}) |
| 263 |
la.deleteFromStart(Loc{endX - 1, start.Y + 1}) |
| 264 |
la.joinLines(start.Y, start.Y+1) |
| 265 |
} |
| 266 |
return sub |
| 267 |
} |
| 268 |
|
| 269 |
// deleteToEnd deletes from the end of a line to the position |
| 270 |
func (la *LineArray) deleteToEnd(pos Loc) { |
| 271 |
la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X] |
| 272 |
} |
| 273 |
|
| 274 |
// deleteFromStart deletes from the start of a line to the position |
| 275 |
func (la *LineArray) deleteFromStart(pos Loc) { |
| 276 |
la.lines[pos.Y].data = la.lines[pos.Y].data[pos.X+1:] |
| 277 |
} |
| 278 |
|
| 279 |
// deleteLine deletes the line number |
| 280 |
func (la *LineArray) deleteLine(y int) { |
| 281 |
la.lines = la.lines[:y+copy(la.lines[y:], la.lines[y+1:])] |
| 282 |
} |
| 283 |
|
| 284 |
func (la *LineArray) deleteLines(y1, y2 int) { |
| 285 |
la.lines = la.lines[:y1+copy(la.lines[y1:], la.lines[y2+1:])] |
| 286 |
} |
| 287 |
|
| 288 |
// Substr returns the string representation between two locations |
| 289 |
func (la *LineArray) Substr(start, end Loc) []byte { |
| 290 |
startX := runeToByteIndex(start.X, la.lines[start.Y].data) |
| 291 |
endX := runeToByteIndex(end.X, la.lines[end.Y].data) |
| 292 |
if start.Y == end.Y { |
| 293 |
src := la.lines[start.Y].data[startX:endX] |
| 294 |
dest := make([]byte, len(src)) |
| 295 |
copy(dest, src) |
| 296 |
return dest |
| 297 |
} |
| 298 |
str := make([]byte, 0, len(la.lines[start.Y+1].data)*(end.Y-start.Y)) |
| 299 |
str = append(str, la.lines[start.Y].data[startX:]...) |
| 300 |
str = append(str, '\n') |
| 301 |
for i := start.Y + 1; i <= end.Y-1; i++ { |
| 302 |
str = append(str, la.lines[i].data...) |
| 303 |
str = append(str, '\n') |
| 304 |
} |
| 305 |
str = append(str, la.lines[end.Y].data[:endX]...) |
| 306 |
return str |
| 307 |
} |
| 308 |
|
| 309 |
// LinesNum returns the number of lines in the buffer |
| 310 |
func (la *LineArray) LinesNum() int { |
| 311 |
return len(la.lines) |
| 312 |
} |
| 313 |
|
| 314 |
// Start returns the start of the buffer |
| 315 |
func (la *LineArray) Start() Loc { |
| 316 |
return Loc{0, 0} |
| 317 |
} |
| 318 |
|
| 319 |
// End returns the location of the last character in the buffer |
| 320 |
func (la *LineArray) End() Loc { |
| 321 |
numlines := len(la.lines) |
| 322 |
return Loc{util.CharacterCount(la.lines[numlines-1].data), numlines - 1} |
| 323 |
} |
| 324 |
|
| 325 |
// LineBytes returns line n as an array of bytes |
| 326 |
func (la *LineArray) LineBytes(lineN int) []byte { |
| 327 |
if lineN >= len(la.lines) || lineN < 0 { |
| 328 |
return []byte{} |
| 329 |
} |
| 330 |
return la.lines[lineN].data |
| 331 |
} |
| 332 |
|
| 333 |
// State gets the highlight state for the given line number |
| 334 |
func (la *LineArray) State(lineN int) highlight.State { |
| 335 |
la.lines[lineN].lock.Lock() |
| 336 |
defer la.lines[lineN].lock.Unlock() |
| 337 |
return la.lines[lineN].state |
| 338 |
} |
| 339 |
|
| 340 |
// SetState sets the highlight state at the given line number |
| 341 |
func (la *LineArray) SetState(lineN int, s highlight.State) { |
| 342 |
la.lines[lineN].lock.Lock() |
| 343 |
defer la.lines[lineN].lock.Unlock() |
| 344 |
la.lines[lineN].state = s |
| 345 |
} |
| 346 |
|
| 347 |
// SetMatch sets the match at the given line number |
| 348 |
func (la *LineArray) SetMatch(lineN int, m highlight.LineMatch) { |
| 349 |
la.lines[lineN].lock.Lock() |
| 350 |
defer la.lines[lineN].lock.Unlock() |
| 351 |
la.lines[lineN].match = m |
| 352 |
} |
| 353 |
|
| 354 |
// Match retrieves the match for the given line number |
| 355 |
func (la *LineArray) Match(lineN int) highlight.LineMatch { |
| 356 |
la.lines[lineN].lock.Lock() |
| 357 |
defer la.lines[lineN].lock.Unlock() |
| 358 |
return la.lines[lineN].match |
| 359 |
} |
| 360 |
|
| 361 |
// Locks the whole LineArray |
| 362 |
func (la *LineArray) Lock() { |
| 363 |
la.lock.Lock() |
| 364 |
} |
| 365 |
|
| 366 |
// Unlocks the whole LineArray |
| 367 |
func (la *LineArray) Unlock() { |
| 368 |
la.lock.Unlock() |
| 369 |
} |
| 370 |
|
| 371 |
// SearchMatch returns true if the location `pos` is within a match |
| 372 |
// of the last search for the buffer `b`. |
| 373 |
// It is used for efficient highlighting of search matches (separately |
| 374 |
// from the syntax highlighting). |
| 375 |
// SearchMatch searches for the matches if it is called first time |
| 376 |
// for the given line or if the line was modified. Otherwise the |
| 377 |
// previously found matches are used. |
| 378 |
// |
| 379 |
// The buffer `b` needs to be passed because the line array may be shared |
| 380 |
// between multiple buffers (multiple instances of the same file opened |
| 381 |
// in different edit panes) which have distinct searches, so SearchMatch |
| 382 |
// needs to know which search to match against. |
| 383 |
func (la *LineArray) SearchMatch(b *Buffer, pos Loc) bool { |
| 384 |
if b.LastSearch == "" { |
| 385 |
return false |
| 386 |
} |
| 387 |
|
| 388 |
lineN := pos.Y |
| 389 |
if la.lines[lineN].search == nil { |
| 390 |
la.lines[lineN].search = make(map[*Buffer]*searchState) |
| 391 |
} |
| 392 |
s, ok := la.lines[lineN].search[b] |
| 393 |
if !ok { |
| 394 |
// Note: here is a small harmless leak: when the buffer `b` is closed, |
| 395 |
// `s` is not deleted from the map. It means that the buffer |
| 396 |
// will not be garbage-collected until the line array is garbage-collected, |
| 397 |
// i.e. until all the buffers sharing this file are closed. |
| 398 |
s = new(searchState) |
| 399 |
la.lines[lineN].search[b] = s |
| 400 |
} |
| 401 |
if !ok || s.search != b.LastSearch || s.useRegex != b.LastSearchRegex || |
| 402 |
s.ignorecase != b.Settings["ignorecase"].(bool) { |
| 403 |
s.search = b.LastSearch |
| 404 |
s.useRegex = b.LastSearchRegex |
| 405 |
s.ignorecase = b.Settings["ignorecase"].(bool) |
| 406 |
s.done = false |
| 407 |
} |
| 408 |
|
| 409 |
if !s.done { |
| 410 |
s.match = nil |
| 411 |
start := Loc{0, lineN} |
| 412 |
end := Loc{util.CharacterCount(la.lines[lineN].data), lineN} |
| 413 |
for start.X < end.X { |
| 414 |
m, found, _ := b.FindNext(b.LastSearch, start, end, start, true, b.LastSearchRegex) |
| 415 |
if !found { |
| 416 |
break |
| 417 |
} |
| 418 |
s.match = append(s.match, [2]int{m[0].X, m[1].X}) |
| 419 |
|
| 420 |
start.X = m[1].X |
| 421 |
if m[1].X == m[0].X { |
| 422 |
start.X = m[1].X + 1 |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
s.done = true |
| 427 |
} |
| 428 |
|
| 429 |
for _, m := range s.match { |
| 430 |
if pos.X >= m[0] && pos.X < m[1] { |
| 431 |
return true |
| 432 |
} |
| 433 |
} |
| 434 |
return false |
| 435 |
} |
| 436 |
|
| 437 |
// invalidateSearchMatches marks search matches for the given line as outdated. |
| 438 |
// It is called when the line is modified. |
| 439 |
func (la *LineArray) invalidateSearchMatches(lineN int) { |
| 440 |
if la.lines[lineN].search != nil { |
| 441 |
for _, s := range la.lines[lineN].search { |
| 442 |
s.done = false |
| 443 |
} |
| 444 |
} |
| 445 |
} |