Class: HighLine

Inherits:
Object show all
Includes:
SystemExtensions
Defined in:
lib/highline.rb,
lib/highline/menu.rb,
lib/highline/question.rb,
lib/highline/color_scheme.rb,
lib/highline/system_extensions.rb

Overview

system_extensions.rb

Created by James Edward Gray II on 2006-06-14.
Copyright 2006 Gray Productions. All rights reserved.

This is Free Software.  See LICENSE and COPYING for details.

Defined Under Namespace

Modules: SystemExtensions Classes: ColorScheme, InvalidAnswerError, Menu, Question, QuestionError, SampleColorScheme

Constant Summary collapse

VERSION =

The version of the installed library.

"1.5.9".freeze
CLEAR =

Embed in a String to clear all previous ANSI sequences. This MUST be done before the program exits!

"\e[0m"
RESET =

An alias for CLEAR.

CLEAR
ERASE_LINE =

Erase the current line of terminal output.

"\e[K"
ERASE_CHAR =

Erase the character under the cursor.

"\e[P"
BOLD =

The start of an ANSI bold sequence.

"\e[1m"
DARK =

The start of an ANSI dark sequence. (Terminal support uncommon.)

"\e[2m"
UNDERLINE =

The start of an ANSI underline sequence.

"\e[4m"
UNDERSCORE =

An alias for UNDERLINE.

UNDERLINE
"\e[5m"
REVERSE =

The start of an ANSI reverse sequence.

"\e[7m"
CONCEALED =

The start of an ANSI concealed sequence. (Terminal support uncommon.)

"\e[8m"
BLACK =

Set the terminal’s foreground ANSI color to black.

"\e[30m"
RED =

Set the terminal’s foreground ANSI color to red.

"\e[31m"
GREEN =

Set the terminal’s foreground ANSI color to green.

"\e[32m"
YELLOW =

Set the terminal’s foreground ANSI color to yellow.

"\e[33m"
BLUE =

Set the terminal’s foreground ANSI color to blue.

"\e[34m"
MAGENTA =

Set the terminal’s foreground ANSI color to magenta.

"\e[35m"
CYAN =

Set the terminal’s foreground ANSI color to cyan.

"\e[36m"
WHITE =

Set the terminal’s foreground ANSI color to white.

"\e[37m"
ON_BLACK =

Set the terminal’s background ANSI color to black.

"\e[40m"
ON_RED =

Set the terminal’s background ANSI color to red.

"\e[41m"
ON_GREEN =

Set the terminal’s background ANSI color to green.

"\e[42m"
ON_YELLOW =

Set the terminal’s background ANSI color to yellow.

"\e[43m"
ON_BLUE =

Set the terminal’s background ANSI color to blue.

"\e[44m"
ON_MAGENTA =

Set the terminal’s background ANSI color to magenta.

"\e[45m"
ON_CYAN =

Set the terminal’s background ANSI color to cyan.

"\e[46m"
ON_WHITE =

Set the terminal’s background ANSI color to white.

"\e[47m"
@@use_color =

The setting used to disable color output.

true
@@track_eof =

The setting used to disable EOF tracking.

true
@@color_scheme =

The setting used to control color schemes.

nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input = $stdin, output = $stdout, wrap_at = nil, page_at = nil) ⇒ HighLine

Create an instance of HighLine, connected to the streams input and output.



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/highline.rb', line 151

def initialize( input = $stdin, output = $stdout,
                wrap_at = nil, page_at = nil )
  @input   = input
  @output  = output
  
  self.wrap_at = wrap_at
  self.page_at = page_at
  
  @question = nil
  @answer   = nil
  @menu     = nil
  @header   = nil
  @prompt   = nil
  @gather   = nil
  @answers  = nil
  @key      = nil
end

Instance Attribute Details

#page_atObject

The current row setting for paging output.



174
175
176
# File 'lib/highline.rb', line 174

def page_at
  @page_at
end

#wrap_atObject

The current column setting for wrapping output.



172
173
174
# File 'lib/highline.rb', line 172

def wrap_at
  @wrap_at
end

Class Method Details

.color_schemeObject

Returns the current color scheme.



78
79
80
# File 'lib/highline.rb', line 78

def self.color_scheme
  @@color_scheme
end

.color_scheme=(setting) ⇒ Object

Pass ColorScheme to setting to turn set a HighLine color scheme.



73
74
75
# File 'lib/highline.rb', line 73

def self.color_scheme=( setting )
  @@color_scheme = setting
end

.track_eof=(setting) ⇒ Object

Pass false to setting to turn off HighLine’s EOF tracking.



60
61
62
# File 'lib/highline.rb', line 60

def self.track_eof=( setting )
  @@track_eof = setting
end

.track_eof?Boolean

Returns true if HighLine is currently tracking EOF for input.

Returns:

  • (Boolean)


65
66
67
# File 'lib/highline.rb', line 65

def self.track_eof?
  @@track_eof
end

.use_color=(setting) ⇒ Object

Pass false to setting to turn off HighLine’s color escapes.



47
48
49
# File 'lib/highline.rb', line 47

def self.use_color=( setting )
  @@use_color = setting
end

.use_color?Boolean

Returns true if HighLine is currently using color escapes.

Returns:

  • (Boolean)


52
53
54
# File 'lib/highline.rb', line 52

def self.use_color?
  @@use_color
end

.using_color_scheme?Boolean

Returns true if HighLine is currently using a color scheme.

Returns:

  • (Boolean)


83
84
85
# File 'lib/highline.rb', line 83

def self.using_color_scheme?
  not @@color_scheme.nil?
end

Instance Method Details

#agree(yes_or_no_question, character = nil) ⇒ Object

A shortcut to HighLine.ask() a question that only accepts “yes” or “no” answers (“y” and “n” are allowed) and returns true or false (true for “yes”). If provided a true value, character will cause HighLine to fetch a single character response. A block can be provided to further configure the question as in HighLine.ask()

Raises EOFError if input is exhausted.



185
186
187
188
189
190
191
192
193
194
# File 'lib/highline.rb', line 185

def agree( yes_or_no_question, character = nil )
  ask(yes_or_no_question, lambda { |yn| yn.downcase[0] == ?y}) do |q|
    q.validate                 = /\Ay(?:es)?|no?\Z/i
    q.responses[:not_valid]    = 'Please enter "yes" or "no".'
    q.responses[:ask_on_error] = :question
    q.character                = character
    
    yield q if block_given?
  end
end

#ask(question, answer_type = String, actions = Hash.new, &details) ⇒ Object

This method is the primary interface for user input. Just provide a question to ask the user, the answer_type you want returned, and optionally a code block setting up details of how you want the question handled. See HighLine.say() for details on the format of question, and HighLine::Question for more information about answer_type and what’s valid in the code block. actions is a hash with proc or lambdas which will be called on errors, default action is explain_error. Type of error, answer, and default action are send to the action.

If @question is set before ask() is called, parameters are ignored and that object (must be a HighLine::Question) is used to drive the process instead.

Raises EOFError if input is exhausted.



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/highline.rb', line 213

def ask( question, answer_type = String, actions = Hash.new, &details ) # :yields: question
  actions.default = Proc.new { |error, answer, default_action| explain_error(error) } unless actions.default
  
  @question ||= Question.new(question, answer_type, &details)
  
  return gather if @question.gather

  # readline() needs to handle it's own output, but readline only supports 
  # full line reading.  Therefore if @question.echo is anything but true, 
  # the prompt will not be issued. And we have to account for that now.
  say(@question) unless (@question.readline and @question.echo == true)
  begin
    @answer = @question.answer_or_default(get_response)
    unless @question.valid_answer?(@answer)
      raise InvalidAnswerError
    end
    
    @answer = @question.convert(@answer)
    
    if @question.in_range?(@answer)
      if @question.confirm
        # need to add a layer of scope to ask a question inside a
        # question, without destroying instance data
        context_change = self.class.new(@input, @output, @wrap_at, @page_at)
        if @question.confirm == true
          confirm_question = "Are you sure?  "
        else
          # evaluate ERb under initial scope, so it will have
          # access to @question and @answer
          template  = ERB.new(@question.confirm, nil, "%")
          confirm_question = template.result(binding)
        end
        unless context_change.agree(confirm_question)
          explain_error(nil)
          raise QuestionError
        end
      end
      
      @answer
    else
      actions[:not_in_range].call(:not_in_range, @answer, actions.default)
      raise QuestionError
    end
  rescue QuestionError
    retry
  rescue InvalidAnswerError
    actions[:not_valid].call(:not_valid, @answer, actions.default)
    retry
  rescue ArgumentError
    actions[:invalid_type].call(:invalid_type, @answer, actions.default)
    retry
  rescue Question::NoAutoCompleteMatch
    actions[:no_completion].call(:no_completion, @answer, actions.default)
    retry
  rescue Question::NotEnoughAnswers
    actions[:not_enough_answers].call(:not_enough_answers, @answer, actions.default)
    retry
  rescue NameError
    raise if $!.is_a?(NoMethodError)
    actions[:ambiguous_completion].call(:ambiguous_completion, @answer, actions.default)
    retry
  ensure
    @question = nil    # Reset Question object.
  end
end

#choose(*items, &details) ⇒ Object

This method is HighLine’s menu handler. For simple usage, you can just pass all the menu items you wish to display. At that point, choose() will build and display a menu, walk the user through selection, and return their choice amoung the provided items. You might use this in a case statement for quick and dirty menus.

However, choose() is capable of much more. If provided, a block will be passed a HighLine::Menu object to configure. Using this method, you can customize all the details of menu handling from index display, to building a complete shell-like menuing system. See HighLine::Menu for all the methods it responds to.

Raises EOFError if input is exhausted.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/highline.rb', line 294

def choose( *items, &details )
  @menu = @question = Menu.new(&details)
  @menu.choices(*items) unless items.empty?
  
  # Set _answer_type_ so we can double as the Question for ask().
  @menu.answer_type = if @menu.shell
    lambda do |command|    # shell-style selection
      first_word = command.to_s.split.first || ""

      options = @menu.options
      options.extend(OptionParser::Completion)
      answer = options.complete(first_word)

      if answer.nil?
        raise Question::NoAutoCompleteMatch
      end

      [answer.last, command.sub(/^\s*#{first_word}\s*/, "")]
    end
  else
    @menu.options          # normal menu selection, by index or name
  end
  
  # Provide hooks for ERb layouts.
  @header   = @menu.header
  @prompt   = @menu.prompt
  
  if @menu.shell
    selected = ask("Ignored", @menu.answer_type)
    @menu.select(self, *selected)
  else
    selected = ask("Ignored", @menu.answer_type)
    @menu.select(self, selected)
  end
end

#color(string, *colors) ⇒ Object

This method provides easy access to ANSI color sequences, without the user needing to remember to CLEAR at the end of each sequence. Just pass the string to color, followed by a list of colors you would like it to be affected by. The colors can be HighLine class constants, or symbols (:blue for BLUE, for example). A CLEAR will automatically be embedded to the end of the returned String.

This method returns the original string unchanged if HighLine::use_color? is false.



341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/highline.rb', line 341

def color( string, *colors )
  return string unless self.class.use_color?
  
  colors.map! do |c|
    if self.class.using_color_scheme? and self.class.color_scheme.include? c
      self.class.color_scheme[c]
    elsif c.is_a? Symbol
      self.class.const_get(c.to_s.upcase)
    else
      c
    end
  end
  "#{colors.flatten.join}#{string}#{CLEAR}"
end

#list(items, mode = :rows, option = nil) ⇒ Object

This method is a utility for quickly and easily laying out lists. It can be accessed within ERb replacements of any text that will be sent to the user.

The only required parameter is items, which should be the Array of items to list. A specified mode controls how that list is formed and option has different effects, depending on the mode. Recognized modes are:

:columns_across

items will be placed in columns, flowing from left to right. If given, option is the number of columns to be used. When absent, columns will be determined based on wrap_at or a default of 80 characters.

:columns_down

Identical to :columns_across, save flow goes down.

:inline

All items are placed on a single line. The last two items are separated by option or a default of “ or ”. All other items are separated by “, ”.

:rows

The default mode. Each of the items is placed on it’s own line. The option parameter is ignored in this mode.

Each member of the items Array is passed through ERb and thus can contain their own expansions. Color escape expansions do not contribute to the final field width.



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/highline.rb', line 384

def list( items, mode = :rows, option = nil )
  items = items.to_ary.map do |item|
    ERB.new(item, nil, "%").result(binding)
  end
  
  case mode
  when :inline
    option = " or " if option.nil?
    
    case items.size
    when 0
      ""
    when 1
      items.first
    when 2
      "#{items.first}#{option}#{items.last}"
    else
      items[0..-2].join(", ") + "#{option}#{items.last}"
    end
  when :columns_across, :columns_down
    max_length = actual_length(
      items.max { |a, b| actual_length(a) <=> actual_length(b) }
    )

    if option.nil?
      limit  = @wrap_at || 80
      option = (limit + 2) / (max_length + 2)
    end

    items     = items.map do |item|
      pad = max_length + (item.length - actual_length(item))
      "%-#{pad}s" % item
    end
    row_count = (items.size / option.to_f).ceil
    
    if mode == :columns_across
      rows = Array.new(row_count) { Array.new }
      items.each_with_index do |item, index|
        rows[index / option] << item
      end

      rows.map { |row| row.join("  ") + "\n" }.join
    else
      columns = Array.new(option) { Array.new }
      items.each_with_index do |item, index|
        columns[index / row_count] << item
      end
    
      list = ""
      columns.first.size.times do |index|
        list << columns.map { |column| column[index] }.
                        compact.join("  ") + "\n"
      end
      list
    end
  else
    items.map { |i| "#{i}\n" }.join
  end
end

#output_colsObject

Returns the number of columns for the console, or a default it they cannot be determined.



496
497
498
499
500
501
# File 'lib/highline.rb', line 496

def output_cols
  return 80 unless @output.tty?
  terminal_size.first
rescue
  return 80
end

#output_rowsObject

Returns the number of rows for the console, or a default if they cannot be determined.



507
508
509
510
511
512
# File 'lib/highline.rb', line 507

def output_rows
  return 24 unless @output.tty?
  terminal_size.last
rescue
  return 24
end

#say(statement) ⇒ Object

The basic output method for HighLine objects. If the provided statement ends with a space or tab character, a newline will not be appended (output will be flush()ed). All other cases are passed straight to Kernel.puts().

The statement parameter is processed as an ERb template, supporting embedded Ruby code. The template is evaluated with a binding inside the HighLine instance, providing easy access to the ANSI color constants and the HighLine.color() method.



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/highline.rb', line 454

def say( statement )
  statement = statement.to_str
  return unless statement.length > 0
  
  template  = ERB.new(statement, nil, "%")
  statement = template.result(binding)
  
  statement = wrap(statement) unless @wrap_at.nil?
  statement = page_print(statement) unless @page_at.nil?
  
  if statement[-1, 1] == " " or statement[-1, 1] == "\t"
    @output.print(statement)
    @output.flush  
  else
    @output.puts(statement)
  end
end