]> git.cworth.org Git - sup/blob - lib/sup/modes/text-mode.rb
Merge branch 'logging'
[sup] / lib / sup / modes / text-mode.rb
1 module Redwood
2
3 class TextMode < ScrollMode
4   attr_reader :text
5   register_keymap do |k|
6     k.add :save_to_disk, "Save to disk", 's'
7     k.add :pipe, "Pipe to process", '|'
8   end
9
10   def initialize text="", filename=nil
11     @text = text
12     @filename = filename
13     update_lines
14     buffer.mark_dirty if buffer
15     super()
16   end
17
18   def save_to_disk
19     fn = BufferManager.ask_for_filename :filename, "Save to file: ", @filename
20     save_to_file(fn) { |f| f.puts text } if fn
21   end
22
23   def pipe
24     command = BufferManager.ask(:shell, "pipe command: ")
25     return if command.nil? || command.empty?
26
27     output = pipe_to_process(command) do |stream|
28       @text.each { |l| stream.puts l }
29     end
30
31     if output
32       BufferManager.spawn "Output of '#{command}'", TextMode.new(output)
33     else
34       BufferManager.flash "'#{command}' done!"
35     end
36   end
37
38   def text= t
39     @text = t
40     update_lines
41     if buffer
42       ensure_mode_validity
43       buffer.mark_dirty 
44     end
45   end
46
47   def << line
48     @lines = [0] if @text.empty?
49     @text << line
50     @lines << @text.length
51     if buffer
52       ensure_mode_validity
53       buffer.mark_dirty
54     end
55   end
56
57   def lines
58     @lines.length - 1
59   end
60
61   def [] i
62     return nil unless i < @lines.length
63     @text[@lines[i] ... (i + 1 < @lines.length ? @lines[i + 1] - 1 : @text.length)].normalize_whitespace
64 #    (@lines[i] ... (i + 1 < @lines.length ? @lines[i + 1] - 1 : @text.length)).inspect
65   end
66
67 private
68
69   def update_lines
70     pos = @text.find_all_positions("\n")
71     pos.push @text.length unless pos.last == @text.length - 1
72     @lines = [0] + pos.map { |x| x + 1 }
73   end
74 end
75
76 end