buffer.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 := max(cur.Offset+delta, 0)
  87. if pos > buf.Rope.Len() {
  88. pos = buf.Rope.Len()
  89. }
  90. edit := Edit{Offset: pos, Inserted: data}
  91. buf.apply(edit)
  92. edits = append(edits, edit)
  93. cur.Offset = pos + shift
  94. _, goal := LineCol(buf, cur.Offset)
  95. cur.Goal = goal
  96. delta += shift
  97. }
  98. buf.commit(cursorsBefore, primaryBefore, edits)
  99. }
  100. func (buf *Buffer) Delete() {
  101. buf.ensureRope()
  102. buf.CM.DeduplicateAndSort()
  103. cursorsBefore, primaryBefore := buf.begin()
  104. delta := 0
  105. var edits []Edit
  106. for i := range buf.CM.Cursors {
  107. cur := &buf.CM.Cursors[i]
  108. pos := cur.Offset + delta
  109. if pos <= 0 {
  110. cur.Offset = 0
  111. continue
  112. }
  113. if pos > buf.Rope.Len() {
  114. pos = buf.Rope.Len()
  115. }
  116. left := buf.Rope.Slice(0, pos)
  117. _, size := utf8.DecodeLastRune(left)
  118. if size <= 0 {
  119. size = 1
  120. }
  121. start := max(pos-size, 0)
  122. deleted := append([]byte{}, buf.Rope.Slice(start, pos)...)
  123. edit := Edit{Offset: start, Deleted: deleted}
  124. buf.apply(edit)
  125. edits = append(edits, edit)
  126. delta -= len(deleted)
  127. cur.Offset = start
  128. _, goal := LineCol(buf, cur.Offset)
  129. cur.Goal = goal
  130. }
  131. buf.CM.DeduplicateAndSort()
  132. buf.commit(cursorsBefore, primaryBefore, edits)
  133. }
  134. func (buf *Buffer) DeleteLine() {
  135. buf.ensureRope()
  136. buf.CM.DeduplicateAndSort()
  137. if buf.Rope.Len() == 0 || len(buf.CM.Cursors) == 0 {
  138. return
  139. }
  140. cursorsBefore, primaryBefore := buf.begin()
  141. primary := buf.CM.Cursors[buf.CM.PrimaryIdx]
  142. line, _ := LineCol(buf, primary.Offset)
  143. start := OffsetForLine(buf, line)
  144. end := buf.Rope.Len()
  145. if line+1 < LineCount(buf) {
  146. end = OffsetForLine(buf, line+1)
  147. } else if line > 0 && start > 0 && buf.Rope.At(start-1) == '\n' {
  148. start--
  149. }
  150. if end <= start {
  151. return
  152. }
  153. deleted := append([]byte{}, buf.Rope.Slice(start, end)...)
  154. edit := Edit{Offset: start, Deleted: deleted}
  155. buf.apply(edit)
  156. newLine := line
  157. if newLine >= LineCount(buf) {
  158. newLine = LineCount(buf) - 1
  159. }
  160. if newLine < 0 {
  161. newLine = 0
  162. }
  163. newOffset := OffsetForLine(buf, newLine)
  164. for i := range buf.CM.Cursors {
  165. buf.CM.Cursors[i].Offset = newOffset
  166. buf.CM.Cursors[i].Goal = 0
  167. }
  168. buf.CM.DeduplicateAndSort()
  169. buf.commit(cursorsBefore, primaryBefore, []Edit{edit})
  170. }
  171. func (buf *Buffer) Clear() {
  172. buf.ensureRope()
  173. cursorsBefore, primaryBefore := buf.begin()
  174. primaryCursor := &Cursor{
  175. Offset: 0,
  176. Goal: 0,
  177. }
  178. buf.CM.Cursors = buf.CM.Cursors[:0]
  179. buf.CM.Cursors = append(buf.CM.Cursors, *primaryCursor)
  180. buf.CM.PrimaryIdx = 0
  181. var edits []Edit
  182. if buf.Rope.Len() > 0 {
  183. deleted := append([]byte{}, buf.Rope.Value()...)
  184. edit := Edit{Offset: 0, Deleted: deleted}
  185. buf.apply(edit)
  186. edits = append(edits, edit)
  187. }
  188. buf.commit(cursorsBefore, primaryBefore, edits)
  189. }
  190. func isWordRune(r rune) bool {
  191. return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
  192. }
  193. func (buf *Buffer) MoveWordHoriz(dir int) {
  194. buf.ensureRope()
  195. for i := range buf.CM.Cursors {
  196. cur := &buf.CM.Cursors[i]
  197. pos := normalizeOffset(buf.Rope, cur.Offset)
  198. switch {
  199. case dir > 0:
  200. for pos < buf.Rope.Len() {
  201. r, size := utf8.DecodeRune(buf.Rope.Slice(pos, buf.Rope.Len()))
  202. if size <= 0 {
  203. size = 1
  204. }
  205. if !isWordRune(r) {
  206. break
  207. }
  208. pos += size
  209. }
  210. for pos < buf.Rope.Len() {
  211. r, size := utf8.DecodeRune(buf.Rope.Slice(pos, buf.Rope.Len()))
  212. if size <= 0 {
  213. size = 1
  214. }
  215. if isWordRune(r) {
  216. break
  217. }
  218. pos += size
  219. }
  220. case dir < 0:
  221. for pos > 0 {
  222. start := prevRuneStart(buf.Rope, pos)
  223. r, _ := utf8.DecodeRune(buf.Rope.Slice(start, pos))
  224. if isWordRune(r) {
  225. break
  226. }
  227. pos = start
  228. }
  229. for pos > 0 {
  230. start := prevRuneStart(buf.Rope, pos)
  231. r, _ := utf8.DecodeRune(buf.Rope.Slice(start, pos))
  232. if !isWordRune(r) {
  233. break
  234. }
  235. pos = start
  236. }
  237. }
  238. cur.Offset = pos
  239. _, goal := LineCol(buf, cur.Offset)
  240. cur.Goal = goal
  241. }
  242. buf.CM.DeduplicateAndSort()
  243. }
  244. func (buf *Buffer) MoveHoriz(dir int) {
  245. buf.ensureRope()
  246. for i := range buf.CM.Cursors {
  247. cur := &buf.CM.Cursors[i]
  248. switch {
  249. case dir < 0:
  250. cur.Offset = prevRuneStart(buf.Rope, cur.Offset)
  251. case dir > 0:
  252. cur.Offset = nextRuneEnd(buf.Rope, cur.Offset)
  253. }
  254. _, goal := LineCol(buf, cur.Offset)
  255. cur.Goal = goal
  256. }
  257. buf.CM.DeduplicateAndSort()
  258. }
  259. func (buf *Buffer) MoveVert(dir int) {
  260. buf.ensureRope()
  261. for i := range buf.CM.Cursors {
  262. cur := &buf.CM.Cursors[i]
  263. line, _ := LineCol(buf, cur.Offset)
  264. targetLine := line + dir
  265. if targetLine < 0 || targetLine >= LineCount(buf) {
  266. continue
  267. }
  268. lineStart := OffsetForLine(buf, targetLine)
  269. lineEnd := lineContentEnd(buf, targetLine)
  270. lineLen := runeCount(buf.Rope, lineStart, lineEnd)
  271. goal := min(cur.Goal, lineLen)
  272. cur.Offset = OffsetForLineCol(buf, targetLine, goal)
  273. }
  274. buf.CM.DeduplicateAndSort()
  275. }
  276. func (buf *Buffer) AddCursorVert(dir int) {
  277. buf.ensureRope()
  278. var newCursors []Cursor
  279. for i := range buf.CM.Cursors {
  280. cur := &buf.CM.Cursors[i]
  281. line, _ := LineCol(buf, cur.Offset)
  282. targetLine := line + dir
  283. if targetLine < 0 || targetLine >= LineCount(buf) {
  284. continue
  285. }
  286. goal := buf.CM.Cursors[buf.CM.PrimaryIdx].Goal
  287. newCursors = append(newCursors, Cursor{
  288. Offset: OffsetForLineCol(buf, targetLine, goal),
  289. Goal: goal,
  290. })
  291. }
  292. buf.CM.Cursors = slices.Concat(buf.CM.Cursors, newCursors)
  293. buf.CM.DeduplicateAndSort()
  294. }
  295. func (buf *Buffer) ScrollToShow(line, maxHeight int) {
  296. if maxHeight <= 0 {
  297. return
  298. }
  299. if line < buf.TopLine {
  300. buf.TopLine = line
  301. } else if line >= buf.TopLine+maxHeight {
  302. buf.TopLine = line - maxHeight + 1
  303. }
  304. if buf.TopLine < 0 {
  305. buf.TopLine = 0
  306. }
  307. }
  308. func (buf *Buffer) ClearCursors() {
  309. primaryCursor := &Cursor{
  310. Offset: buf.CM.Cursors[buf.CM.PrimaryIdx].Offset,
  311. Goal: buf.CM.Cursors[buf.CM.PrimaryIdx].Goal,
  312. }
  313. buf.CM.Cursors = buf.CM.Cursors[:0]
  314. buf.CM.Cursors = append(buf.CM.Cursors, *primaryCursor)
  315. buf.CM.PrimaryIdx = 0
  316. }
  317. func LineCount(buf *Buffer) int {
  318. return buf.LI.Count()
  319. }
  320. func LineCol(buf *Buffer, offset int) (line, col int) {
  321. offset = max(normalizeOffset(buf.Rope, offset), 0)
  322. if offset > buf.Rope.Len() {
  323. offset = buf.Rope.Len()
  324. }
  325. line = buf.LI.LineForOffset(offset)
  326. lineStart := buf.LI.OffsetForLine(line)
  327. col = runeCount(buf.Rope, lineStart, offset)
  328. return
  329. }
  330. func OffsetForLine(buf *Buffer, targetLine int) int {
  331. if targetLine <= 0 {
  332. return 0
  333. }
  334. if targetLine >= buf.LI.Count() {
  335. return buf.Rope.Len()
  336. }
  337. return buf.LI.OffsetForLine(targetLine)
  338. }
  339. func OffsetForLineCol(buf *Buffer, line int, col int) int {
  340. if col <= 0 {
  341. return OffsetForLine(buf, line)
  342. }
  343. start := OffsetForLine(buf, line)
  344. end := lineContentEnd(buf, line)
  345. i := start
  346. for n := 0; i < end && n < col; n++ {
  347. _, size := utf8.DecodeRune(buf.Rope.Slice(i, end))
  348. if size <= 0 {
  349. size = 1
  350. }
  351. i += size
  352. }
  353. if i > end {
  354. return end
  355. }
  356. return i
  357. }
  358. func LineText(buf *Buffer, line int) string {
  359. start := OffsetForLine(buf, line)
  360. end := max(lineContentEnd(buf, line), start)
  361. return string(buf.Rope.Slice(start, end))
  362. }
  363. func lineContentEnd(buf *Buffer, line int) int {
  364. nextStart := OffsetForLine(buf, line+1)
  365. if nextStart > 0 && nextStart <= buf.Rope.Len() && buf.Rope.At(nextStart-1) == '\n' {
  366. return nextStart - 1
  367. }
  368. return nextStart
  369. }
  370. func runeCount(r *rope.Node, start, end int) int {
  371. if start < 0 {
  372. start = 0
  373. }
  374. if end < start {
  375. end = start
  376. }
  377. if end > r.Len() {
  378. end = r.Len()
  379. }
  380. return utf8.RuneCount(r.Slice(start, end))
  381. }
  382. func normalizeOffset(r *rope.Node, offset int) int {
  383. if offset < 0 {
  384. return 0
  385. }
  386. if offset > r.Len() {
  387. return r.Len()
  388. }
  389. for offset > 0 && offset < r.Len() && !utf8.RuneStart(r.At(offset)) {
  390. offset--
  391. }
  392. return offset
  393. }
  394. func prevRuneStart(r *rope.Node, offset int) int {
  395. offset = normalizeOffset(r, offset)
  396. if offset <= 0 {
  397. return 0
  398. }
  399. left := r.Slice(0, offset)
  400. _, size := utf8.DecodeLastRune(left)
  401. if size <= 0 {
  402. size = 1
  403. }
  404. start := max(offset-size, 0)
  405. return start
  406. }
  407. func nextRuneEnd(r *rope.Node, offset int) int {
  408. offset = normalizeOffset(r, offset)
  409. if offset >= r.Len() {
  410. return r.Len()
  411. }
  412. _, size := utf8.DecodeRune(r.Slice(offset, r.Len()))
  413. if size <= 0 {
  414. size = 1
  415. }
  416. end := offset + size
  417. if end > r.Len() {
  418. end = r.Len()
  419. }
  420. return end
  421. }
  422. func RuneAt(buf *Buffer, offset int) rune {
  423. if buf.Rope == nil || offset < 0 || offset >= buf.Rope.Len() {
  424. return ' '
  425. }
  426. r, size := utf8.DecodeRune(buf.Rope.Slice(offset, buf.Rope.Len()))
  427. if size <= 0 || r == '\n' || r == '\t' {
  428. return ' '
  429. }
  430. return r
  431. }
  432. func (buf Buffer) String() string {
  433. if buf.Rope == nil {
  434. return ""
  435. }
  436. return string(buf.Rope.Value())
  437. }