MCPcopy
hub / github.com/micro-editor/micro / updateTrailingWs

Method updateTrailingWs

internal/buffer/eventhandler.go:347–399  ·  view source on GitHub ↗

updateTrailingWs updates the cursor's trailing whitespace status after a text event

(t *TextEvent)

Source from the content-addressed store, hash-verified

345
346// updateTrailingWs updates the cursor's trailing whitespace status after a text event
347func (eh *EventHandler) updateTrailingWs(t *TextEvent) {
348 if len(t.Deltas) != 1 {
349 return
350 }
351 text := t.Deltas[0].Text
352 start := t.Deltas[0].Start
353 end := t.Deltas[0].End
354
355 c := eh.cursors[eh.active]
356 isEol := func(loc Loc) bool {
357 return loc.X == util.CharacterCount(eh.buf.LineBytes(loc.Y))
358 }
359 if t.EventType == TextEventInsert && c.Loc == end && isEol(end) {
360 var addedTrailingWs bool
361 addedAfterWs := false
362 addedWsOnly := false
363 if start.Y == end.Y {
364 addedTrailingWs = util.HasTrailingWhitespace(text)
365 addedWsOnly = util.IsBytesWhitespace(text)
366 addedAfterWs = start.X > 0 && util.IsWhitespace(c.buf.RuneAt(Loc{start.X - 1, start.Y}))
367 } else {
368 lastnl := bytes.LastIndex(text, []byte{'\n'})
369 addedTrailingWs = util.HasTrailingWhitespace(text[lastnl+1:])
370 }
371
372 if addedTrailingWs && !(addedAfterWs && addedWsOnly) {
373 c.NewTrailingWsY = c.Y
374 } else if !addedTrailingWs {
375 c.NewTrailingWsY = -1
376 }
377 } else if t.EventType == TextEventRemove && c.Loc == start && isEol(start) {
378 removedAfterWs := util.HasTrailingWhitespace(eh.buf.LineBytes(start.Y))
379 var removedWsOnly bool
380 if start.Y == end.Y {
381 removedWsOnly = util.IsBytesWhitespace(text)
382 } else {
383 firstnl := bytes.Index(text, []byte{'\n'})
384 removedWsOnly = util.IsBytesWhitespace(text[:firstnl])
385 }
386
387 if removedAfterWs && !removedWsOnly {
388 c.NewTrailingWsY = c.Y
389 } else if !removedAfterWs {
390 c.NewTrailingWsY = -1
391 }
392 } else if c.NewTrailingWsY != -1 && start.Y != end.Y && c.Loc.GreaterThan(start) &&
393 ((t.EventType == TextEventInsert && c.Y == c.NewTrailingWsY+(end.Y-start.Y)) ||
394 (t.EventType == TextEventRemove && c.Y == c.NewTrailingWsY-(end.Y-start.Y))) {
395 // The cursor still has its new trailingws
396 // but its line number was shifted by insert or remove of lines above
397 c.NewTrailingWsY = c.Y
398 }
399}

Callers 1

DoTextEventMethod · 0.95

Calls 7

CharacterCountFunction · 0.92
HasTrailingWhitespaceFunction · 0.92
IsBytesWhitespaceFunction · 0.92
IsWhitespaceFunction · 0.92
RuneAtMethod · 0.80
LineBytesMethod · 0.65
GreaterThanMethod · 0.45

Tested by

no test coverage detected