]> git.cworth.org Git - sup/blob - lib/sup/modes/completion-mode.rb
Merge branch 'alignment-tweaks' into next
[sup] / lib / sup / modes / completion-mode.rb
1 module Redwood
2
3 class CompletionMode < ScrollMode
4   INTERSTITIAL = "  "
5
6   def initialize list, opts={}
7     @list = list
8     @header = opts[:header]
9     @prefix_len = opts[:prefix_len]
10     @lines = nil
11     super :slip_rows => 1, :twiddles => false
12   end
13
14   def lines
15     update_lines unless @lines
16     @lines.length
17   end
18
19   def [] i
20     update_lines unless @lines
21     @lines[i]
22   end
23
24   def roll; if at_bottom? then jump_to_start else page_down end end
25
26 private
27
28   def update_lines
29     width = buffer.content_width
30     max_length = @list.max_of { |s| s.length }
31     num_per = [1, buffer.content_width / (max_length + INTERSTITIAL.length)].max
32     @lines = [@header].compact
33     @list.each_with_index do |s, i|
34       if @prefix_len
35         @lines << [] if i % num_per == 0
36         if @prefix_len < s.length
37           prefix = s[0 ... @prefix_len]
38           suffix = s[(@prefix_len + 1) .. -1]
39           char = s[@prefix_len].chr
40
41           @lines.last += [[:none, sprintf("%#{max_length - suffix.length - 1}s", prefix)],
42                           [:completion_character_color, char],
43                           [:none, suffix + INTERSTITIAL]]
44         else
45           @lines.last += [[:none, sprintf("%#{max_length}s#{INTERSTITIAL}", s)]]
46         end
47       else
48         @lines << "" if i % num_per == 0
49         @lines.last += sprintf "%#{max_length}s#{INTERSTITIAL}", s
50       end
51     end
52   end
53 end
54
55 end