kill-ring.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Ring buffer for Emacs-style kill/yank operations.
  3. *
  4. * Tracks killed (deleted) text entries. Consecutive kills can accumulate
  5. * into a single entry. Supports yank (paste most recent) and yank-pop
  6. * (cycle through older entries).
  7. */
  8. export class KillRing {
  9. private ring: string[] = [];
  10. /**
  11. * Add text to the kill ring.
  12. *
  13. * @param text - The killed text to add
  14. * @param opts - Push options
  15. * @param opts.prepend - If accumulating, prepend (backward deletion) or append (forward deletion)
  16. * @param opts.accumulate - Merge with the most recent entry instead of creating a new one
  17. */
  18. push(text: string, opts: { prepend: boolean; accumulate?: boolean }): void {
  19. if (!text) return;
  20. if (opts.accumulate && this.ring.length > 0) {
  21. const last = this.ring.pop()!;
  22. this.ring.push(opts.prepend ? text + last : last + text);
  23. } else {
  24. this.ring.push(text);
  25. }
  26. }
  27. /** Get most recent entry without modifying the ring. */
  28. peek(): string | undefined {
  29. return this.ring.length > 0 ? this.ring[this.ring.length - 1] : undefined;
  30. }
  31. /** Move last entry to front (for yank-pop cycling). */
  32. rotate(): void {
  33. if (this.ring.length > 1) {
  34. const last = this.ring.pop()!;
  35. this.ring.unshift(last);
  36. }
  37. }
  38. get length(): number {
  39. return this.ring.length;
  40. }
  41. }