buffer.go 11 KB

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