class TextEditor::Buffer

An internal representation of a buffer. These buffers are rendered out to the terminal by {Window} instances.

Public Class Methods

new(lines = nil) click to toggle source
   # File lib/text_editor/buffer.rb
 8 def initialize(lines = nil)
 9   @lines = parse_lines(lines)
10 end

Public Instance Methods

delete_char(line, column) click to toggle source
   # File lib/text_editor/buffer.rb
12 def delete_char(line, column)
13   validate_line!(line)
14   content = self.line(line)
15   content.slice!(column)
16   replace_line(line, content)
17 end
delete_line(line) click to toggle source
   # File lib/text_editor/buffer.rb
19 def delete_line(line)
20   lines = @lines.dup
21   lines.delete_at(line)
22   self.class.new(lines)
23 end
each_line(&block) click to toggle source
   # File lib/text_editor/buffer.rb
25 def each_line(&block)
26   @lines.each(&block)
27 end
insert_char(line, column, char) click to toggle source
   # File lib/text_editor/buffer.rb
29 def insert_char(line, column, char)
30   validate_line!(line)
31   content = self.line(line)
32   content.insert(column, char)
33   replace_line(line, content)
34 end
insert_line(line, content = "") click to toggle source
   # File lib/text_editor/buffer.rb
36 def insert_line(line, content = "")
37   lines = @lines.dup.insert(line, content)
38   self.class.new(lines.compact)
39 end
line(line) click to toggle source
   # File lib/text_editor/buffer.rb
41 def line(line)
42   @lines[line].to_s.dup
43 end
replace_char(line, column, char) click to toggle source
   # File lib/text_editor/buffer.rb
45 def replace_char(line, column, char)
46   validate_line!(line)
47   content = self.line(line)
48   content[column] = char
49   replace_line(line, content)
50 end
replace_line(line, content = "") click to toggle source
   # File lib/text_editor/buffer.rb
52 def replace_line(line, content = "")
53   validate_line!(line)
54   lines = @lines.dup
55   lines[line] = content
56   self.class.new(lines.compact)
57 end
size() click to toggle source
   # File lib/text_editor/buffer.rb
59 def size
60   @lines.size
61 end
to_s() click to toggle source
   # File lib/text_editor/buffer.rb
63 def to_s
64   @lines.join("\n")
65 end

Private Instance Methods

parse_lines(lines) click to toggle source
   # File lib/text_editor/buffer.rb
69 def parse_lines(lines)
70   case lines
71   when nil, ""
72     [""]
73   when Array
74     lines
75   when Pathname
76     parse_lines(lines.safe_read)
77   when String
78     lines.each_line.map(&:chomp)
79   else
80     raise ArgumentError
81   end
82 end
validate_line!(line) click to toggle source
   # File lib/text_editor/buffer.rb
84 def validate_line!(line)
85   raise IndexError if line >= size
86 end