lib/sup/modes/log_mode.rb (1367B) - raw
1 require 'stringio'
2 module Redwood
3
4 ## a variant of text mode that allows the user to automatically follow text,
5 ## and respawns when << is called if necessary.
6
7 class LogMode < TextMode
8 register_keymap do |k|
9 k.add :toggle_follow, "Toggle follow mode", 'f'
10 end
11
12 ## if buffer_name is supplied, this mode will spawn a buffer
13 ## upon receiving the << message. otherwise, it will act like
14 ## a regular buffer.
15 def initialize autospawn_buffer_name=nil
16 @follow = true
17 @autospawn_buffer_name = autospawn_buffer_name
18 @on_kill = []
19 super()
20 end
21
22 ## register callbacks for when the buffer is killed
23 def on_kill &b; @on_kill << b end
24
25 def toggle_follow
26 @follow = !@follow
27 if @follow
28 jump_to_line(lines - buffer.content_height + 1) # leave an empty line at bottom
29 end
30 buffer.mark_dirty
31 end
32
33 def << s
34 if buffer.nil? && @autospawn_buffer_name
35 BufferManager.spawn @autospawn_buffer_name, self, :hidden => true, :system => true
36 end
37
38 s.split("\n").each { |l| super(l + "\n") } # insane. different << semantics.
39
40 if @follow
41 follow_top = lines - buffer.content_height + 1
42 jump_to_line follow_top if topline < follow_top
43 end
44 end
45
46 def status
47 super + " (follow: #@follow)"
48 end
49
50 def cleanup
51 @on_kill.each { |cb| cb.call self }
52 self.text = ""
53 super
54 end
55 end
56
57 end