class HighLine

A HighLine object is a “high-level line oriented” shell over an input and an output stream. HighLine simplifies common console interaction, effectively replacing puts() and gets(). User code can simply specify the question to ask and any details about user interaction, then leave the rest of the work to HighLine. When HighLine.ask() returns, you'll have the answer you requested, even if HighLine had to ask many times, validate results, perform range checking, convert types, etc.

color_scheme.rb

Created by Jeremy Hinegardner on 2007-01-24 Copyright 2007. All rights reserved

This is Free Software. See LICENSE and COPYING for details

simulate.rb

Created by Andy Rossmeissl on 2012-04-29.
Copyright 2005 Gray Productions. All rights reserved.

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

adapted from gist.github.com/194554

Extensions for class String

HighLine::String is a subclass of String with convenience methods added for colorization.

Available convenience methods include:

* 'color' method         e.g.  highline_string.color(:bright_blue, :underline)
* colors                 e.g.  highline_string.magenta
* RGB colors             e.g.  highline_string.rgb_ff6000
                          or   highline_string.rgb(255,96,0)
* background colors      e.g.  highline_string.on_magenta
* RGB background colors  e.g.  highline_string.on_rgb_ff6000
                          or   highline_string.on_rgb(255,96,0)
* styles                 e.g.  highline_string.underline

Additionally, convenience methods can be chained, for instance the following are equivalent:

highline_string.bright_blue.blink.underline
highline_string.color(:bright_blue, :blink, :underline)
HighLine.color(highline_string, :bright_blue, :blink, :underline)

For those less squeamish about possible conflicts, the same convenience methods can be added to the built-in String class, as follows:

require 'highline'
Highline.colorize_strings

color_scheme.rb

Created by Richard LeBer on 2011-06-27. Copyright 2011. All rights reserved

This is Free Software. See LICENSE and COPYING for details

Constants

BASIC_COLORS
BLACK_STYLE

These RGB colors are approximate; see en.wikipedia.org/wiki/ANSI_escape_code

BLUE_STYLE
BOLD_STYLE
CLEAR_STYLE
COLORS
CONCEALED_STYLE
CYAN_STYLE
DARK_STYLE

for example bold black. Bold without a color displays the system-defined bold color (e.g. red on Mac iTerm)

ERASE_CHAR_STYLE
ERASE_LINE_STYLE

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

GRAY_STYLE

Alias for WHITE, since WHITE is actually a light gray on Macs

GREEN_STYLE
MAGENTA_STYLE
NONE_STYLE

On Mac OSX Terminal, this is black foreground, or bright white background. Also used as base for RGB colors, if available

RED_STYLE
RESET_STYLE
REVERSE_STYLE
STYLES
UNDERLINE_STYLE
UNDERSCORE_STYLE
VERSION

The version of the installed library.

WHITE_STYLE

On Mac OSX Terminal, white is actually gray

YELLOW_STYLE

Attributes

indent_level[RW]

The indentation level

indent_size[RW]

The indentation size

multi_indent[RW]

Indentation over multiple lines

page_at[R]

The current row setting for paging output.

wrap_at[R]

The current column setting for wrapping output.

Public Class Methods

String(s) click to toggle source
# File lib/highline/string_extensions.rb, line 27
def self.String(s)
  HighLine::String.new(s)
end
Style(*args) click to toggle source
# File lib/highline/style.rb, line 10
def self.Style(*args)
  args = args.compact.flatten
  if args.size==1
    arg = args.first
    if arg.is_a?(Style)
      Style.list[arg.name] || Style.index(arg)
    elsif arg.is_a?(::String) && arg =~ /^\e\[/ # arg is a code
      if styles = Style.code_index[arg]
        styles.first
      else
        Style.new(:code=>arg)
      end
    elsif style = Style.list[arg]
      style
    elsif HighLine.color_scheme && HighLine.color_scheme[arg]
      HighLine.color_scheme[arg]
    elsif arg.is_a?(Hash)
      Style.new(arg)
    elsif arg.to_s.downcase =~ /^rgb_([a-f0-9]{6})$/
      Style.rgb($1)
    elsif arg.to_s.downcase =~ /^on_rgb_([a-f0-9]{6})$/
      Style.rgb($1).on
    else
      raise NameError, "#{arg.inspect} is not a defined Style"
    end
  else
    name = args
    Style.list[name] || Style.new(:list=>args)
  end
end
color( string, *colors ) click to toggle source

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.

# File lib/highline.rb, line 377
def self.color( string, *colors )
  return string unless self.use_color?
  Style(*colors).color(string)
end
color_code(*colors) click to toggle source

In case you just want the color code, without the embedding and the CLEAR

# File lib/highline.rb, line 383
def self.color_code(*colors)
  Style(*colors).code
end
color_scheme() click to toggle source

Returns the current color scheme.

# File lib/highline.rb, line 80
def self.color_scheme
  @@color_scheme
end
color_scheme=( setting ) click to toggle source

Pass ColorScheme to setting to set a HighLine color scheme.

# File lib/highline.rb, line 75
def self.color_scheme=( setting )
  @@color_scheme = setting
end
colorize_strings() click to toggle source
# File lib/highline/string_extensions.rb, line 108
def self.colorize_strings
  ::String.send(:include, StringExtensions)
end
const_missing(name) click to toggle source

For RGB colors:

# File lib/highline.rb, line 148
def self.const_missing(name)
  if name.to_s =~ /^(ON_)?(RGB_)([A-F0-9]{6})(_STYLE)?$/ # RGB color
    on = $1
    suffix = $4
    if suffix
      code_name = $1.to_s + $2 + $3
    else
      code_name = name.to_s
    end
    style_name = code_name + '_STYLE'
    style = Style.rgb($3)
    style = style.on if on
    const_set(style_name, style)
    const_set(code_name, style.code)
    if suffix
      style
    else
      style.code
    end
  else
    raise NameError, "Bad color or uninitialized constant #{name}"
  end
end
new( input = $stdin, output = $stdout, wrap_at = nil, page_at = nil, indent_size=3, indent_level=0 ) click to toggle source

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

# File lib/highline.rb, line 176
def initialize( input = $stdin, output = $stdout,
                wrap_at = nil, page_at = nil, indent_size=3, indent_level=0 )
  @input   = input
  @output  = output

  @multi_indent = true
  @indent_size = indent_size
  @indent_level = indent_level

  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

  initialize_system_extensions if respond_to?(:initialize_system_extensions)
end
supports_rgb_color?() click to toggle source

For checking if the current version of HighLine supports RGB colors Usage: HighLine.supports_rgb_color? rescue false # rescue for compatibility with older versions Note: color usage also depends on HighLine.use_color being set

# File lib/highline.rb, line 54
def self.supports_rgb_color?
  true
end
track_eof=( setting ) click to toggle source

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

# File lib/highline.rb, line 62
def self.track_eof=( setting )
  @@track_eof = setting
end
track_eof?() click to toggle source

Returns true if HighLine is currently tracking EOF for input.

# File lib/highline.rb, line 67
def self.track_eof?
  @@track_eof
end
uncolor(string) click to toggle source

Remove color codes from a string

# File lib/highline.rb, line 398
def self.uncolor(string)
  Style.uncolor(string)
end
use_color=( setting ) click to toggle source

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

# File lib/highline.rb, line 42
def self.use_color=( setting )
  @@use_color = setting
end
use_color?() click to toggle source

Returns true if HighLine is currently using color escapes.

# File lib/highline.rb, line 47
def self.use_color?
  @@use_color
end
using_color_scheme?() click to toggle source

Returns true if HighLine is currently using a color scheme.

# File lib/highline.rb, line 85
def self.using_color_scheme?
  not @@color_scheme.nil?
end

Public Instance Methods

agree( yes_or_no_question, character = nil ) { |q| ... } click to toggle source

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.

# File lib/highline.rb, line 222
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 ) { |question| ... } click to toggle source

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.

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.

# File lib/highline.rb, line 247
def ask( question, answer_type = String, &details ) # :yields: question
  @question ||= Question.new(question, answer_type, &details)

  return gather if @question.gather

  # readline() needs to handle its 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.
  # Also, JRuby-1.7's ConsoleReader.readLine() needs to be passed the prompt
  # to handle line editing properly.
  say(@question) unless ((JRUBY or @question.readline) and @question.echo == true)

  begin
    @answer = @question.answer_or_default(get_response)
    unless @question.valid_answer?(@answer)
      explain_error(:not_valid)
      raise QuestionError
    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, @indent_size, @indent_level)
        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
      explain_error(:not_in_range)
      raise QuestionError
    end
  rescue QuestionError
    retry
  rescue ArgumentError, NameError => error
    raise if error.is_a?(NoMethodError)
    if error.message =~ /ambiguous/
      # the assumption here is that OptionParser::Completion#complete
      # (used for ambiguity resolution) throws exceptions containing
      # the word 'ambiguous' whenever resolution fails
      explain_error(:ambiguous_completion)
    else
      explain_error(:invalid_type)
    end
    retry
  rescue Question::NoAutoCompleteMatch
    explain_error(:no_completion)
    retry
  ensure
    @question = nil    # Reset Question object.
  end
end
choose( *items, &details ) click to toggle source

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 among 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.

# File lib/highline.rb, line 328
def choose( *items, &details )
  @menu = @question = Menu.new(&details)
  @menu.choices(*items) unless items.empty?

  # Set auto-completion
  @menu.completion = @menu.options
  # 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(*args) click to toggle source

Works as an instance method, same as the class method

# File lib/highline.rb, line 393
def color(*args)
  self.class.color(*args)
end
color_code(*colors) click to toggle source

Works as an instance method, same as the class method

# File lib/highline.rb, line 388
def color_code(*colors)
  self.class.color_code(*colors)
end
indent(increase=1, statement=nil, multiline=nil) { |self| ... } click to toggle source

Executes block or outputs statement with indentation

# File lib/highline.rb, line 660
def indent(increase=1, statement=nil, multiline=nil)
  @indent_level += increase
  multi = @multi_indent
  @multi_indent = multiline unless multiline.nil?
  begin
      if block_given?
          yield self
      else
          say(statement)
      end
  rescue
      @multi_indent = multi
      @indent_level -= increase
      raise
  end
  @multi_indent = multi
  @indent_level -= increase
end
indentation() click to toggle source

Outputs indentation with current settings

# File lib/highline.rb, line 653
def indentation
  return ' '*@indent_size*@indent_level
end
list( items, mode = :rows, option = nil ) click to toggle source

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.

:uneven_columns_across

Like :columns_across but each column is sized independently.

:uneven_columns_down

Like :columns_down but each column is sized independently.

: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 its 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.

# File lib/highline.rb, line 440
def list( items, mode = :rows, option = nil )
  items = items.to_ary.map do |item|
    if item.nil?
      ""
    else
      ERB.new(item, nil, "%").result(binding)
    end
  end

  if items.empty?
    ""
  else
    case mode
    when :inline
      option = " or " if option.nil?

      if items.size == 1
        items.first
      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.to_s.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
    when :uneven_columns_across
      if option.nil?
        limit = @wrap_at || 80
        items.size.downto(1) do |column_count|
          row_count = (items.size / column_count.to_f).ceil
          rows      = Array.new(row_count) { Array.new }
          items.each_with_index do |item, index|
            rows[index / column_count] << item
          end

          widths = Array.new(column_count, 0)
          rows.each do |row|
            row.each_with_index do |field, column|
              size           = actual_length(field)
              widths[column] = size if size > widths[column]
            end
          end

          if column_count == 1 or
             widths.inject(0) { |sum, n| sum + n + 2 } <= limit + 2
            return rows.map { |row|
              row.zip(widths).map { |field, i|
                "%-#{i + (field.to_s.length - actual_length(field))}s" % field
              }.join("  ") + "\n"
            }.join
          end
        end
      else
        row_count = (items.size / option.to_f).ceil
        rows      = Array.new(row_count) { Array.new }
        items.each_with_index do |item, index|
          rows[index / option] << item
        end

        widths = Array.new(option, 0)
        rows.each do |row|
          row.each_with_index do |field, column|
            size           = actual_length(field)
            widths[column] = size if size > widths[column]
          end
        end

        return rows.map { |row|
          row.zip(widths).map { |field, i|
            "%-#{i + (field.to_s.length - actual_length(field))}s" % field
          }.join("  ") + "\n"
        }.join
      end
    when :uneven_columns_down
      if option.nil?
        limit = @wrap_at || 80
        items.size.downto(1) do |column_count|
          row_count = (items.size / column_count.to_f).ceil
          columns   = Array.new(column_count) { Array.new }
          items.each_with_index do |item, index|
            columns[index / row_count] << item
          end

          widths = Array.new(column_count, 0)
          columns.each_with_index do |column, i|
            column.each do |field|
              size      = actual_length(field)
              widths[i] = size if size > widths[i]
            end
          end

          if column_count == 1 or
             widths.inject(0) { |sum, n| sum + n + 2 } <= limit + 2
            list = ""
            columns.first.size.times do |index|
              list << columns.zip(widths).map { |column, width|
                field = column[index]
                "%-#{width + (field.to_s.length - actual_length(field))}s" %
                field
              }.compact.join("  ").strip + "\n"
            end
            return list
          end
        end
      else
        row_count = (items.size / option.to_f).ceil
        columns   = Array.new(option) { Array.new }
        items.each_with_index do |item, index|
          columns[index / row_count] << item
        end

        widths = Array.new(option, 0)
        columns.each_with_index do |column, i|
          column.each do |field|
            size      = actual_length(field)
            widths[i] = size if size > widths[i]
          end
        end

        list = ""
        columns.first.size.times do |index|
          list << columns.zip(widths).map { |column, width|
            field = column[index]
            "%-#{width + (field.to_s.length - actual_length(field))}s" % field
          }.compact.join("  ").strip + "\n"
        end
        return list
      end
    else
      items.map { |i| "#{i}\n" }.join
    end
  end
end
newline() click to toggle source

Outputs newline

# File lib/highline.rb, line 682
def newline
  @output.puts
end
output_cols() click to toggle source

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

# File lib/highline.rb, line 690
def output_cols
  return 80 unless @output.tty?
  terminal_size.first
rescue
  return 80
end
output_rows() click to toggle source

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

# File lib/highline.rb, line 701
def output_rows
  return 24 unless @output.tty?
  terminal_size.last
rescue
  return 24
end
page_at=( setting ) click to toggle source

Set to an integer value to cause HighLine to page output lines over the indicated line limit. When nil, the default, no paging occurs. If set to :auto, HighLine will attempt to determine the rows available for the @output or use a sensible default.

# File lib/highline.rb, line 646
def page_at=( setting )
  @page_at = setting == :auto ? output_rows - 2 : setting
end
say( statement ) click to toggle source

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.

# File lib/highline.rb, line 616
def say( statement )
  statement = format_statement(statement)
  return unless statement.length > 0

    # Don't add a newline if statement ends with whitespace, OR
  # if statement ends with whitespace before a color escape code.
  if /[ \t](\e\[\d+(;\d+)*m)?\Z/ =~ statement
    @output.print(indentation+statement)
    @output.flush
  else
    @output.puts(indentation+statement)
  end
end
uncolor(string) click to toggle source

Works as an instance method, same as the class method

# File lib/highline.rb, line 403
def uncolor(string)
  self.class.uncolor(string)
end
wrap_at=( setting ) click to toggle source

Set to an integer value to cause HighLine to wrap output lines at the indicated character limit. When nil, the default, no wrapping occurs. If set to :auto, HighLine will attempt to determine the columns available for the @output or use a sensible default.

# File lib/highline.rb, line 636
def wrap_at=( setting )
  @wrap_at = setting == :auto ? output_cols : setting
end

Private Instance Methods

actual_length( string_with_escapes ) click to toggle source

Returns the length of the passed string_with_escapes, minus and color sequence escapes.

# File lib/highline.rb, line 1029
def actual_length( string_with_escapes )
  string_with_escapes.to_s.gsub(/\e\[\d{1,2}m/, "").length
end
continue_paging?() click to toggle source

Ask user if they wish to continue paging output. Allows them to type “q” to cancel the paging process.

# File lib/highline.rb, line 992
def continue_paging?
  command = HighLine.new(@input, @output).ask(
    "-- press enter/return to continue or q to stop -- "
  ) { |q| q.character = true }
  command !~ /\A[qQ]\Z/  # Only continue paging if Q was not hit.
end
explain_error( error ) click to toggle source

A helper method for sending the output stream and error and repeat of the question.

# File lib/highline.rb, line 733
def explain_error( error )
  say(@question.responses[error]) unless error.nil?
  if @question.responses[:ask_on_error] == :question
    say(@question)
  elsif @question.responses[:ask_on_error]
    say(@question.responses[:ask_on_error])
  end
end
format_statement(statement) click to toggle source
# File lib/highline.rb, line 710
def format_statement statement
  statement = statement.dup.to_str
  return statement unless statement.length > 0

# Allow non-ascii menu prompts in ruby > 1.9.2. ERB eval the menu statement
  # with the environment's default encoding(usually utf8)
  statement.force_encoding(Encoding.default_external) if defined?(Encoding) && Encoding.default_external

  template  = ERB.new(statement, nil, "%")
  statement = template.result(binding)

  statement = wrap(statement) unless @wrap_at.nil?
  statement = page_print(statement) unless @page_at.nil?

  statement = statement.gsub(/\n(?!$)/,"\n#{indentation}") if @multi_indent

  statement
end
gather( ) click to toggle source

Collects an Array/Hash full of answers as described in HighLine::Question#gather.

Raises EOFError if input is exhausted.

# File lib/highline.rb, line 748
def gather(  )
  original_question = @question
  original_question_string = @question.question
  original_gather = @question.gather

  verify_match = @question.verify_match
  @question.gather = false

  begin   # when verify_match is set this loop will repeat until unique_answers == 1
    @answers          = [ ]
    @gather = original_gather
    original_question.question = original_question_string

    case @gather
    when Integer
      @answers << ask(@question)
      @gather  -= 1

      original_question.question = ""
      until @gather.zero?
        @question =  original_question
        @answers  << ask(@question)
        @gather   -= 1
      end
    when ::String, Regexp
      @answers << ask(@question)

      original_question.question = ""
      until (@gather.is_a?(::String) and @answers.last.to_s == @gather) or
          (@gather.is_a?(Regexp) and @answers.last.to_s =~ @gather)
        @question =  original_question
        @answers  << ask(@question)
      end

      @answers.pop
    when Hash
      @answers = { }
      @gather.keys.sort.each do |key|
        @question     = original_question
        @key          = key
        @answers[key] = ask(@question)
      end
    end

    if verify_match && (unique_answers(@answers).size > 1)
      @question =  original_question
      explain_error(:mismatch)
    else
      verify_match = false
    end

  end while verify_match

  original_question.verify_match ? @answer : @answers
end
get_line( ) click to toggle source

Read a line of input from the input stream and process whitespace as requested by the Question object.

If Question's readline property is set, that library will be used to fetch input. WARNING: This ignores the currently set input stream.

Raises EOFError if input is exhausted.

# File lib/highline.rb, line 822
def get_line(  )
  if @question.readline
    require "readline"    # load only if needed

    # capture say()'s work in a String to feed to readline()
    old_output = @output
    @output    = StringIO.new
    say(@question)
    question = @output.string
    @output  = old_output

    # prep auto-completion
    Readline.completion_proc = lambda do |string|
      @question.selection.grep(/\A#{Regexp.escape(string)}/)
    end

    # work-around ugly readline() warnings
    old_verbose = $VERBOSE
    $VERBOSE    = nil
    raw_answer  = Readline.readline(question, true)
    if raw_answer.nil?
      if @@track_eof
        raise EOFError, "The input stream is exhausted."
      else
        raw_answer = String.new # Never return nil
      end
    end
    answer      = @question.change_case(
                      @question.remove_whitespace(raw_answer))
    $VERBOSE    = old_verbose

    answer
  else
    if JRUBY
      statement = format_statement(@question)
      raw_answer = @java_console.readLine(statement, nil)

      raise EOFError, "The input stream is exhausted." if raw_answer.nil? and
                                                          @@track_eof
    else
      raise EOFError, "The input stream is exhausted." if @@track_eof and
                                                          @input.eof?
      raw_answer = @input.gets
    end

    @question.change_case(@question.remove_whitespace(raw_answer))
  end
end
get_response( ) click to toggle source

Return a line or character of input, as requested for this question. Character input will be returned as a single character String, not an Integer.

This question's first_answer will be returned instead of input, if set.

Raises EOFError if input is exhausted.

# File lib/highline.rb, line 880
def get_response(  )
  return @question.first_answer if @question.first_answer?

  if @question.character.nil?
    if @question.echo == true and @question.limit.nil?
      get_line
    else
      raw_no_echo_mode

      line            = ""
      backspace_limit = 0
      begin

        while character = get_character(@input)
          # honor backspace and delete
          if character == 127 or character == 8
            line.slice!(-1, 1)
            backspace_limit -= 1
          else
            line << character.chr
            backspace_limit = line.size
          end
          # looking for carriage return (decimal 13) or
          # newline (decimal 10) in raw input
          break if character == 13 or character == 10
          if @question.echo != false
            if character == 127 or character == 8
              # only backspace if we have characters on the line to
              # eliminate, otherwise we'll tromp over the prompt
              if backspace_limit >= 0 then
                @output.print("\b#{HighLine.Style(:erase_char).code}")
              else
                  # do nothing
              end
            else
              if @question.echo == true
                @output.print(character.chr)
              else
                @output.print(@question.echo)
              end
            end
            @output.flush
          end
          break if @question.limit and line.size == @question.limit
        end
      ensure
        restore_mode
      end
      if @question.overwrite
        @output.print("\r#{HighLine.Style(:erase_line).code}")
        @output.flush
      else
        say("\n")
      end

      @question.change_case(@question.remove_whitespace(line))
    end
  else
    if JRUBY #prompt has not been shown
      say @question
    end

    raw_no_echo_mode
    begin
      if @question.character == :getc
        response = @input.getbyte.chr
      else
        response = get_character(@input).chr
        if @question.overwrite
          @output.print("\r#{HighLine.Style(:erase_line).code}")
          @output.flush
        else
          echo = if @question.echo == true
            response
          elsif @question.echo != false
            @question.echo
          else
            ""
          end
          say("#{echo}\n")
        end
      end
    ensure
      restore_mode
    end
    @question.change_case(response)
  end
end
page_print( output ) click to toggle source

Page print a series of at most page_at lines for output. After each page is printed, HighLine will pause until the user presses enter/return then display the next page of data.

Note that the final page of output is not printed, but returned instead. This is to support any special handling for the final sequence.

# File lib/highline.rb, line 977
def page_print( output )
  lines = output.scan(/[^\n]*\n?/)
  while lines.size > @page_at
    @output.puts lines.slice!(0...@page_at).join
    @output.puts
    # Return last line if user wants to abort paging
    return (["...\n"] + lines.slice(-2,1)).join unless continue_paging?
  end
  return lines.join
end
unique_answers(list = @answers) click to toggle source

A helper method used by HighLine::Question#verify_match for finding whether a list of answers match or differ from each other.

# File lib/highline.rb, line 809
def unique_answers(list = @answers)
  (list.respond_to?(:values) ? list.values : list).uniq
end
wrap( text ) click to toggle source

Wrap a sequence of lines at wrap_at characters per line. Existing newlines will not be affected by this process, but additional newlines may be added.

# File lib/highline.rb, line 1004
def wrap( text )
  wrapped = [ ]
  text.each_line do |line|
    # take into account color escape sequences when wrapping
    wrap_at = @wrap_at + (line.length - actual_length(line))
    while line =~ /([^\n]{#{wrap_at + 1},})/
      search  = $1.dup
      replace = $1.dup
      if index = replace.rindex(" ", wrap_at)
        replace[index, 1] = "\n"
        replace.sub!(/\n[ \t]+/, "\n")
        line.sub!(search, replace)
      else
        line[$~.begin(1) + wrap_at, 0] = "\n"
      end
    end
    wrapped << line
  end
  return wrapped.join
end