| 🛟 Updated. 28d5985 k33g 18h ago | 1 | // Package buffer holds the text of one edited file, together with the cursor, |
| 2 | // the selection and the undo history. |
| 3 | // |
| 4 | // It knows nothing about terminals, rendering or syntax colouring: everything |
| 5 | // here is plain data manipulation, which makes it fully testable on its own. |
| 6 | // Positions are expressed in runes, never in bytes, so that accented letters |
| 7 | // and CJK characters count as one column like any other character. |
| 8 | package buffer |
| 9 | |
| 10 | // Position is a place in the text, as a zero-based line number and a |
| 11 | // zero-based column counted in runes. |
| 12 | // |
| 13 | // A column equal to the line length is legal: it is the position just after |
| 14 | // the last character, where the cursor sits when you press End. |
| 15 | type Position struct { |
| 16 | Line int |
| 17 | Col int |
| 18 | } |
| 19 | |
| 20 | // Before reports whether p comes strictly earlier in the text than other. |
| 21 | func (p Position) Before(other Position) bool { |
| 22 | if p.Line != other.Line { |
| 23 | return p.Line < other.Line |
| 24 | } |
| 25 | return p.Col < other.Col |
| 26 | } |
| 27 | |
| 28 | // After reports whether p comes strictly later in the text than other. |
| 29 | func (p Position) After(other Position) bool { |
| 30 | return other.Before(p) |
| 31 | } |
| 32 | |
| 33 | // Range is a half-open span of text: Start is included, End is excluded. |
| 34 | // |
| 35 | // A range whose Start equals its End is empty and covers no character; that is |
| 36 | // how an insertion point is expressed. |
| 37 | type Range struct { |
| 38 | Start Position |
| 39 | End Position |
| 40 | } |
| 41 | |
| 42 | // NewRange returns the range covering a and b, whichever of the two comes |
| 43 | // first in the text. Use it when a range is built from two user-supplied |
| 44 | // points, such as a selection anchor and the cursor. |
| 45 | func NewRange(a, b Position) Range { |
| 46 | if b.Before(a) { |
| 47 | return Range{Start: b, End: a} |
| 48 | } |
| 49 | return Range{Start: a, End: b} |
| 50 | } |
| 51 | |
| 52 | // IsEmpty reports whether the range covers no character at all. |
| 53 | func (r Range) IsEmpty() bool { |
| 54 | return r.Start == r.End |
| 55 | } |
| 56 | |
| 57 | // Contains reports whether p falls inside the range. The start is included and |
| 58 | // the end is excluded, so an empty range contains nothing. |
| 59 | func (r Range) Contains(p Position) bool { |
| 60 | return !p.Before(r.Start) && p.Before(r.End) |
| 61 | } |