Class: HighLine
- 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, Menu, Question, QuestionError, SampleColorScheme
Constant Summary collapse
- VERSION =
The version of the installed library.
"1.2.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
- BLINK =
The start of an ANSI blink sequence. (Terminal support uncommon.)
"\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
-
#page_at ⇒ Object
The current row setting for paging output.
-
#wrap_at ⇒ Object
The current column setting for wrapping output.
Class Method Summary collapse
-
.color_scheme ⇒ Object
Returns the current color scheme.
-
.color_scheme=(setting) ⇒ Object
Pass ColorScheme to setting to turn set a HighLine color scheme.
-
.track_eof=(setting) ⇒ Object
Pass
false
to setting to turn off HighLine’s EOF tracking. -
.track_eof? ⇒ Boolean
Returns true if HighLine is currently tracking EOF for input.
-
.use_color=(setting) ⇒ Object
Pass
false
to setting to turn off HighLine’s color escapes. -
.use_color? ⇒ Boolean
Returns true if HighLine is currently using color escapes.
-
.using_color_scheme? ⇒ Boolean
Returns
true
if HighLine is currently using a color scheme.
Instance Method Summary collapse
-
#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
orfalse
(true
for “yes”). -
#ask(question, answer_type = String, &details) ⇒ Object
This method is the primary interface for user input.
-
#choose(*items, &details) ⇒ Object
This method is HighLine’s menu handler.
-
#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.
-
#initialize(input = $stdin, output = $stdout, wrap_at = nil, page_at = nil) ⇒ HighLine
constructor
Create an instance of HighLine, connected to the streams input and output.
-
#list(items, mode = :rows, option = nil) ⇒ Object
This method is a utility for quickly and easily laying out lists.
-
#output_cols ⇒ Object
Returns the number of columns for the console, or a default it they cannot be determined.
-
#output_rows ⇒ Object
Returns the number of rows for the console, or a default if they cannot be determined.
-
#say(statement) ⇒ Object
The basic output method for HighLine objects.
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.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'lib/highline.rb', line 147 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_at ⇒ Object
The current row setting for paging output.
170 171 172 |
# File 'lib/highline.rb', line 170 def page_at @page_at end |
#wrap_at ⇒ Object
The current column setting for wrapping output.
168 169 170 |
# File 'lib/highline.rb', line 168 def wrap_at @wrap_at end |
Class Method Details
.color_scheme ⇒ Object
Returns the current color scheme.
74 75 76 |
# File 'lib/highline.rb', line 74 def self.color_scheme @@color_scheme end |
.color_scheme=(setting) ⇒ Object
Pass ColorScheme to setting to turn set a HighLine color scheme.
69 70 71 |
# File 'lib/highline.rb', line 69 def self.color_scheme=( setting ) @@color_scheme = setting end |
.track_eof=(setting) ⇒ Object
Pass false
to setting to turn off HighLine’s EOF tracking.
56 57 58 |
# File 'lib/highline.rb', line 56 def self.track_eof=( setting ) @@track_eof = setting end |
.track_eof? ⇒ Boolean
Returns true if HighLine is currently tracking EOF for input.
61 62 63 |
# File 'lib/highline.rb', line 61 def self.track_eof? @@track_eof end |
.use_color=(setting) ⇒ Object
Pass false
to setting to turn off HighLine’s color escapes.
43 44 45 |
# File 'lib/highline.rb', line 43 def self.use_color=( setting ) @@use_color = setting end |
.use_color? ⇒ Boolean
Returns true if HighLine is currently using color escapes.
48 49 50 |
# File 'lib/highline.rb', line 48 def self.use_color? @@use_color end |
.using_color_scheme? ⇒ Boolean
Returns true
if HighLine is currently using a color scheme.
79 80 81 |
# File 'lib/highline.rb', line 79 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.
Raises EOFError if input is exhausted.
180 181 182 183 184 185 186 187 |
# File 'lib/highline.rb', line 180 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 end end |
#ask(question, answer_type = String, &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.
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.
203 204 205 206 207 208 209 210 211 212 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 |
# File 'lib/highline.rb', line 203 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 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) 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) 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 explain_error(:invalid_type) retry rescue Question::NoAutoCompleteMatch explain_error(:no_completion) retry rescue NameError raise if $!.is_a?(NoMethodError) explain_error(:ambiguous_completion) 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.
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/highline.rb', line 277 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 || "" = @menu. .extend(OptionParser::Completion) answer = .complete(first_word) if answer.nil? raise Question::NoAutoCompleteMatch end [answer.last, command.sub(/^\s*#{first_word}\s*/, "")] end else @menu. # 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
.
324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'lib/highline.rb', line 324 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.
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 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 |
# File 'lib/highline.rb', line 367 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_cols ⇒ Object
Returns the number of columns for the console, or a default it they cannot be determined.
479 480 481 482 483 484 |
# File 'lib/highline.rb', line 479 def output_cols return 80 unless @output.tty? terminal_size.first rescue return 80 end |
#output_rows ⇒ Object
Returns the number of rows for the console, or a default if they cannot be determined.
490 491 492 493 494 495 |
# File 'lib/highline.rb', line 490 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.
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
# File 'lib/highline.rb', line 437 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 |