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