model.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package editor
  2. import (
  3. "moose/internal/buffer"
  4. "github.com/zyedidia/rope"
  5. "unicode/utf8"
  6. "strings"
  7. )
  8. type Model struct {
  9. Buffer buffer.Buffer
  10. CommandBuffer buffer.Buffer
  11. Actions []Action
  12. Width int
  13. Height int
  14. ShouldQuit bool
  15. }
  16. func NewModel() Model {
  17. initialBuf := buffer.Buffer{
  18. Rope: rope.New([]byte{}),
  19. CM: buffer.CursorManager{
  20. Cursors: []buffer.Cursor{{Offset: 0, Goal: 0}},
  21. PrimaryIdx: 0,
  22. },
  23. }
  24. //vp := viewport.New()
  25. //vp.MouseWheelEnabled = false
  26. model := Model{
  27. Buffer: initialBuf,
  28. Actions: DefaultActions(),
  29. ShouldQuit: false,
  30. }
  31. return model
  32. }
  33. func (m *Model) Quit() {
  34. m.ShouldQuit = true
  35. }
  36. func (m Model) ToString() string {
  37. content := []byte(m.Buffer.String())
  38. cursorMap := make(map[int]bool)
  39. for _, cur := range m.Buffer.CM.Cursors {
  40. offset := cur.Offset
  41. if offset < 0 {
  42. offset = 0
  43. }
  44. if offset > len(content) {
  45. offset = len(content)
  46. }
  47. cursorMap[offset] = true
  48. }
  49. var out strings.Builder
  50. out.Grow(len(content) + len(cursorMap))
  51. for i := 0; i < len(content); {
  52. r, size := utf8.DecodeRune(content[i:])
  53. if r == utf8.RuneError && size == 1 {
  54. if cursorMap[i] {
  55. out.WriteRune('█')
  56. i++
  57. continue
  58. }
  59. out.WriteByte(content[i])
  60. i++
  61. continue
  62. }
  63. if cursorMap[i] {
  64. out.WriteRune('█')
  65. if r == '\n' {
  66. out.WriteRune('\n')
  67. }
  68. i += size
  69. continue
  70. }
  71. out.WriteRune(r)
  72. i += size
  73. }
  74. if cursorMap[len(content)] {
  75. out.WriteRune('█')
  76. }
  77. return out.String()
  78. }