1
0

buffer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package buffer
  2. import (
  3. "fmt"
  4. "os"
  5. "slices"
  6. "unicode"
  7. "unicode/utf8"
  8. "moose/internal/highlight"
  9. tree_sitter "github.com/tree-sitter/go-tree-sitter"
  10. "github.com/zyedidia/rope"
  11. )
  12. type BufferManager struct {
  13. Buffers []Buffer
  14. CurrentIdx int
  15. PaletteBuffer Buffer
  16. }
  17. func (bm *BufferManager) Current() *Buffer {
  18. if len(bm.Buffers) == 0 {
  19. return nil
  20. }
  21. if bm.CurrentIdx < 0 || bm.CurrentIdx >= len(bm.Buffers) {
  22. bm.CurrentIdx = len(bm.Buffers) - 1
  23. }
  24. return &bm.Buffers[bm.CurrentIdx]
  25. }
  26. // TODO: implement BufferType (BufferNormal, BufferVisual, BufferInteractive).
  27. // BufferVisual (completely readonly) and BufferInteractive (readonly for user) will only be navigable the Visual mode.
  28. // The visual mode will have abilities to modify the buffer, through managed functions which eg. a extension has defined.
  29. // For example pressing space to check or uncheck a radio button.
  30. // BufferVisual may be redundant, just use BufferInteractive without any defined functionality? Rename BufferInteractive to BufferVisual?
  31. // Used for interactive things: file explorer (like emacs dired), ...
  32. type Buffer struct {
  33. Rope *rope.Node
  34. LI *LineIndex
  35. CM CursorManager
  36. Path string
  37. TopLine int
  38. History UndoStack
  39. Language string
  40. HighlightQuery []byte
  41. Tree *tree_sitter.Tree
  42. Spans []highlight.HighlightSpan
  43. IsDirty bool
  44. }
  45. func NewBuffer() Buffer {
  46. return Buffer{
  47. Rope: rope.New([]byte{}),
  48. LI: NewLineIndex(),
  49. CM: CursorManager{
  50. Cursors: []Cursor{{Offset: 0, Goal: 0}},
  51. PrimaryIdx: 0,
  52. },
  53. IsDirty: true,
  54. Language: "lua",
  55. }
  56. }
  57. func NewBufferFromPath(path string) Buffer {
  58. b := NewBuffer()
  59. content, err := os.ReadFile(path)
  60. if err != nil {
  61. fmt.Printf("[moose-error] %v", err)
  62. os.Exit(1)
  63. }
  64. b.Clear()
  65. b.Rope = rope.New(content)
  66. b.LI.Rebuild(b.Rope)
  67. b.Path = path
  68. b.History = UndoStack{}
  69. b.Language = highlight.DetectLanguage(path)
  70. if b.Language != "" {
  71. if queryData, err := highlight.GetQuery(b.Language); err == nil {
  72. b.HighlightQuery = queryData
  73. }
  74. }
  75. return b
  76. }
  77. func (buf *Buffer) ensureRope() {
  78. if buf == nil {
  79. return
  80. }
  81. if buf.Rope == nil {
  82. buf.Rope = rope.New([]byte{})
  83. }
  84. if buf.LI == nil {
  85. buf.LI = NewLineIndexFromRope(buf.Rope)
  86. }
  87. }
  88. func (buf *Buffer) Insert(content string) {
  89. if buf == nil {
  90. return
  91. }
  92. buf.ensureRope()
  93. buf.CM.DeduplicateAndSort()
  94. cursorsBefore, primaryBefore := buf.begin()
  95. delta := 0
  96. data := []byte(content)
  97. shift := len(data)
  98. edits := make([]Edit, 0, len(buf.CM.Cursors))
  99. for i := range buf.CM.Cursors {
  100. cur := &buf.CM.Cursors[i]
  101. pos := max(cur.Offset+delta, 0)
  102. if pos > buf.Rope.Len() {
  103. pos = buf.Rope.Len()
  104. }
  105. edit := Edit{Offset: pos, Inserted: data}
  106. buf.apply(edit)
  107. edits = append(edits, edit)
  108. cur.Offset = pos + shift
  109. _, goal := LineCol(buf, cur.Offset)
  110. cur.Goal = goal
  111. delta += shift
  112. }
  113. buf.commit(cursorsBefore, primaryBefore, edits)
  114. }
  115. func (buf *Buffer) Delete() {
  116. buf.ensureRope()
  117. buf.CM.DeduplicateAndSort()
  118. cursorsBefore, primaryBefore := buf.begin()
  119. delta := 0
  120. var edits []Edit
  121. for i := range buf.CM.Cursors {
  122. cur := &buf.CM.Cursors[i]
  123. pos := cur.Offset + delta
  124. if pos <= 0 {
  125. cur.Offset = 0
  126. continue
  127. }
  128. if pos > buf.Rope.Len() {
  129. pos = buf.Rope.Len()
  130. }
  131. left := buf.Rope.Slice(0, pos)
  132. _, size := utf8.DecodeLastRune(left)
  133. if size <= 0 {
  134. size = 1
  135. }
  136. start := max(pos-size, 0)
  137. deleted := append([]byte{}, buf.Rope.Slice(start, pos)...)
  138. edit := Edit{Offset: start, Deleted: deleted}
  139. buf.apply(edit)
  140. edits = append(edits, edit)
  141. delta -= len(deleted)
  142. cur.Offset = start
  143. _, goal := LineCol(buf, cur.Offset)
  144. cur.Goal = goal
  145. }
  146. buf.CM.DeduplicateAndSort()
  147. buf.commit(cursorsBefore, primaryBefore, edits)
  148. }
  149. func (buf *Buffer) DeleteLine() {
  150. buf.ensureRope()
  151. buf.CM.DeduplicateAndSort()
  152. if buf.Rope.Len() == 0 || len(buf.CM.Cursors) == 0 {
  153. return
  154. }
  155. cursorsBefore, primaryBefore := buf.begin()
  156. primary := buf.CM.Cursors[buf.CM.PrimaryIdx]
  157. line, _ := LineCol(buf, primary.Offset)
  158. start := OffsetForLine(buf, line)
  159. end := buf.Rope.Len()
  160. if line+1 < LineCount(buf) {
  161. end = OffsetForLine(buf, line+1)
  162. } else if line > 0 && start > 0 && buf.Rope.At(start-1) == '\n' {
  163. start--
  164. }
  165. if end <= start {
  166. return
  167. }
  168. deleted := append([]byte{}, buf.Rope.Slice(start, end)...)
  169. edit := Edit{Offset: start, Deleted: deleted}
  170. buf.apply(edit)
  171. newLine := line
  172. if newLine >= LineCount(buf) {
  173. newLine = LineCount(buf) - 1
  174. }
  175. if newLine < 0 {
  176. newLine = 0
  177. }
  178. newOffset := OffsetForLine(buf, newLine)
  179. for i := range buf.CM.Cursors {
  180. buf.CM.Cursors[i].Offset = newOffset
  181. buf.CM.Cursors[i].Goal = 0
  182. }
  183. buf.CM.DeduplicateAndSort()
  184. buf.commit(cursorsBefore, primaryBefore, []Edit{edit})
  185. }
  186. func (buf *Buffer) Clear() {
  187. buf.ensureRope()
  188. cursorsBefore, primaryBefore := buf.begin()
  189. primaryCursor := &Cursor{
  190. Offset: 0,
  191. Goal: 0,
  192. }
  193. buf.CM.Cursors = buf.CM.Cursors[:0]
  194. buf.CM.Cursors = append(buf.CM.Cursors, *primaryCursor)
  195. buf.CM.PrimaryIdx = 0
  196. var edits []Edit
  197. if buf.Rope.Len() > 0 {
  198. deleted := append([]byte{}, buf.Rope.Value()...)
  199. edit := Edit{Offset: 0, Deleted: deleted}
  200. buf.apply(edit)
  201. edits = append(edits, edit)
  202. }
  203. buf.commit(cursorsBefore, primaryBefore, edits)
  204. }
  205. func isWordRune(r rune) bool {
  206. return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
  207. }
  208. func (buf *Buffer) MoveWordHoriz(dir int) {
  209. buf.ensureRope()
  210. for i := range buf.CM.Cursors {
  211. cur := &buf.CM.Cursors[i]
  212. pos := normalizeOffset(buf.Rope, cur.Offset)
  213. switch {
  214. case dir > 0:
  215. for pos < buf.Rope.Len() {
  216. r, size := utf8.DecodeRune(buf.Rope.Slice(pos, buf.Rope.Len()))
  217. if size <= 0 {
  218. size = 1
  219. }
  220. if !isWordRune(r) {
  221. break
  222. }
  223. pos += size
  224. }
  225. for pos < buf.Rope.Len() {
  226. r, size := utf8.DecodeRune(buf.Rope.Slice(pos, buf.Rope.Len()))
  227. if size <= 0 {
  228. size = 1
  229. }
  230. if isWordRune(r) {
  231. break
  232. }
  233. pos += size
  234. }
  235. case dir < 0:
  236. for pos > 0 {
  237. start := prevRuneStart(buf.Rope, pos)
  238. r, _ := utf8.DecodeRune(buf.Rope.Slice(start, pos))
  239. if isWordRune(r) {
  240. break
  241. }
  242. pos = start
  243. }
  244. for pos > 0 {
  245. start := prevRuneStart(buf.Rope, pos)
  246. r, _ := utf8.DecodeRune(buf.Rope.Slice(start, pos))
  247. if !isWordRune(r) {
  248. break
  249. }
  250. pos = start
  251. }
  252. }
  253. cur.Offset = pos
  254. _, goal := LineCol(buf, cur.Offset)
  255. cur.Goal = goal
  256. }
  257. buf.CM.DeduplicateAndSort()
  258. }
  259. func (buf *Buffer) MoveHoriz(dir int) {
  260. buf.ensureRope()
  261. for i := range buf.CM.Cursors {
  262. cur := &buf.CM.Cursors[i]
  263. switch {
  264. case dir < 0:
  265. cur.Offset = prevRuneStart(buf.Rope, cur.Offset)
  266. case dir > 0:
  267. cur.Offset = nextRuneEnd(buf.Rope, cur.Offset)
  268. }
  269. _, goal := LineCol(buf, cur.Offset)
  270. cur.Goal = goal
  271. }
  272. buf.CM.DeduplicateAndSort()
  273. }
  274. func (buf *Buffer) MoveVert(dir int) {
  275. buf.ensureRope()
  276. for i := range buf.CM.Cursors {
  277. cur := &buf.CM.Cursors[i]
  278. line, _ := LineCol(buf, cur.Offset)
  279. targetLine := line + dir
  280. if targetLine < 0 || targetLine >= LineCount(buf) {
  281. continue
  282. }
  283. lineStart := OffsetForLine(buf, targetLine)
  284. lineEnd := lineContentEnd(buf, targetLine)
  285. lineLen := runeCount(buf.Rope, lineStart, lineEnd)
  286. goal := min(cur.Goal, lineLen)
  287. cur.Offset = OffsetForLineCol(buf, targetLine, goal)
  288. }
  289. buf.CM.DeduplicateAndSort()
  290. }
  291. func (buf *Buffer) AddCursorVert(dir int) {
  292. buf.ensureRope()
  293. var newCursors []Cursor
  294. for i := range buf.CM.Cursors {
  295. cur := &buf.CM.Cursors[i]
  296. line, _ := LineCol(buf, cur.Offset)
  297. targetLine := line + dir
  298. if targetLine < 0 || targetLine >= LineCount(buf) {
  299. continue
  300. }
  301. goal := buf.CM.Cursors[buf.CM.PrimaryIdx].Goal
  302. newCursors = append(newCursors, Cursor{
  303. Offset: OffsetForLineCol(buf, targetLine, goal),
  304. Goal: goal,
  305. })
  306. }
  307. buf.CM.Cursors = slices.Concat(buf.CM.Cursors, newCursors)
  308. buf.CM.DeduplicateAndSort()
  309. }
  310. func (buf *Buffer) ScrollToShow(line, maxHeight int) {
  311. if maxHeight <= 0 {
  312. return
  313. }
  314. if line < buf.TopLine {
  315. buf.TopLine = line
  316. } else if line >= buf.TopLine+maxHeight {
  317. buf.TopLine = line - maxHeight + 1
  318. }
  319. if buf.TopLine < 0 {
  320. buf.TopLine = 0
  321. }
  322. }
  323. func (buf *Buffer) ClearCursors() {
  324. primaryCursor := &Cursor{
  325. Offset: buf.CM.Cursors[buf.CM.PrimaryIdx].Offset,
  326. Goal: buf.CM.Cursors[buf.CM.PrimaryIdx].Goal,
  327. }
  328. buf.CM.Cursors = buf.CM.Cursors[:0]
  329. buf.CM.Cursors = append(buf.CM.Cursors, *primaryCursor)
  330. buf.CM.PrimaryIdx = 0
  331. }
  332. func LineCount(buf *Buffer) int {
  333. return buf.LI.Count()
  334. }
  335. func LineCol(buf *Buffer, offset int) (line, col int) {
  336. offset = max(normalizeOffset(buf.Rope, offset), 0)
  337. if offset > buf.Rope.Len() {
  338. offset = buf.Rope.Len()
  339. }
  340. line = buf.LI.LineForOffset(offset)
  341. lineStart := buf.LI.OffsetForLine(line)
  342. col = runeCount(buf.Rope, lineStart, offset)
  343. return
  344. }
  345. func OffsetForLine(buf *Buffer, targetLine int) int {
  346. if targetLine <= 0 {
  347. return 0
  348. }
  349. if targetLine >= buf.LI.Count() {
  350. return buf.Rope.Len()
  351. }
  352. return buf.LI.OffsetForLine(targetLine)
  353. }
  354. func OffsetForLineCol(buf *Buffer, line int, col int) int {
  355. if col <= 0 {
  356. return OffsetForLine(buf, line)
  357. }
  358. start := OffsetForLine(buf, line)
  359. end := lineContentEnd(buf, line)
  360. i := start
  361. for n := 0; i < end && n < col; n++ {
  362. _, size := utf8.DecodeRune(buf.Rope.Slice(i, end))
  363. if size <= 0 {
  364. size = 1
  365. }
  366. i += size
  367. }
  368. if i > end {
  369. return end
  370. }
  371. return i
  372. }
  373. func LineText(buf *Buffer, line int) string {
  374. start := OffsetForLine(buf, line)
  375. end := max(lineContentEnd(buf, line), start)
  376. return string(buf.Rope.Slice(start, end))
  377. }
  378. func lineContentEnd(buf *Buffer, line int) int {
  379. nextStart := OffsetForLine(buf, line+1)
  380. if nextStart > 0 && nextStart <= buf.Rope.Len() && buf.Rope.At(nextStart-1) == '\n' {
  381. return nextStart - 1
  382. }
  383. return nextStart
  384. }
  385. func runeCount(r *rope.Node, start, end int) int {
  386. if start < 0 {
  387. start = 0
  388. }
  389. if end < start {
  390. end = start
  391. }
  392. if end > r.Len() {
  393. end = r.Len()
  394. }
  395. return utf8.RuneCount(r.Slice(start, end))
  396. }
  397. func normalizeOffset(r *rope.Node, offset int) int {
  398. if offset < 0 {
  399. return 0
  400. }
  401. if offset > r.Len() {
  402. return r.Len()
  403. }
  404. for offset > 0 && offset < r.Len() && !utf8.RuneStart(r.At(offset)) {
  405. offset--
  406. }
  407. return offset
  408. }
  409. func prevRuneStart(r *rope.Node, offset int) int {
  410. offset = normalizeOffset(r, offset)
  411. if offset <= 0 {
  412. return 0
  413. }
  414. left := r.Slice(0, offset)
  415. _, size := utf8.DecodeLastRune(left)
  416. if size <= 0 {
  417. size = 1
  418. }
  419. start := max(offset-size, 0)
  420. return start
  421. }
  422. func nextRuneEnd(r *rope.Node, offset int) int {
  423. offset = normalizeOffset(r, offset)
  424. if offset >= r.Len() {
  425. return r.Len()
  426. }
  427. _, size := utf8.DecodeRune(r.Slice(offset, r.Len()))
  428. if size <= 0 {
  429. size = 1
  430. }
  431. end := offset + size
  432. if end > r.Len() {
  433. end = r.Len()
  434. }
  435. return end
  436. }
  437. func RuneAt(buf *Buffer, offset int) rune {
  438. if buf.Rope == nil || offset < 0 || offset >= buf.Rope.Len() {
  439. return ' '
  440. }
  441. r, size := utf8.DecodeRune(buf.Rope.Slice(offset, buf.Rope.Len()))
  442. if size <= 0 || r == '\n' || r == '\t' {
  443. return ' '
  444. }
  445. return r
  446. }
  447. func (buf Buffer) String() string {
  448. if buf.Rope == nil {
  449. return ""
  450. }
  451. return string(buf.Rope.Value())
  452. }