ansi-1.5.0/0000755000004100000410000000000012465501305012500 5ustar www-datawww-dataansi-1.5.0/HISTORY.md0000644000004100000410000001444712465501305014175 0ustar www-datawww-data# RELEASE HISTORY ## 1.5.0 | 2015-01-16 ANSI 1.5 introduces one change that is not backward compatiable. The `:clear_line` code no longer clears to the end of the line. Instead it clears the entire line. If you have used this in the past you will need to update your code to use `:clear_eol` or `:clear_right` instead. In addition this release finally fixes some long time issues with Windows compatability, and a few other bugs. Yeah! Changes: * Alias `:right` and `:left` as `:forward` and `:back` respectively. * Change `:clear_line` to clear whole line, not just to the end of line. * Add `:cursor_hide` and `:cursor_show` codes. * Fix and adjust #rgb method to work as one would expect. * Fix Windows compatability (old code was alwasy using stty). * Fix duplicated hash key in chart.rb. ## 1.4.3 | 2012-06-26 This release bring two small changes. The first improves support for Windows by only rescuing LoadError when 'win32console' fails to load. The second improves the heuritstics used for determining the current terminal screen width. Changes: * Only rescue LoadError on windows require. (#9) [bug] * Improvements for getting proper screen width. ## 1.4.2 | 2012-01-29 ANSI chains are a new feature inspired by Kazuyoshi Tlacaelel's Isna project. It is a fluid notation for the String#ansi method, e.g. `"foo".red.on_white`. Also, ASNI now supports "smart codes", preventing previously applied codes from undermining the applicaiton of additional codes --a subtle issue that most other ANSI libraries overlook. Plus a few other improvements including that of the API documentation. Changes: * Add ANSI::Chains, extending String#ansi method. * Support smart code application. * Add Diff#to_a and shortcut to it via Diff.diff(). * Improve #colorize method in ProgressBar. * Change ProgressBar's default mark to `|` instead of `o`. * Fix Curses return order of screen cols and rows. * Support center alignment in Columns. * Support custom padding for Columns. ## 1.4.1 | 2011-11-09 This release simply fixes a documentation issue, to make sure QED.rdoc appears in the YARD docs. And a shout-out to Chad Perrin for submitting some doc fixes for this project and a few other Rubyworks projects. Changes: * Adjust .yardopts file. * Documentation fixes. ## 1.4.0 | 2011-11-05 New release adds a HexDump class for colorized byte string dumps and fixes some minor cell size issues with the Table class. This release also modernizes the build config and changes the license to BSD-2-Clause. Changes: * Add HexDump class. * Fix cell size of tables when ANSI codes are used. * Fix extra ansi codes in tables without format. * Modernize build configuration. * Switch to BSD-2-Clause license. ## 1.3.0 | 2011-06-30 This release cleans up the Code module. It adds support for x-term 256 color codes. Also, the Diff class is now awesome, making use of an LCS algorithm. But the most important difference with this release is that the String core extensions are in their own file, core.rb. If you want to use them you will need to require `ansi` or `ansi/core`. Changes: * Clean-up Code module. * Utilize common chart for Code methods. * Constants now have their own module. * Move core methods to `ansi/core.rb`. * Add XTerm 256 color code support. * Improved Diff class with LCS algorithm. ## 1.2.5 | 2011-05-03 This release introduces a preliminary rendition of a Diff class for getting colorized comparisons of strings and other objects. It's not officially supported yet, so this is only a point release. Changes: * Added Diff class for colorized comparisons. * Fixed minor issue with Columns format block; col comes before row. ## 1.2.4 | 2011-04-29 This release improves to the ANSI::Columns class. In particular the layout is more consistent with intended functionality. Changes: * Improved ANSI::Columns to give more consistent output. * ANSI::Columns#to_s can override number of columns. * ANSI::Columns can take a String or Array list. ## 1.2.3 | 2011-04-08 Minor release to add #clear method to ProgressBar and provide bug fix to BBCode.ansi_to_bbcode. Big thanks goes to Junegunn Choi for this fix. Changes: * Add ProgressBar#clear method. * Fixed ANSI::BBCode.ansi_to_bbcode and ansi_to_html from omitting lines without any ansi code (Junegunn Choi). ## 1.2.2 | 2010-06-12 This release removes warnings about string arguments for certain ANSI::Code methods. While the string form is considered deprecated, for a few methods there is no use for any argument, so the string form can remain. In addition, String#unansi has been added to compliment String#ansi. Lastly, this release also adds the #display method to ANSI::Mixin. Changes: * Remove string argument warnings. * Add String#unansi and String#unansi! * Add ANSI::Mixin#display. ## 1.2.1 | 2010-05-10 This release was simply a quick fix to remove the incorrect embedded version number, until it gets fixed. ## 1.2.0 | 2010-05-10 This release entails numerous improvements. First and foremost the Code module is transitioning to a block interface only and phasing out the string argument interface. Admittedly this is mildly unconventional, but it allows the arguments to be used as options with common defaults more elegantly. Another important change is that ANSI::Code no longer provides String extension methods when included. For this use the new ANSI::Mixin. Other improvements include a String extension, #ansi, added to code.rb, which makes it even easier to apply ANSI codes to strings. Also, the ANSI::String class has been fixed (a few bugs crept it with the last release) and continues to improve. On top of all this testing has substantially improved thanks to QED. Changes: * Support string argument for now but with warning * Bug fixes for ANSI::String * Add mixin.rb for alternate mixin. * Many new tests and QED documents. ## 1.1.0 | 2009-10-04 This release is the first toward making the ANSI library more widely usable. Changes: * Add bbcode.rb for conversion between BBCode/ANSI/HTML. * ProgressBar and Progressbar are the same. * Other minor underthehood improvements. ## 1.0.1 | 2009-08-15 The release fixes a single bug that should allow Ruby 1.9 to use the ANSI library. Changes: * Renamed PLATFORM to RUBY_PLATFORM ## 1.0.0 | 2009-08-15 This is the initial stand-alone release of ANSI, a collection of ANSI based classes spun-off from Ruby Facets. Changes: * Happy Birthday! ansi-1.5.0/.index0000644000004100000410000000276712465501305013624 0ustar www-datawww-data--- revision: 2013 type: ruby sources: - INDEX.yml authors: - name: Thomas Sawyer email: transfire@gmail.com - name: Florian Frank organizations: [] requirements: - groups: - build development: true name: mast - groups: - build development: true name: indexer - groups: - build development: true name: ergo - groups: - test development: true name: qed - groups: - test development: true name: ae - groups: - test development: true name: lemon conflicts: [] alternatives: [] resources: - type: home uri: http://rubyworks.github.com/ansi label: Homepage - type: docs uri: http://rubydoc.info/gems/ansi/frames label: Documentation - type: code uri: http://github.com/rubyworks/ansi label: Source Code - type: bugs uri: http://github.com/rubyworks/ansi/issues label: Issue Tracker - type: mail uri: http://groups.google.com/group/rubyworks-mailinglist label: Mailing List repositories: - name: upstream scm: git uri: git://github.com/rubyworks/ansi.git categories: [] copyrights: - holder: Rubyworks year: '2009' license: BSD-2-Clause customs: [] paths: lib: - lib name: ansi title: ANSI version: 1.5.0 summary: ANSI at your fingertips! description: The ANSI project is a superlative collection of ANSI escape code related libraries eabling ANSI colorization and stylization of console output. Byte for byte ANSI is the best ANSI code library available for the Ruby programming language. orgranizations: - Rubyworks created: '2009-08-01' date: '2015-01-16' ansi-1.5.0/demo/0000755000004100000410000000000012465501305013424 5ustar www-datawww-dataansi-1.5.0/demo/08_table.md0000644000004100000410000000070312465501305015344 0ustar www-datawww-data# ANSI::Table The ANSI::Table class can be used to output tabular data with nicely formated ASCII cell borders. require 'ansi/table' The constructor takes an 2-dimensional array. data = [ [ 10, 20, 30 ], [ 20, 10, 20 ], [ 50, 40, 20 ] ] table = ANSI::Table.new(data) table.to_s The output will be: +----+----+----+ | 10 | 20 | 30 | | 20 | 10 | 20 | | 50 | 40 | 20 | +----+----+----+ ansi-1.5.0/demo/09_diff.md0000644000004100000410000000156412465501305015174 0ustar www-datawww-data# ANSI::Diff require 'ansi/diff' a = 'abcYefg' b = 'abcXefg' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mYefg\e[0m\n\e[31mabc\e[0mXefg" Try another. a = 'abc' b = 'abcdef' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\n\e[31mabc\e[0mdef" And another. a = 'abcXXXghi' b = 'abcdefghi' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mXXXghi\e[0m\n\e[31mabc\e[0mdefghi" And another. a = 'abcXXXdefghi' b = 'abcdefghi' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mXXX\e[0m\e[35mdefghi\e[0m\n\e[31mabc\e[0m\e[35mdefghi\e[0m" Comparison that is mostly different. a = 'abcpppz123' b = 'abcxyzzz43' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mpppz123\e[0m\n\e[31mabc\e[0mxyzzz43" ansi-1.5.0/demo/04_progressbar.md0000644000004100000410000000306012465501305016601 0ustar www-datawww-data# ANSI::Progressbar Pretty progress bars are easy to construct. require 'ansi/progressbar' pbar = ANSI::Progressbar.new("Test Bar", 100) Running the bar simply requires calling the #inc method during a loop and calling `#finish` when done. 100.times do |i| sleep 0.01 pbar.inc end pbar.finish We will use this same rountine in all the examples below, so lets make a quick macro for it. Notice we have to use `#reset` first before reusing the same progress bar. def run(pbar) pbar.reset 100.times do |i| sleep 0.01 pbar.inc end pbar.finish puts end The progress bar can be stylized in almost any way. The `#format` setter provides control over the parts that appear on the line. For example, by default the format is: pbar.format("%-14s %3d%% %s %s", :title, :percentage, :bar, :stat) So lets vary it up to demonstrate the case. pbar.format("%-14s %3d%% %s %s", :title, :percentage, :stat, :bar) run(pbar) The progress bar has an extra build in format intended for use with file downloads called `#transer_mode`. pbar.transfer_mode run(pbar) Calling this methods is the same as calling: pbar.format("%-14s %3d%% %s %s",:title, :percentage, :bar, :stat_for_file_transfer) run(pbar) The `#style` setter allows each part of the line be modified with ANSI codes. And the `#bar_mark` writer can be used to change the character used to make the bar. pbar.standard_mode pbar.style(:title => [:red], :bar=>[:blue]) pbar.bar_mark = "=" run(pbar) ansi-1.5.0/demo/07_columns.md0000644000004100000410000000356612465501305015746 0ustar www-datawww-data# ANSI::Columns The +Columns+ class makes it easy to create nice looking text columns, sorted from top to bottom, right to left (as opposed to the other way around). require 'ansi/columns' list = %w{a b c d e f g h i j k l} columns = ANSI::Columns.new(list) columns.to_s(4) The output will be: a d g j b e h k c f i l Besides an array of elements, Columns.new can take a string in which the elements are divided by newlines characters. The default column size can also be given to the initializer. list = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl" columns = ANSI::Columns.new(list, :columns=>6) columns.to_s The output will be: a c e g i k b d f h j l If the column count is +nil+, then the number of columns will be calculated as a best fit for the current terminal window. ## Padding Columns can adjust the padding between cells. list = %w{a b c d e f g h i j k l} columns = ANSI::Columns.new(list, :padding=>2) columns.to_s(4) The output will be: a d g j b e h k c f i l ## Alignment Columns can also be aligned either left or right. list = %w{xx xx xx yy y yy z zz z} columns = ANSI::Columns.new(list, :align=>:right) columns.to_s(3) The output will be: xx yy z xx y zz xx yy z ## Format Lastly, columns can be augmented with ANSI codes. This is done through a formatting block. The block can take up to three parameters, the cell content, the column and row numbers, or the cell and the column and row numbers. list = %w{a b c d e f g h i j k l} columns = ANSI::Columns.new(list){ |c,r| r % 2 == 0 ? :red : :blue } out = columns.to_s(4) out.assert == ( "\e[31ma \e[0m\e[31md \e[0m\e[31mg \e[0m\e[31mj \e[0m\n" + "\e[34mb \e[0m\e[34me \e[0m\e[34mh \e[0m\e[34mk \e[0m\n" + "\e[31mc \e[0m\e[31mf \e[0m\e[31mi \e[0m\e[31ml \e[0m\n" ) ansi-1.5.0/demo/02_core.md0000644000004100000410000000047612465501305015206 0ustar www-datawww-data# String Extensions In addition the library offers an extension to String class called #ansi, which allows some of the ANSI::Code methods to be called in a more object-oriented fashion. require 'ansi/core' str = "Hello".ansi(:red) + "World".ansi(:blue) str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" ansi-1.5.0/demo/05_mixin.md0000644000004100000410000000153112465501305015376 0ustar www-datawww-data# ANSI::Mixin The ANSI::Mixin module is design for including into String-like classes. It will support any class that defines a #to_s method. require 'ansi/mixin' In this demonstration we will simply include it in the core String class. class ::String include ANSI::Mixin end Now all strings will have access to ANSI's style and color codes via simple method calls. "roses".red.assert == "\e[31mroses\e[0m" "violets".blue.assert == "\e[34mviolets\e[0m" "sugar".italic.assert == "\e[3msugar\e[0m" The method can be combined, of course. "you".italic.bold.assert == "\e[1m\e[3myou\e[0m\e[0m" The mixin also supports background methods. "envy".on_green.assert == "\e[42menvy\e[0m" And it also supports the combined foreground-on-background methods. "b&w".white_on_black.assert == "\e[37m\e[40mb&w\e[0m" ansi-1.5.0/demo/applique/0000755000004100000410000000000012465501305015244 5ustar www-datawww-dataansi-1.5.0/demo/applique/ae.rb0000644000004100000410000000001512465501305016152 0ustar www-datawww-datarequire 'ae' ansi-1.5.0/demo/applique/output.rb0000644000004100000410000000015212465501305017127 0ustar www-datawww-dataWhen "output will be" do |text| # how to get result of last block? @_.strip.assert == text.strip end ansi-1.5.0/demo/06_string.md0000644000004100000410000000307612465501305015567 0ustar www-datawww-data# ANSI::String The ANSI::String class is a very sophisticated implementation of Ruby's standard String class, but one that can handle ANSI codes seamlessly. require 'ansi/string' flower1 = ANSI::String.new("Roses") flower2 = ANSI::String.new("Violets") Like any other string. flower1.to_s.assert == "Roses" flower2.to_s.assert == "Violets" Bet now we can add color. flower1.red! flower2.blue! flower1.to_s.assert == "\e[31mRoses\e[0m" flower2.to_s.assert == "\e[34mViolets\e[0m" Despite that the string representation now contains ANSI codes, we can still manipulate the string in much the same way that we manipulate an ordinary string. flower1.size.assert == 5 flower2.size.assert == 7 Like ordinary strings we can concatenate the two strings flowers = flower1 + ' ' + flower2 flowers.to_s.assert == "\e[31mRoses\e[0m \e[34mViolets\e[0m" flowers.size.assert == 13 Standard case conversion such as #upcase and #downcase work. flower1.upcase.to_s.assert == "\e[31mROSES\e[0m" flower1.downcase.to_s.assert == "\e[31mroses\e[0m" Some of the most difficult methods to re-implement were the substitution methods such as #sub and #gsub. They are still somewhat more limited than the original string methods, but their primary functionality should work. flower1.gsub('s', 'z').to_s.assert == "\e[31mRozez\e[0m" There are still a number of methods that need implementation. ANSI::String is currently a very partial implementation. But as you can see from the methods it does currently support, is it already useful. ansi-1.5.0/demo/10_bbcode.md0000644000004100000410000000125112465501305015463 0ustar www-datawww-data# ANSI::BBCode The BBCode module provides methods for converting between BBCodes, basic HTML and ANSI codes. require 'ansi/bbcode' BBCodes are color and style codes in square brackets, quite popular with on line forums. bbcode = "this is [COLOR=red]red[/COLOR], this is [B]bold[/B]" We can convert this to ANSI code simply enough: ansi = ANSI::BBCode.bbcode_to_ansi(bbcode) ansi.assert == "this is \e[0;31mred\e[0m, this is \e[1mbold\e[0m\n" In addition the BBCode module supports conversion to simple HTML. html = ANSI::BBCode.bbcode_to_html(bbcode) html.assert == "this is red, this is bold
\n" ansi-1.5.0/demo/01_ansicode.md0000644000004100000410000000344212465501305016036 0ustar www-datawww-data# ANSI::Code Require the library. require 'ansi/code' ANSI::Code can be used as a functions module. str = ANSI::Code.red + "Hello" + ANSI::Code.blue + "World" str.assert == "\e[31mHello\e[34mWorld" If a block is supplied to each method then yielded value will be wrapped in the ANSI code and clear code. str = ANSI::Code.red{ "Hello" } + ANSI::Code.blue{ "World" } str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" More conveniently the ANSI::Code module extends ANSI itself. str = ANSI.red + "Hello" + ANSI.blue + "World" str.assert == "\e[31mHello\e[34mWorld" str = ANSI.red{ "Hello" } + ANSI.blue{ "World" } str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" ANSI also supports XTerm 256 color mode using red, blue and green values with the `#rgb` method. str = ANSI::Code.rgb(0, 255, 0) str.assert == "\e[38;5;46m" Or using CSS style hex codes as well. str = ANSI::Code.rgb("#00FF00") str.assert == "\e[38;5;46m" Both of these methods can take blocks to wrap text in the color and clear codes. str = ANSI::Code.rgb("#00FF00"){ "Hello" } str.assert == "\e[38;5;46mHello\e[0m" In the appropriate context the ANSI::Code module can also be included, making its methods directly accessible. include ANSI::Code str = red + "Hello" + blue + "World" str.assert == "\e[31mHello\e[34mWorld" str = red{ "Hello" } + blue{ "World" } str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" Along with the single font colors, the library include background colors. str = on_red + "Hello" str.assert == "\e[41mHello" As well as combined color methods. str = white_on_red + "Hello" str.assert == "\e[37m\e[41mHello" The ANSI::Code module supports most standard ANSI codes, though not all platforms support every code, so YMMV. ansi-1.5.0/demo/11_terminal.md0000644000004100000410000000025112465501305016060 0ustar www-datawww-data# ANSI::Terminal We should be ables to get the terminal width via the `terminal_width` method. width = ANSI::Terminal.terminal_width Fixnum.assert === width ansi-1.5.0/demo/03_logger.md0000644000004100000410000000076412465501305015536 0ustar www-datawww-data# ANSI::Logger Require the ANSI::Logger library. require 'ansi/logger' Create a new ANSI::Logger log = ANSI::Logger.new(STDOUT) Info logging appears normal. log.info{"Info logs are green.\n"} Warn logging appears yellow. log.warn{"Warn logs are yellow.\n"} Debug logging appears cyan. log.debug{"Debug logs are cyan.\n"} Error logging appears red. log.error{"Error logs are red.\n"} Fatal logging appears bright red. log.fatal{"Fatal logs are bold red!\n"} ansi-1.5.0/LICENSE.txt0000644000004100000410000000243612465501305014330 0ustar www-datawww-dataBSD-2-Clause License (http://spdx.org/licenses/BSD-2-Clause) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ansi-1.5.0/DEMO.md0000644000004100000410000002413112465501305013547 0ustar www-datawww-data# ANSI::Code Require the library. require 'ansi/code' ANSI::Code can be used as a functions module. str = ANSI::Code.red + "Hello" + ANSI::Code.blue + "World" str.assert == "\e[31mHello\e[34mWorld" If a block is supplied to each method then yielded value will be wrapped in the ANSI code and clear code. str = ANSI::Code.red{ "Hello" } + ANSI::Code.blue{ "World" } str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" More conveniently the ANSI::Code module extends ANSI itself. str = ANSI.red + "Hello" + ANSI.blue + "World" str.assert == "\e[31mHello\e[34mWorld" str = ANSI.red{ "Hello" } + ANSI.blue{ "World" } str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" In the appropriate context the ANSI::Code module can also be included, making its methods directly accessible. include ANSI::Code str = red + "Hello" + blue + "World" str.assert == "\e[31mHello\e[34mWorld" str = red{ "Hello" } + blue{ "World" } str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" Along with the single font colors, the library include background colors. str = on_red + "Hello" str.assert == "\e[41mHello" As well as combined color methods. str = white_on_red + "Hello" str.assert == "\e[37m\e[41mHello" The ANSI::Code module supports most standard ANSI codes, though not all platforms support every code, so YMMV. # String Extensions In addition the library offers an extension to String class called #ansi, which allows some of the ANSI::Code methods to be called in a more object-oriented fashion. require 'ansi/core' str = "Hello".ansi(:red) + "World".ansi(:blue) str.assert == "\e[31mHello\e[0m\e[34mWorld\e[0m" # ANSI::Logger Require the ANSI::Logger library. require 'ansi/logger' Create a new ANSI::Logger log = ANSI::Logger.new(STDOUT) Info logging appears normal. log.info{"Info logs are green.\n"} Warn logging appears yellow. log.warn{"Warn logs are yellow.\n"} Debug logging appears cyan. log.debug{"Debug logs are cyan.\n"} Error logging appears red. log.error{"Error logs are red.\n"} Fatal logging appears bright red. log.fatal{"Fatal logs are bold red!\n"} # ANSI::Progressbar Pretty progress bars are easy to construct. require 'ansi/progressbar' pbar = ANSI::Progressbar.new("Test Bar", 100) Running the bar simply requires calling the #inc method during a loop and calling #finish when done. 100.times do |i| sleep 0.01 pbar.inc end pbar.finish We will use this same rountine in all the examples below, so lets make a quick macro for it. Notice we have to use #reset first before reusing the same progress bar. def run(pbar) pbar.reset 100.times do |i| sleep 0.01 pbar.inc end pbar.finish puts end The progress bar can be stylized in almost any way. The #format setter provides control over the parts that appear on the line. For example, by default the format is: pbar.format("%-14s %3d%% %s %s", :title, :percentage, :bar, :stat) So lets vary it up to demonstrate the case. pbar.format("%-14s %3d%% %s %s", :title, :percentage, :stat, :bar) run(pbar) The progress bar has an extra build in format intended for use with file downloads called #transer_mode. pbar.transfer_mode run(pbar) Calling this methods is the same as calling: pbar.format("%-14s %3d%% %s %s",:title, :percentage, :bar, :stat_for_file_transfer) run(pbar) The #style setter allows each part of the line be modified with ANSI codes. And the #bar_mark writer can be used to change the character used to make the bar. pbar.standard_mode pbar.style(:title => [:red], :bar=>[:blue]) pbar.bar_mark = "=" run(pbar) # ANSI::Mixin The ANSI::Mixin module is design for including into String-like classes. It will support any class that defines a #to_s method. require 'ansi/mixin' In this demonstration we will simply include it in the core String class. class ::String include ANSI::Mixin end Now all strings will have access to ANSI's style and color codes via simple method calls. "roses".red.assert == "\e[31mroses\e[0m" "violets".blue.assert == "\e[34mviolets\e[0m" "sugar".italic.assert == "\e[3msugar\e[0m" The method can be combined, of course. "you".italic.bold.assert == "\e[1m\e[3myou\e[0m\e[0m" The mixin also supports background methods. "envy".on_green.assert == "\e[42menvy\e[0m" And it also supports the combined foreground-on-background methods. "b&w".white_on_black.assert == "\e[37m\e[40mb&w\e[0m" # ANSI::String The ANSI::String class is a very sophisticated implementation of Ruby's standard String class, but one that can handle ANSI codes seamlessly. require 'ansi/string' flower1 = ANSI::String.new("Roses") flower2 = ANSI::String.new("Violets") Like any other string. flower1.to_s.assert == "Roses" flower2.to_s.assert == "Violets" Bet now we can add color. flower1.red! flower2.blue! flower1.to_s.assert == "\e[31mRoses\e[0m" flower2.to_s.assert == "\e[34mViolets\e[0m" Despite that the string representation now contains ANSI codes, we can still manipulate the string in much the same way that we manipulate an ordinary string. flower1.size.assert == 5 flower2.size.assert == 7 Like ordinary strings we can concatenate the two strings flowers = flower1 + ' ' + flower2 flowers.to_s.assert == "\e[31mRoses\e[0m \e[34mViolets\e[0m" flowers.size.assert == 13 Standard case conversion such as #upcase and #downcase work. flower1.upcase.to_s.assert == "\e[31mROSES\e[0m" flower1.downcase.to_s.assert == "\e[31mroses\e[0m" Some of the most difficult methods to re-implement were the substitution methods such as #sub and #gsub. They are still somewhat more limited than the original string methods, but their primary functionality should work. flower1.gsub('s', 'z').to_s.assert == "\e[31mRozez\e[0m" There are still a number of methods that need implementation. ANSI::String is currently a very partial implementation. But as you can see from the methods it does currently support, is it already useful. # ANSI::Columns The +Columns+ class makes it easy to create nice looking text columns, sorted from top to bottom, right to left (as opposed to the other way around). require 'ansi/columns' list = %w{a b c d e f g h i j k l} columns = ANSI::Columns.new(list) columns.to_s(4) The output will be: a d g j b e h k c f i l Besides an array of elements, Columns.new can take a string in which the elements are divided by newlines characters. The default column size can also be given to the initializer. list = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl" columns = ANSI::Columns.new(list, :columns=>6) columns.to_s The output will be: a c e g i k b d f h j l If the column count is +nil+, then the number of columns will be calculated as a best fit for the current terminal window. ## Padding Columns can adjust the padding between cells. list = %w{a b c d e f g h i j k l} columns = ANSI::Columns.new(list, :padding=>2) columns.to_s(4) The output will be: a d g j b e h k c f i l ## Alignment Columns can also be aligned either left or right. list = %w{xx xx xx yy y yy z zz z} columns = ANSI::Columns.new(list, :align=>:right) columns.to_s(3) The output will be: xx yy z xx y zz xx yy z ## Format Lastly, columns can be augmented with ANSI codes. This is done through a formatting block. The block can take up to three parameters, the cell content, the column and row numbers, or the cell and the column and row numbers. list = %w{a b c d e f g h i j k l} columns = ANSI::Columns.new(list){ |c,r| r % 2 == 0 ? :red : :blue } out = columns.to_s(4) out.assert == ( "\e[31ma \e[0m\e[31md \e[0m\e[31mg \e[0m\e[31mj \e[0m\n" + "\e[34mb \e[0m\e[34me \e[0m\e[34mh \e[0m\e[34mk \e[0m\n" + "\e[31mc \e[0m\e[31mf \e[0m\e[31mi \e[0m\e[31ml \e[0m\n" ) # ANSI::Table The ANSI::Table class can be used to output tabular data with nicely formated ASCII cell borders. require 'ansi/table' The constructor takes an 2-dimensional array. data = [ [ 10, 20, 30 ], [ 20, 10, 20 ], [ 50, 40, 20 ] ] table = ANSI::Table.new(data) table.to_s The output will be: +----+----+----+ | 10 | 20 | 30 | | 20 | 10 | 20 | | 50 | 40 | 20 | +----+----+----+ # ANSI::Diff require 'ansi/diff' a = 'abcYefg' b = 'abcXefg' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mYefg\e[0m\n\e[31mabc\e[0mXefg" Try another. a = 'abc' b = 'abcdef' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\n\e[31mabc\e[0mdef" And another. a = 'abcXXXghi' b = 'abcdefghi' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mXXXghi\e[0m\n\e[31mabc\e[0mdefghi" And another. a = 'abcXXXdefghi' b = 'abcdefghi' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mXXX\e[0m\e[35mdefghi\e[0m\n\e[31mabc\e[0m\e[35mdefghi\e[0m" Comparison that is mostly different. a = 'abcpppz123' b = 'abcxyzzz43' diff = ANSI::Diff.new(a,b) diff.to_s.assert == "\e[31mabc\e[0m\e[33mpppz123\e[0m\n\e[31mabc\e[0mxyzzz43" # ANSI::BBCode The BBCode module provides methods for converting between BBCodes, basic HTML and ANSI codes. require 'ansi/bbcode' BBCodes are color and style codes in square brackets, quite popular with on line forums. bbcode = "this is [COLOR=red]red[/COLOR], this is [B]bold[/B]" We can convert this to ANSI code simply enough: ansi = ANSI::BBCode.bbcode_to_ansi(bbcode) ansi.assert == "this is \e[0;31mred\e[0m, this is \e[1mbold\e[0m\n" In addition the BBCode module supports conversion to simple HTML. html = ANSI::BBCode.bbcode_to_html(bbcode) html.assert == "this is red, this is bold
\n" # ANSI::Terminal We should be ables to get the terminal width via the `terminal_width` method. width = ANSI::Terminal.terminal_width Fixnum.assert === width ansi-1.5.0/lib/0000755000004100000410000000000012465501305013246 5ustar www-datawww-dataansi-1.5.0/lib/ansi/0000755000004100000410000000000012465501305014200 5ustar www-datawww-dataansi-1.5.0/lib/ansi/diff.rb0000644000004100000410000001245212465501305015441 0ustar www-datawww-datarequire 'ansi/code' module ANSI # Diff produces colorized differences of two string or objects. # class Diff # Highlights the differnce between two strings. # # This class method is equivalent to calling: # # ANSI::Diff.new(object1, object2).to_a # def self.diff(object1, object2, options={}) new(object1, object2, options={}).to_a end # Setup new Diff object. If the objects given are not Strings # and do not have `#to_str` defined to coerce them to such, then # their `#inspect` methods are used to convert them to strings # for comparison. # # @param [Object] object1 # First object to compare. # # @param [Object] object2 # Second object to compare. # # @param [Hash] options # Options for contoller the way difference is shown. (Not yet used.) # def initialize(object1, object2, options={}) @object1 = convert(object1) @object2 = convert(object2) @diff1, @diff2 = diff_string(@object1, @object2) end # Returns the first object's difference string. def diff1 @diff1 end # Returns the second object's difference string. def diff2 @diff2 end # Returns both first and second difference strings separated by a # new line character. # # @todo Should we use `$/` record separator instead? # # @return [String] Joined difference strings. def to_s "#{@diff1}\n#{@diff2}" end # Returns both first and second difference strings separated by a # the given `separator`. The default is `$/`, the record separator. # # @param [String] separator # The string to use as the separtor between the difference strings. # # @return [String] Joined difference strings. def join(separator=$/) "#{@diff1}#{separator}#{@diff2}" end # Returns the first and second difference strings in an array. # # @return [Array] Both difference strings. def to_a [diff1, diff2] end private # Take two plain strings and produce colorized # versions of each highlighting their differences. # # @param [String] string1 # First string to compare. # # @param [String] string2 # Second string to compare. # # @return [Array] The two difference strings. def diff_string(string1, string2) compare(string1, string2) end # Ensure the object of comparison is a string. If +object+ is not # an instance of String then it wll be converted to one by calling # either #to_str, if the object responds to it, or #inspect. def convert(object) if String === object object elsif object.respond_to?(:to_str) object.to_str else object.inspect end end # Rotation of colors for diff output. COLORS = [:red, :yellow, :magenta] # Take two plain strings and produce colorized # versions of each highlighting their differences. # # @param [String] x # First string to compare. # # @param [String] y # Second string to compare. # # @return [Array] The two difference strings. def compare(x, y) c = common(x, y) a = x.dup b = y.dup oi = 0 oj = 0 c.each_with_index do |m, q| i = a.index(m, oi) j = b.index(m, oj) a[i,m.size] = ANSI.ansi(m, COLORS[q%3]) if i b[j,m.size] = ANSI.ansi(m, COLORS[q%3]) if j oi = i + m.size if i oj = j + m.size if j end return a, b end # Oh, I should have documented this will I knew what the # hell it was doing ;) def common(x,y) c = lcs(x, y) i = x.index(c) j = y.index(c) ix = i + c.size jx = j + c.size if i == 0 l = y[0...j] elsif j == 0 l = x[0...i] else l = common(x[0...i], y[0...j]) end if ix == x.size - 1 r = y[jx..-1] elsif jx = y.size - 1 r = x[ix..-1] else r = common(x[ix..-1], y[jx..-1]) end [l, c, r].flatten.reject{ |s| s.empty? } end # Least common string. def lcs(s1, s2) res="" num=Array.new(s1.size){Array.new(s2.size)} len,ans=0 lastsub=0 s1.scan(/./).each_with_index do |l1,i | s2.scan(/./).each_with_index do |l2,j | unless l1==l2 num[i][j]=0 else (i==0 || j==0)? num[i][j]=1 : num[i][j]=1 + num[i-1][j-1] if num[i][j] > len len = ans = num[i][j] thissub = i thissub -= num[i-1][j-1] unless num[i-1][j-1].nil? if lastsub==thissub res+=s1[i,1] else lastsub=thissub res=s1[lastsub, (i+1)-lastsub] end end end end end res end # Hmm... is this even useful? def lcs_size(s1, s2) num=Array.new(s1.size){Array.new(s2.size)} len,ans=0,0 s1.scan(/./).each_with_index do |l1,i | s2.scan(/./).each_with_index do |l2,j | unless l1==l2 num[i][j]=0 else (i==0 || j==0)? num[i][j]=1 : num[i][j]=1 + num[i-1][j-1] len = ans = num[i][j] if num[i][j] > len end end end ans end end end ansi-1.5.0/lib/ansi/string.rb0000644000004100000410000001376612465501305016050 0ustar www-datawww-datarequire 'ansi/code' #require 'ansi/layout/split' # Create a new Ansi::String object. def ANSI.string(str) ANSI::String.new(str) end # IMPORTANT! ANSI::String is experimental!!! # # ANSI::String stores a regular string (`@text`) and an associative # array that ties a character index to an ANSI code (`marks`). # For example is we have the string: # # "Big Apple" # # And applied the color red to it, the marks list would be: # # [[0, :red], [9, :clear]] # # TODO: In the future we may be able to subclass String, # instead of delegating via @text, but not until it is more # compatible. # class ANSI::String CLR = ANSI::Code::CLEAR attr :text attr :marks # New Ansi::String def initialize(text=nil, marks=nil) @text = (text || '').to_s @marks = marks || [] yield(self) if block_given? end # Convert Ansi::String object to normal String. # This converts the intental markup codes to ANSI codes. def to_s s = text.dup m = marks.sort do |a,b| v = b[0] <=> a[0] if v == 0 (b[1] == :clear or b[1] == :reset) ? -1 : 1 else v end end m.each do |(index, code)| s.insert(index, ANSI::Code.__send__(code)) end #s << CLR unless s =~ /#{Regexp.escape(CLR)}$/ # always end with a clear s end # ANSI::String is a type of String. alias_method :to_str, :to_s # The size of the base text. def size ; text.size ; end # Upcase the string. def upcase ; self.class.new(text.upcase, marks) ; end def upcase! ; text.upcase! ; end # Downcase the string. def downcase ; self.class.new(text.downcase, marks) ; end def downcase! ; text.upcase! ; end # Add one String to another, or to a regular String. def +(other) case other when ANSI::String ntext = text + other.text nmarks = marks.dup omarks = shift_marks(0, text.size, other.marks) omarks.each{ |(i, c)| nmarks << [i,c] } else ntext = text + other.to_s nmarks = marks.dup end self.class.new(ntext, nmarks) end # #def |(other) # Split.new(self, other) #end # #def lr(other, options={}) # Split.new(self, other, options) #end # slice def slice(*args) if args.size == 2 index, len = *args endex = index+len new_text = text[index, len] new_marks = [] marks.each do |(i, v)| new_marks << [i, v] if i >= index && i < endex end self.class.new(new_text, new_marks) elsif args.size == 1 rng = args.first case rng when Range index, endex = rng.begin, rng.end new_text = text[rng] new_marks = [] marks.each do |(i, v)| new_marks << [i, v] if i >= index && i < endex end self.class.new(new_text, new_marks) else nm = marks.select do |(i, v)| #marks[0] == rng or ( marks[0] == rng + 1 && [:clear, :reset].include?(marks[1]) ) i == rng or ( i == rng + 1 && [:clear, :reset].include?(v) ) end self.class.new(text[rng,1], nm) end else raise ArgumentError end end # alias_method :[], :slice # This is more limited than the normal String method. # It does not yet support a block, and +replacement+ # won't substitue for \1, \2, etc. # # TODO: block support. def sub!(pattern, replacement=nil, &block) mark_changes = [] text = @text.sub(pattern) do |s| index = $~.begin(0) replacement = block.call(s) if block_given? delta = (replacement.size - s.size) mark_changes << [index, delta] replacement end marks = @marks mark_changes.each do |index, delta| marks = shift_marks(index, delta, marks) end @text = text @marks = marks self end # See #sub!. def sub(pattern,replacement=nil, &block) dup.sub!(pattern, replacement, &block) end # def gsub!(pattern, replacement=nil, &block) mark_changes = [] mark_additions = [] text = @text.gsub(pattern) do |s| index = $~.begin(0) replacement = block.call(self.class.new(s)) if block_given? if self.class===replacement adj_marks = replacement.marks.map{ |(i,c)| [i+index,c] } mark_additions.concat(adj_marks) replacement = replacement.text end delta = (replacement.size - s.size) mark_changes << [index, delta] replacement end marks = @marks mark_changes.each do |(index, delta)| marks = shift_marks(index, delta, marks) end marks.concat(mark_additions) @text = text @marks = marks self end # See #gsub!. def gsub(pattern, replacement=nil, &block) dup.gsub!(pattern, replacement, &block) end # def ansi(code) m = marks.dup m.unshift([0, code]) m.push([size, :clear]) self.class.new(text, m) end alias_method :color, :ansi # def ansi!(code) marks.unshift([0, code]) marks.push([size, :clear]) end alias_method :color!, :ansi! def red ; color(:red) ; end def green ; color(:green) ; end def blue ; color(:blue) ; end def black ; color(:black) ; end def magenta ; color(:magenta) ; end def yellow ; color(:yellow) ; end def cyan ; color(:cyan) ; end def bold ; ansi(:bold) ; end def underline ; ansi(:underline) ; end def red! ; color!(:red) ; end def green! ; color!(:green) ; end def blue! ; color!(:blue) ; end def black! ; color!(:black) ; end def magenta! ; color!(:magenta) ; end def yellow! ; color!(:yellow) ; end def cyan! ; color!(:cyan) ; end def bold! ; ansi!(:bold) ; end def underline! ; ansi!(:underline) ; end private # def shift_marks(index, delta, marks=nil) new_marks = [] (marks || @marks).each do |(i, c)| case i <=> index when -1 new_marks << [i, c] when 0, 1 new_marks << [i+delta, c] end end new_marks end # def shift_marks!(index, delta) @marks.replace(shift_marks(index, delta)) end end ansi-1.5.0/lib/ansi/hexdump.rb0000644000004100000410000000577012465501305016210 0ustar www-datawww-datamodule ANSI require 'ansi/code' # TODO: split dump method into two parts, the first should create a hex table # then the second, #dump method, will print it out. # Create a colorized hex dump of byte string. # # Output looks something like the following, but colorized. # # 000352c0: ed 33 8c 85 6e cc f6 f7 72 79 1c e3 3a b4 c2 c6 |.3..n...ry..:...| # 000352d0: c8 8d d6 ee 3e 68 a1 a5 ae b2 b7 97 a4 1d 5f a7 |....>h........_.| # 000352e0: d8 7d 28 db f6 8a e7 8a 7b 8d 0b bd 35 7d 25 3c |.}(.....{...5}%<| # 000352f0: 8b 3c c8 9d ec 04 85 54 92 a0 f7 a8 ed cf 05 7d |.<.....T.......}| # 00035300: b5 e3 9e 35 f0 79 9f 51 74 e3 60 ee 0f 03 8e 3f |...5.y.Qt.`....?| # 00035310: 05 5b 91 87 e6 48 48 ee a3 77 ae ad 5e 2a 56 a2 |.[...HH..w..^*V.| # 00035320: b6 96 86 f3 3c 92 b3 c8 62 4a 6f 96 10 5c 9c bb |....<...bJo..\..| # # In the future, we will make the colorization more customizable and # allow the groupings to be selectable at 2, 4, 8 or 16. # class HexDump # Printable ASCII codes. ASCII_PRINTABLE = (33..126) # def initialize(options={}) @offset = 0 options.each do |k,v| __send__("#{k}=", v) end @color = true if color.nil? end # Use color? attr_accessor :color # Show index? attr_accessor :index # Offset byte count. attr_accessor :offset # Dump data string as colorized hex table. # # @param data [String] # String to convert to hex and display. # def dump(data) lines = data.to_s.scan(/.{1,16}/m) max_offset = (offset + data.size) / 256 #16 * 16 max_offset_width = max_offset.to_s.size + 1 max_hex_width = 49 #3 * 16 + 1 out = template() off = offset() if index? puts((' ' * max_offset_width) + " 0 1 2 3 4 5 6 7 8 9 A B C D E F\n") end lines.each_with_index do |line, n| offset = off + n * 16 bytes = line.unpack("C*") hex = bytes.map{ |c| "%0.2x" % c }.insert(8, '').join(' ') plain = bytes.map do |c| if ASCII_PRINTABLE.include?(c) c = c.chr else color ? Code::WHITE + Code::STRIKE + '.' + Code::CLEAR : '.' end end.join('') fill = [offset.to_s.rjust(max_offset_width), hex.ljust(max_hex_width), plain] puts(out % fill) end end # Hex dump a random string. # def dump_random(size=64) data = (0..size).map{ rand(255).chr }.join('') dump(data) end # def index? @index end private # Hex dump line template. # # @return [String] hex dump line template def template if color Code::CYAN + "%s: " + Code::YELLOW + "%s " + Code::BLUE + "|" + Code::CLEAR + "%s" + Code::BLUE + "|" + Code::CLEAR else "%s: %s |%s|" end end end end ansi-1.5.0/lib/ansi/columns.rb0000644000004100000410000001146112465501305016210 0ustar www-datawww-datarequire 'ansi/terminal' module ANSI # class Columns # Create a column-based layout. # # @param [String,Array] list # Multiline String or Array of strings to columnize. # # @param [Hash] options # Options to customize columnization. # # @option options [Fixnum] :columns # Number of columns. # # @option options [Symbol] :align # Column alignment, either :left, :right or :center. # # @option options [String,Fixnum] :padding # String or number or spaces to append to each column. # # The +format+ block MUST return ANSI codes. def initialize(list, options={}, &format) self.list = list self.columns = options[:columns] || options[:cols] self.padding = options[:padding] || 1 self.align = options[:align] || :left #self.ansi = options[:ansi] self.format = format #@columns = nil if @columns == 0 end # def inspect "#<#{self.class}:#{object_id} #{list.inspect} x #{columns}>" end # List layout into columns. Each new line is taken to be # a row-column cell. attr :list def list=(list) case list when ::String @list = list.lines.to_a.map{ |e| e.chomp("\n") } when ::Array @list = list.map{ |e| e.to_s } end end # Default number of columns to display. If nil then the number # of coumns is estimated from the size of the terminal. attr :columns # Set column count ensuring value is either an integer or nil. # The the value given is zero, it will be taken to mean the same # as nil, which means fit-to-screen. def columns=(integer) integer = integer.to_i @columns = (integer.zero? ? nil : integer) end # Padding size to apply to cells. attr :padding # Set padding to string or number (of spaces). def padding=(pad) case pad when Numeric @padding = ' ' * pad.to_i else @padding = pad.to_s end end # Alignment to apply to cells. attr :align # Set alignment ensuring value is a symbol. # # @param [#to_sym] symbol # Either `:right`, `:left` or `:center`. # # @return [Symbol] The given symbol. def align=(symbol) symbol = symbol.to_sym raise ArgumentError, "invalid alignment -- #{symbol.inspect}" \ unless [:left, :right, :center].include?(symbol) @align = symbol end # Formating to apply to cells. attr :format # Set formatting procedure. The procedure must return # ANSI codes, suitable for passing to String#ansi method. def format=(procedure) @format = procedure ? procedure.to_proc : nil end # TODO: Should #to_s also take options and formatting block? # Maybe instead have hoin take all these and leave #to_s bare. # Return string in column layout. The number of columns is determined # by the `columns` property or overriden by +cols+ argument. def to_s(cols=nil) to_s_columns(cols || columns) end # def join(cols=nil) to_s_columns(cols || columns) end private # Layout string lines into columns. # # @todo Put in empty strings for blank cells. # @todo Centering look like it's off by one to the right. # def to_s_columns(columns=nil) lines = list.to_a count = lines.size max = lines.map{ |l| l.size }.max if columns.nil? width = Terminal.terminal_width columns = (width / (max + padding.size)).to_i end rows = [] mod = (count / columns.to_f).to_i mod += 1 if count % columns != 0 lines.each_with_index do |line, index| (rows[index % mod] ||=[]) << line.strip end pad = padding tmp = template(max, pad) str = "" rows.each_with_index do |row, ri| row.each_with_index do |cell, ci| ansi_codes = ansi_formatting(cell, ci, ri) if ansi_codes.empty? str << (tmp % cell) else str << (tmp % cell).ansi(*ansi_codes) end end str.rstrip! str << "\n" end str end # Aligns the cell left or right. def template(max, pad) case align when :center, 'center' offset = " " * (max / 2) "#{offset}%#{max}s#{offset}#{pad}" when :right, 'right' "%#{max}s#{pad}" else "%-#{max}s#{pad}" end end # Used to apply ANSI formatting to each cell. def ansi_formatting(cell, col, row) if @format case @format.arity when 0 f = @format[] when 1 f = @format[cell] when 2 f = @format[col, row] else f = @format[cell, col, row] end else f = nil end [f].flatten.compact end end end ansi-1.5.0/lib/ansi/chart.rb0000644000004100000410000000572612465501305015640 0ustar www-datawww-datamodule ANSI # Table of codes used throughout the system. # # @see http://en.wikipedia.org/wiki/ANSI_escape_code CHART = { :clear => 0, :reset => 0, :bright => 1, :bold => 1, :faint => 2, :dark => 2, :italic => 3, :underline => 4, :underscore => 4, :blink => 5, :slow_blink => 5, :rapid => 6, :rapid_blink => 6, :invert => 7, :inverse => 7, :reverse => 7, :negative => 7, :swap => 7, :conceal => 8, :concealed => 8, :hide => 9, :strike => 9, :default_font => 10, :font_default => 10, :font0 => 10, :font1 => 11, :font2 => 12, :font3 => 13, :font4 => 14, :font5 => 15, :font6 => 16, :font7 => 17, :font8 => 18, :font9 => 19, :fraktur => 20, :bright_off => 21, :bold_off => 21, :double_underline => 21, :clean => 22, :italic_off => 23, :fraktur_off => 23, :underline_off => 24, :blink_off => 25, :inverse_off => 26, :positive => 26, :conceal_off => 27, :show => 27, :reveal => 27, :crossed_off => 29, :crossed_out_off => 29, :black => 30, :red => 31, :green => 32, :yellow => 33, :blue => 34, :magenta => 35, :cyan => 36, :white => 37, :on_black => 40, :on_red => 41, :on_green => 42, :on_yellow => 43, :on_blue => 44, :on_magenta => 45, :on_cyan => 46, :on_white => 47, :frame => 51, :encircle => 52, :overline => 53, :frame_off => 54, :encircle_off => 54, :overline_off => 55, } # SPECIAL_CHART = { :save => "\e[s", # Save current cursor positon. :restore => "\e[u", # Restore saved cursor positon. :clear_eol => "\e[K", # Clear to the end of the current line. :clr => "\e[K", # Clear to the end of the current line. :clear_right => "\e[0K", # Clear to the end of the current line. :clear_left => "\e[1K", # Clear to the start of the current line. :clear_line => "\e[2K", # Clear the entire current line. :clear_screen => "\e[2J", # Clear the screen and move cursor to home. :cls => "\e[2J", # Clear the screen and move cursor to home. :cursor_hide => "\e[?25l", # Hide the cursor. :cursor_show => "\e[?25h" # Show the cursor. } end ansi-1.5.0/lib/ansi/bbcode.rb0000644000004100000410000003007212465501305015745 0ustar www-datawww-data# BBCode # # Copyright (c) 2002 Thomas-Ivo Heinen # # This module is free software. You may use, modify, and/or redistribute this # software under the same terms as Ruby. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. # module ANSI # TODO: Integrate BBCode with Code module. # The BBCode module helps ease the separation of core and frontend with the # core (or submodules) being still able to say, what colors shall be used # in it's responses. This is achieved by encoding formatting information # using the BBCode tokens. This enables you to "pipe" layout information # such as colors, style, font, size and alignment through the core to # the frontend. # # Additionally it converts markups/codes between ANSI, HTML and BBCode # almost freely ;) # # # Converting a bbcode string to ANSI and XHTML # str = "this is [COLOR=red]red[/COLOR], this is [B]bold[/B]" # print( BBCode.bbcode_to_ansi(str) ) # print( BBCode.bbcode_to_html(str) ) # module BBCode ## ANSIname => ANSIcode LUT ANSINAME2CODE= { "reset" => "\e[0m", "bold" => "\e[1m", "underline" => "\e[4m", "blink" => "\e[5m", "reverse" => "\e[7m", "invisible" => "\e[8m", "black" => "\e[0;30m", "darkgrey" => "\e[1;30m", "red" => "\e[0;31m", "lightred" => "\e[1;31m", "green" => "\e[0;32m", "lightgreen" => "\e[1;32m", "brown" => "\e[0;33m", "yellow" => "\e[1;33m", "blue" => "\e[0;34m", "lightblue" => "\e[1;34m", "purple" => "\e[0;35m", "magenta" => "\e[1;35m", "cyan" => "\e[1;36m", "lightcyan" => "\e[1;36m", "grey" => "\e[0;37m", "white" => "\e[1;37m", "bgblack" => "\e[40m", "bgred" => "\e[41m", "bggreen" => "\e[42m", "bgyellow" => "\e[43m", "bgblue" => "\e[44m", "bgmagenta" => "\e[45m", "bgcyan" => "\e[46m", "bgwhite" => "\e[47m" } ## BBColor => ANSIname LUT BBCOLOR2ANSI = { "skyblue" => "blue", "royalblue" => "blue", "blue" => "blue", "darkblue" => "blue", "orange" => "red", "orangered" => "red", "crimson" => "red", "red" => "lightred", "firebrick" => "red", "darkred" => "red", "green" => "green", "limegreen" => "green", "seagreen" => "green", "darkgreen" => "green", "deeppink" => "magenta", "tomato" => "red", "coral" => "cyan", "purple" => "purple", "indigo" => "blue", "burlywood" => "red", "sandybrown"=> "red", "sierra" => "sierra", "chocolate" => "brown", "teal" => "teal", "silver" => "white", "black" => "black", "yellow" => "yellow", "magenta" => "magenta", "cyan" => "cyan", "white" => "white" } ## ANSInames => BBCode LUT ANSINAME2BBCODE = { "bold" => "B", "underline" => "U", "reverse" => "I", "red" => "COLOR=red", "blue" => "COLOR=blue", "green" => "COLOR=green", "cyan" => "COLOR=cyan", "magenta"=> "COLOR=deeppink", "purple" => "COLOR=purple", "black" => "COLOR=black", "white" => "COLOR=white", "yellow" => "COLOR=yellow", "brown" => "COLOR=chocolate" } ## Needed for alignments @@width = 80 # --------------------------- # Returns the ANSI sequence for given color, if existant def BBCode.ansi(colorname) colorname.strip! return ANSINAME2CODE[ colorname.downcase ] end # --- strip_bbcode( string ) # Will strip any BBCode tags from the given string. def BBCode.strip_bbcode(string) string.strip! return string.gsub(/\[[A-Za-z0-9\/=]+\]/, "") end # Returns the string with all ansi escape sequences converted to BBCodes def BBCode.ansi_to_bbcode(string) return "" if string.nil? || string.to_s.strip.empty? result = "" tagstack = [] ## Iterate over input lines string.split("\n").each do |line| ## Iterate over found ansi sequences line.scan(/\e\[[0-9;]+m/).each do |seq| ansiname = ANSINAME2CODE.invert["#{seq}"] ## Pop last tag and form closing tag if ansiname == "reset" lasttag = tagstack.pop bbname = "/" + String.new( lasttag.split("=")[0] ) ## Get corresponding BBCode tag + Push to stack else bbname = ANSINAME2BBCODE[ansiname] tagstack.push(bbname) end ## Replace ansi sequence by BBCode tag replace = sprintf("[%s]", bbname) line.sub!(seq, replace) end ## Append converted line result << sprintf("%s\n", line) end ## Some tags are unclosed while !tagstack.empty? result << sprintf("[/%s]", String.new(tagstack.pop.split("=")[0]) ) end return result end # Converts a BBCode string to one with ANSI sequences. # Returns the string with all formatting instructions in BBCodes converted # to ANSI code sequences / aligned with spaces to specified width. def BBCode.bbcode_to_ansi(string, usecolors = true) return "" if string.nil? || string.to_s.strip.empty? result = "" return BBCode.strip_bbcode(string) if !usecolors ## Iterate over lines string.split("\n").each do |line| ## TODO: stacking? other styles! ANSINAME2BBCODE.each do |key,val| line.gsub!(/\[#{val}\]/, ANSINAME2CODE[key]) line.gsub!(/\[\/#{val}\]/, ANSINAME2CODE["reset"]) end ## Fonttypes and sizes not available line.gsub!(/\[SIZE=\d\]/, "") line.gsub!(/\[\/SIZE\]/, "") line.gsub!(/\[FONT=[^\]]*\]/, "") line.gsub!(/\[\/FONT\]/, "") ## Color-mapping colors = line.scan(/\[COLOR=(.*?)\]/i) colors = colors.collect{|s| s[0].to_s} if !colors.nil? colors.each do |col| name = BBCOLOR2ANSI[col.downcase] name = BBCOLOR2ANSI["white"] if name.nil? code = ANSINAME2CODE[name] line.gsub!(/\[COLOR=#{col}\]/i, code) end line.gsub!(/\[\/COLOR\]/, ANSINAME2CODE["reset"]) ## TODO: Alignment ## TODO: IMGs ## TODO: EMAILs ## TODO: URLs ## TODO: QUOTEs ## TODO: LISTs result << sprintf("%s\n", line) end return result end # Converts a HTML string into one with BBCode markup (TODO) # Returns the (X)HTML markup string as BBCode def BBCode.html_to_bbcode(string) return "" if string.nil? || string.to_s.strip.empty? result = "" ## Iterate over lines string.split(/
/i).each do |line| styles = { "strong" => "b", "b" => "b", "em" => "i", "i" => "i", "u" => "u" } ## preserve B, I, U styles.each do |html,code| line.gsub!(/<#{html}>/i, "[#{code.upcase}]") line.gsub!(/<\/#{html}>/i, "[/#{code.upcase}]") end ## TODO: COLORs ## TODO: SIZEs ## TODO: FONTs ## EMAIL line.gsub!(/.*?<\/a>/i, "[EMAIL]\\1[/EMAIL]") ## URL line.gsub!(/(.*?)<\/a>/i, "[URL=\\1]\\2[/URL]") ## Other refs + closing tags => throw away line.gsub!(//i, "") line.gsub!(/<\/a>/i, "") ## IMG #line.gsub!(//i, "[IMG=\\1]") line.gsub!(//i, "[IMG]\\1[/IMG]") ## CENTER (right/left??) line.gsub!(/
/i, "[ALIGN=center]") line.gsub!(/<\/center>/i, "[/ALIGN]") ## QUOTE line.gsub!(/<(?:xmp|pre)>/i, "[QUOTE]") line.gsub!(/<\/(?:xmp|pre)>/i, "[/QUOTE]") ## LIST line.gsub!(/
    /i, "\n[LIST]\n") line.gsub!(/<\/ul>/i, "\n[/LIST]\n") line.gsub!(/
  • */i, "\n[*] ") ## Unkown tags => throw away line.gsub!(/<.*? *\/?>/, "") result << sprintf("%s
    \n", line) end return result.gsub!(/
    /i, "\n") end # Converts a BBCode string to one with HTML markup. # Returns the string with all formatting instructions in # BBCodes converted to XHTML markups. def BBCode.bbcode_to_html(string) return "" if string.nil? || string.to_s.strip.empty? result = "" quote = 0 ## Iterate over lines string.split("\n").each do |line| styles = { "b" => "strong", "i" => "em", "u" => "u" } ## preserve B, I, U styles.each do |code,html| line.gsub!(/\[#{code}\]/i, "<#{html}>") line.gsub!(/\[\/#{code}\]/i, "") end ## COLOR => font color=... (TODO: should be numeric!) line.gsub!(/\[COLOR=(.*?)\]/i, "") line.gsub!(/\[\/COLOR\]/i, "") ## SIZE => font size=... line.gsub!(/\[SIZE=(.*?)\]/i, "") line.gsub!(/\[\/SIZE\]/i, "") ## URL line.gsub!(/\[URL\]([^\[]+?)\[\/URL\]/i, "
    \\1") line.gsub!(/\[URL=(.*?)\](.+?)\[\/URL\]/i, "\\2") ## IMG line.gsub!(/\[IMG=(.*?)\]/i, "") ## ALIGN=center (TODO: right, left) line.gsub!(/\[ALIGN=center\]/i, "
    ") line.gsub!(/\[ALIGN=right\]/i, "
    ") line.gsub!(/\[ALIGN=left\]/i, "
    ") line.gsub!(/\[\/ALIGN\]/i, "
    ") ## QUOTE quote+=1 if line =~ /\[QUOTE\]/i quote-=1 if (line =~ /\[\/QUOTE\]/i) && (quote > -1) line.gsub!(/\[QUOTE\]/i, "
    \n")
                line.gsub!(/\[\/QUOTE\]/i, "
    \n") line.gsub!(/^/, ">"*quote) if quote > 0 ## EMAIL line.gsub!(/\[EMAIL\](.*?)\[\/EMAIL\]/i, "\\1") ## LIST (TODO: LIST=1, LIST=A) line.gsub!(/\[LIST(?:=(.*?))?\]/i, "\n
      \n") line.gsub!(/\[\/LIST\]/i, "\n
    \n") line.gsub!(/\[\*\]/i, "\n
  • ") ## FONT => font ?????? ## ?BLUR?, FADE? result << sprintf("%s
    \n", line) end return result end # -- Transitive methods --------------- # Converts an ANSI string to one with HTML markup. # Returns the string with ANSI code sequences converted to XHTML markup. def BBCode.ansi_to_html(string) bbcoded = BBCode.ansi_to_bbcode(string ) htmled = BBCode.bbcode_to_html(bbcoded) return htmled end # Returns the (X)HTML markup code as ANSI sequences def BBCode.html_to_ansi(string) bbcoded = BBCode.html_to_bbcode(string ) ansied = BBCode.bbcode_to_ansi(bbcoded) return ansied end end #module BBCode end ansi-1.5.0/lib/ansi/terminal.rb0000644000004100000410000000155312465501305016344 0ustar www-datawww-datamodule ANSI # = Terminal # # This library is based of HighLine's SystemExtensions # by James Edward Gray II. # # Copyright 2006 Gray Productions # # Distributed under the tems of the # {Ruby software license}[http://www.ruby-lang.org/en/LICENSE.txt]. module Terminal module_function modes = %w{win32 termios curses stty} # This section builds character reading and terminal size functions # to suit the proper platform we're running on. # # Be warned: Here be dragons! # begin require 'ansi/terminal/' + (mode = modes.shift) CHARACTER_MODE = mode rescue LoadError retry end # Get the width of the terminal window. def terminal_width terminal_size.first end # Get the height of the terminal window. def terminal_height terminal_size.last end end end ansi-1.5.0/lib/ansi/logger.rb0000644000004100000410000001153412465501305016010 0ustar www-datawww-data# Ansi::Logger # Copyright (c) 2009 Thomas Sawyer # Copyright (c) 2005 George Moschovitis require "logger" require "time" require "ansi/code" # = ANSI::Logger # # Extended variation of Ruby's standard Logger library that supports # color output. # # log = ANSI::Logger.new # # log.formatter do |severity, timestamp, progname, msg| # ANSI::Logger::SIMPLE_FORMAT % [severity, msg] # end # #-- # TODO: What's all this about then? # # When using debug level logger messages always append 'if $DBG' # at the end. This hack is needed because Ruby does not support # lazy evaluation (lisp macros). #++ class ANSI::Logger < Logger # Some available logging formats. SIMPLE_FORMAT = "%5s: %s\n" DETAILED_FORMAT = "%s %5s: %s\n" # TODO: Not sure I like this approach. class ::Logger #:nodoc: class LogDevice #:nodoc: attr_writer :ansicolor def ansicolor? @ansicolor.nil? ? true : @ansicolor end end end # def ansicolor? @logdev.ansicolor? end # def ansicolor=(on) @logdev.ansicolor = on end # Dictate the way in which this logger should format the # messages it displays. This method requires a block. The # block should return formatted strings given severity, # timestamp, progname and msg. # # === Example # # logger = ANSI::Logger.new # # logger.formatter do |severity, timestamp, progname, msg| # "#{progname}@#{timestamp} - #{severity}::#{msg}" # end # def formatter(&block) self.formatter = block if block super end def styles(options=nil) @styles ||= { :info => [], :warn => [:yellow], :debug => [:cyan], :error => [:red], :fatal => [:bold, :red] } @styles.merge!(options) if options @styles end # def info(progname=nil, &block) return unless info? @logdev.ansicolor? ? info_with_color{ super } : super end # def warn(progname=nil, &block) return unless warn? @logdev.ansicolor? ? warn_with_color{ super } : super end # def debug(progname=nil, &block) return unless debug? @logdev.ansicolor? ? debug_with_color{ super } : super end # def error(progname=nil, &block) return unless error? @logdev.ansicolor? ? error_with_color{ super } : super end # def fatal(progname=nil, &block) return unless error? @logdev.ansicolor? ? fatal_with_color{ super } : super end private def info_with_color #:yield: styles[:info].each{ |s| self << ANSI::Code.send(s) } yield self << ANSI::Code.clear end def warn_with_color #:yield: styles[:warn].each{ |s| self << ANSI::Code.send(s) } yield self << ANSI::Code.clear end def error_with_color #:yield: styles[:error].each{ |s| self << ANSI::Code.send(s) } yield self << ANSI::Code.clear end def debug_with_color #:yield: styles[:debug].each{ |s| self << ANSI::Code.send(s) } yield self << ANSI::Code.clear end def fatal_with_color #:yield: styles[:fatal].each{ |s| self << ANSI::Code.send(s) } yield self << ANSI::Code.clear end end # NOTE: trace is deprecated b/c binding of caller is no longer possible. =begin # Prints a trace message to DEBUGLOG (at debug level). # Useful for emitting the value of variables, etc. Use # like this: # # x = y = 5 # trace 'x' # -> 'x = 5' # trace 'x ** y' # -> 'x ** y = 3125' # # If you have a more complicated value, like an array of # hashes, then you'll probably want to use an alternative # output format. For instance: # # trace 'value', :yaml # # Valid output format values (the _style_ parameter) are: # # :p :inspect # :pp (pretty-print, using 'pp' library) # :s :to_s # :y :yaml :to_yaml (using the 'yaml' library') # # The default is :p. # # CREDITS: # # This code comes straight from the dev-utils Gem. # Author: Gavin Sinclair def trace(expr, style=:p) unless expr.respond_to? :to_str warn "trace: Can't evaluate the given value: #{caller.first}" else raise "FACETS: binding/or_caller is no longer possible" require "facets/core/binding/self/of_caller" Binding.of_caller do |b| value = b.eval(expr.to_str) formatter = TRACE_STYLES[style] || :inspect case formatter when :pp then require 'pp' when :y, :yaml, :to_yaml then require 'yaml' end value_s = value.send(formatter) message = "#{expr} = #{value_s}" lines = message.split(/\n/) indent = " " debug(lines.shift) lines.each do |line| debug(indent + line) end end end end TRACE_STYLES = {} # :nodoc: TRACE_STYLES.update( :pp => :pp_s, :s => :to_s, :p => :inspect, :y => :to_yaml, :yaml => :to_yaml, :inspect => :inspect, :to_yaml => :to_yaml ) =end ansi-1.5.0/lib/ansi/table.rb0000644000004100000410000000733612465501305015625 0ustar www-datawww-datarequire 'ansi/core' require 'ansi/terminal' module ANSI class Table # The Table class can be used to output nicely formatted # tables with division lines and alignment. # # table - array of array # # options[:align] - align :left or :right # options[:padding] - space to add to each cell # options[:fit] - fit to screen width # options[:border] - # # The +format+ block must return ANSI codes to apply # to each cell. # # Other Implementations: # # * http://github.com/visionmedia/terminal-table # * http://github.com/aptinio/text-table # # TODO: Support for table headers and footers. def initialize(table, options={}, &format) @table = table @padding = options[:padding] || 0 @align = options[:align] @fit = options[:fit] @border = options[:border] #@ansi = [options[:ansi]].flatten @format = format @pad = " " * @padding end # attr_accessor :table # Fit to scree width. attr_accessor :fit # attr_accessor :padding # attr_accessor :align # attr_accessor :format # attr_accessor :border # def to_s #(fit=false) #row_count = table.size #col_count = table[0].size max = max_columns(fit) div = dividing_line top = div #.gsub('+', ".") bot = div #.gsub('+', "'") body = [] table.each_with_index do |row, r| body_row = [] row.each_with_index do |cell, c| t = cell_template(max[c]) s = t % cell.to_s body_row << apply_format(s, cell, c, r) end body << "| " + body_row.join(' | ') + " |" end if border body = body.join("\n#{div}\n") else body = body.join("\n") end "#{top}\n#{body}\n#{bot}\n" end private # TODO: look at the lines and figure out how many columns will fit def fit_width width = Terminal.terminal_width ((width.to_f / column_size) - (padding + 3)).to_i end # Calculate the maximun column sizes. # # @return [Array] maximum size for each column def max_columns(fit=false) max = Array.new(column_size, 0) table.each do |row| row.each_with_index do |col, index| col = col.to_s col = col.unansi if fit max[index] = [max[index], col.size, fit_width].max else max[index] = [max[index], col.size].max end end end max end # Number of columns based on the first row of table. # # @return [Integer] number of columns def column_size table.first.size end # def cell_template(max) case align when :right, 'right' "#{@pad}%#{max}s" else "%-#{max}s#{@pad}" end end # TODO: make more efficient def dividing_line tmp = max_columns(fit).map{ |m| "%#{m}s" }.join(" | ") tmp = "| #{tmp} |" lin = (tmp % (['-'] * column_size)).gsub(/[^\|]/, '-').gsub('|', '+') lin end #def dividing_line_top # dividing_line.gsub('+', '.') #end #def dividing_line_bottom # dividing_line.gsub('+', "'") #end # def apply_format(str, cell, col, row) if @format str.ansi(*ansi_formating(cell, col, row)) else str end end # def ansi_formating(cell, col, row) if @format case @format.arity when 0 f = @format[] when 1 f = @format[cell] when 2 f = @format[row, col] else f = @format[cell, row, col] end else f = nil end [f].flatten.compact end end end ansi-1.5.0/lib/ansi/chain.rb0000644000004100000410000000120012465501305015600 0ustar www-datawww-datarequire 'ansi/code' module ANSI # ANSI::Chain was inspired by Kazuyoshi Tlacaelel's Isna library. # class Chain # def initialize(string) @string = string.to_s @codes = [] end # attr :string # attr :codes # def method_missing(s, *a, &b) if ANSI::CHART.key?(s) @codes << s self else super(s, *a, &b) end end # def to_s if codes.empty? result = @string else result = Code.ansi(@string, *codes) codes.clear end result end # def to_str to_s end end end ansi-1.5.0/lib/ansi/progressbar.rb0000644000004100000410000001443012465501305017060 0ustar www-datawww-data# Copyright (C) 2009 Thomas Sawyer # # This library is based on the original ProgressBar # by Satoru Takabayashi. # # ProgressBar Copyright (C) 2001 Satoru Takabayashi require 'ansi/code' module ANSI # = Progressbar # # Progressbar is a text-based progressbar library. # # pbar = Progressbar.new( "Demo", 100 ) # 100.times { pbar.inc } # pbar.finish # class ProgressBar # def initialize(title, total, out=STDERR) @title = title @total = total @out = out @bar_length = 80 @bar_mark = "|" @total_overflow = true @current = 0 @previous = 0 @is_finished = false @start_time = Time.now @format = "%-14s %3d%% %s %s" @format_arguments = [:title, :percentage, :bar, :stat] @styles = {} # yield self if block_given? # show_progress end public attr_accessor :format attr_accessor :format_arguments attr_accessor :styles # def title=(str) @title = str end # def bar_mark=(mark) @bar_mark = String(mark)[0..0] end alias_method :barmark=, :bar_mark= alias_method :mark=, :bar_mark= def total_overflow=(boolv) @total_overflow = boolv ? true : false end # Get rid of warning about Kenrel method being redefined. remove_method :format # Set format and format arguments. def format(format, *arguments) @format = format @format_arguments = *arguments unless arguments.empty? end # Set ANSI styling options. def style(options) @styles = options end # def standard_mode @format = "%-14s %3d%% %s %s" @format_arguments = [:title, :percentage, :bar, :stat] end # def transfer_mode @format = "%-14s %3d%% %s %s" @format_arguments = [:title, :percentage, :bar, :stat_for_file_transfer] end # For backward compatability alias_method :file_transfer_mode, :transfer_mode def finish @current = @total @is_finished = true show_progress end def flush @out.flush end def halt @is_finished = true show_progress end def set(count) if count < 0 raise "invalid count less than zero: #{count}" elsif count > @total if @total_overflow @total = count + 1 else raise "invalid count greater than total: #{count}" end end @current = count show_progress @previous = @current end # def reset @current = 0 @is_finished = false end # def inc(step = 1) @current += step @current = @total if @current > @total show_progress @previous = @current end # def clear @out.print(" " * get_width + eol) end def inspect "(ProgressBar: #{@current}/#{@total})" end private # def convert_bytes(bytes) if bytes < 1024 sprintf("%6dB", bytes) elsif bytes < 1024 * 1000 # 1000kb sprintf("%5.1fKB", bytes.to_f / 1024) elsif bytes < 1024 * 1024 * 1000 # 1000mb sprintf("%5.1fMB", bytes.to_f / 1024 / 1024) else sprintf("%5.1fGB", bytes.to_f / 1024 / 1024 / 1024) end end # def transfer_rate bytes_per_second = @current.to_f / (Time.now - @start_time) sprintf("%s/s", convert_bytes(bytes_per_second)) end # def bytes convert_bytes(@current) end # def format_time(t) t = t.to_i sec = t % 60 min = (t / 60) % 60 hour = t / 3600 sprintf("%02d:%02d:%02d", hour, min, sec); end # # ETA stands for Estimated Time of Arrival. def eta if @current == 0 "ETA: --:--:--" else elapsed = Time.now - @start_time eta = elapsed * @total / @current - elapsed; sprintf("ETA: %s", format_time(eta)) end end # def elapsed elapsed = Time.now - @start_time sprintf("Time: %s", format_time(elapsed)) end # def stat if @is_finished then elapsed else eta end end # def stat_for_file_transfer if @is_finished then sprintf("%s %s %s", bytes, transfer_rate, elapsed) else sprintf("%s %s %s", bytes, transfer_rate, eta) end end # def eol if @is_finished then "\n" else "\r" end end # def bar len = percentage * @bar_length / 100 sprintf("|%s%s|", @bar_mark * len, " " * (@bar_length - len)) end # def percentage if @total.zero? 100 else @current * 100 / @total end end # def title @title[0,13] + ":" end # TODO: Use Terminal.terminal_width instead. def get_width # FIXME: I don't know how portable it is. default_width = 80 begin tiocgwinsz = 0x5413 data = [0, 0, 0, 0].pack("SSSS") if @out.ioctl(tiocgwinsz, data) >= 0 then #rows, cols, xpixels, ypixels = data.unpack("SSSS") cols = data.unpack("SSSS")[1] if cols >= 0 then cols else default_width end else default_width end rescue Exception default_width end end # def show arguments = @format_arguments.map do |method| colorize(send(method), styles[method]) end line = sprintf(@format, *arguments) width = get_width length = ANSI::Code.uncolor{line}.length if length == width - 1 @out.print(line + eol) elsif length >= width @bar_length = [@bar_length - (length - width + 1), 0].max @bar_length == 0 ? @out.print(line + eol) : show else #line.length < width - 1 @bar_length += width - length + 1 show end end # def show_progress if @total.zero? cur_percentage = 100 prev_percentage = 0 else cur_percentage = (@current * 100 / @total).to_i prev_percentage = (@previous * 100 / @total).to_i end if cur_percentage > prev_percentage || @is_finished show end end # def colorize(part, style) return part unless style #[style].flatten.inject(part){ |pt, st| ANSI::Code.ansi(pt, *st) } ANSI::Code.ansi(part, *style) end end # Progressbar = ProgressBar #:nodoc: end ansi-1.5.0/lib/ansi/version.rb0000644000004100000410000000050512465501305016212 0ustar www-datawww-datamodule ANSI # Returns Hash table of project metadata. def self.metadata @spec ||= ( require 'yaml' YAML.load(File.new(File.dirname(__FILE__) + '/../ansi.yml')) ) end # Check metadata for missing constants. def self.const_missing(name) metadata[name.to_s.downcase] || super(name) end end ansi-1.5.0/lib/ansi/code.rb0000644000004100000410000002132012465501305015435 0ustar www-datawww-datamodule ANSI # Global variable can be used to prevent ANSI codes # from being used in ANSI's methods that do so to string. # # NOTE: This has no effect on methods that return ANSI codes. $ansi = true if RUBY_PLATFORM =~ /(win32|w32)/ begin require 'Win32/Console/ANSI' rescue LoadError warn "ansi: 'gem install win32console' to use color on Windows" $ansi = false end end require 'ansi/constants' # TODO: up, down, right, left, etc could have yielding methods too? # ANSI Codes # # Ansi::Code module makes it very easy to use ANSI codes. # These are especially nice for beautifying shell output. # # Ansi::Code.red + "Hello" + Ansi::Code.blue + "World" # => "\e[31mHello\e[34mWorld" # # Ansi::Code.red{ "Hello" } + Ansi::Code.blue{ "World" } # => "\e[31mHello\e[0m\e[34mWorld\e[0m" # # IMPORTANT! Do not mixin Ansi::Code, instead use {ANSI::Mixin}. # # See {ANSI::CHART} for list of all supported codes. # module Code extend self # include ANSI Constants include Constants # Regexp for matching most ANSI codes. PATTERN = /\e\[(\d+)m/ # ANSI clear code. ENDCODE = "\e[0m" # List of primary styles. def self.styles %w{bold dark italic underline underscore blink rapid reverse negative concealed strike} end # List of primary colors. def self.colors %w{black red green yellow blue magenta cyan white} end # Return ANSI code given a list of symbolic names. def [](*codes) code(*codes) end # Dynamically create color on color methods. # # @deprecated # colors.each do |color| colors.each do |on_color| module_eval <<-END, __FILE__, __LINE__ def #{color}_on_#{on_color}(string=nil) if string return string unless $ansi #warn "use ANSI block notation for future versions" return #{color.upcase} + ON_#{color.upcase} + string + ENDCODE end if block_given? return yield unless $ansi #{color.upcase} + ON_#{on_color.upcase} + yield.to_s + ENDCODE else #{color.upcase} + ON_#{on_color.upcase} end end END end end # Use method missing to dispatch ANSI code methods. def method_missing(code, *args, &blk) esc = nil if CHART.key?(code) esc = "\e[#{CHART[code]}m" elsif SPECIAL_CHART.key?(code) esc = SPECIAL_CHART[code] end if esc if string = args.first return string unless $ansi #warn "use ANSI block notation for future versions" return "#{esc}#{string}#{ENDCODE}" end if block_given? return yield unless $ansi return "#{esc}#{yield}#{ENDCODE}" end esc else super(code, *args, &blk) end end # TODO: How to deal with position codes when $ansi is false? # Should we raise an error or just not push the codes? # For now, we will leave this it as is. # Like +move+ but returns to original position after # yielding the block. def display(line, column=0) #:yield: result = "\e[s" result << "\e[#{line.to_i};#{column.to_i}H" if block_given? result << yield result << "\e[u" #elsif string # result << string # result << "\e[u" end result end # Move cursor to line and column. def move(line, column=0) "\e[#{line.to_i};#{column.to_i}H" end # Move cursor up a specified number of spaces. def up(spaces=1) "\e[#{spaces.to_i}A" end # Move cursor down a specified number of spaces. def down(spaces=1) "\e[#{spaces.to_i}B" end # Move cursor left a specified number of spaces. def left(spaces=1) "\e[#{spaces.to_i}D" end alias :back :left # Move cursor right a specified number of spaces. def right(spaces=1) "\e[#{spaces.to_i}C" end alias :forward :right ## #def position # "\e[#;#R" #end # Apply ANSI codes to a first argument or block value. # # @example # ansi("Valentine", :red, :on_white) # # @example # ansi(:red, :on_white){ "Valentine" } # # @return [String] # String wrapped ANSI code. # def ansi(*codes) #:yield: if block_given? string = yield.to_s else # first argument must be the string string = codes.shift.to_s end return string unless $ansi c = code(*codes) c + string.gsub(ENDCODE, ENDCODE + c) + ENDCODE end # TODO: Allow selective removal using *codes argument? # Remove ANSI codes from string or block value. # # @param [String] string # String from which to remove ANSI codes. # # @return [String] # String wrapped ANSI code. # def unansi(string=nil) #:yield: if block_given? string = yield.to_s else string = string.to_s end string.gsub(PATTERN, '') end # Alias for #ansi method. # # @deprecated # Here for backward compatibility. alias_method :style, :ansi # Alias for #unansi method. # # @deprecated # Here for backwards compatibility. alias_method :unstyle, :unansi # Alternate term for #ansi. # # @deprecated # May change in future definition. alias_method :color, :ansi # Alias for unansi. # # @deprecated # May change in future definition. alias_method :uncolor, :unansi # Look-up code from chart, or if Integer simply pass through. # Also resolves :random and :on_random. # # @param codes [Array 255 v end end # extend Code end ansi-1.5.0/lib/ansi/core.rb0000644000004100000410000000053312465501305015456 0ustar www-datawww-datarequire 'ansi/code' require 'ansi/chain' class ::String # def ansi(*codes) if codes.empty? ANSI::Chain.new(self) else ANSI::Code.ansi(self, *codes) end end # def ansi!(*codes) replace(ansi(*codes)) end # def unansi ANSI::Code.unansi(self) end # def unansi! replace(unansi) end end ansi-1.5.0/lib/ansi/terminal/0000755000004100000410000000000012465501305016013 5ustar www-datawww-dataansi-1.5.0/lib/ansi/terminal/curses.rb0000644000004100000410000000061412465501305017645 0ustar www-datawww-datamodule ANSI module Terminal require 'curses' module_function #CHARACTER_MODE = "curses" # For Debugging purposes only. # # Curses savvy getc(). # def get_character(input = STDIN) Curses.getch() end def terminal_size Curses.init_screen w, r = Curses.cols, Curses.lines Curses.close_screen return w, r end end end ansi-1.5.0/lib/ansi/terminal/win32.rb0000644000004100000410000000573112465501305017310 0ustar www-datawww-datamodule ANSI module Terminal # Cygwin will look like Windows, but we want to treat it like a Posix OS: raise LoadError, "Cygwin is a Posix OS." if RUBY_PLATFORM =~ /\bcygwin\b/i require "Win32API" # See if we're on Windows. module_function #CHARACTER_MODE = "Win32API" # For Debugging purposes only. # # Windows savvy getc(). # # def get_character( input = STDIN ) @stdin_handle ||= GetStdHandle(STD_INPUT_HANDLE) begin SetConsoleEcho(@stdin_handle, false) input.getc ensure SetConsoleEcho(@stdin_handle, true) end end # A Windows savvy method to fetch the console columns, and rows. def terminal_size stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE) bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy = GetConsoleScreenBufferInfo(stdout_handle) return right - left + 1, bottom - top + 1 end # windows savvy console echo toggler def SetConsoleEcho( console_handle, on ) mode = GetConsoleMode(console_handle) # toggle the console echo bit if on mode |= ENABLE_ECHO_INPUT else mode &= ~ENABLE_ECHO_INPUT end ok = SetConsoleMode(console_handle, mode) end # win32 console APIs STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 ENABLE_PROCESSED_INPUT = 0x0001 ENABLE_LINE_INPUT = 0x0002 ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 ENABLE_ECHO_INPUT = 0x0004 ENABLE_WINDOW_INPUT = 0x0008 ENABLE_MOUSE_INPUT = 0x0010 ENABLE_INSERT_MODE = 0x0020 ENABLE_QUICK_EDIT_MODE = 0x0040 @@apiGetStdHandle = nil @@apiGetConsoleMode = nil @@apiSetConsoleMode = nil @@apiGetConsoleScreenBufferInfo = nil def GetStdHandle( handle_type ) @@apiGetStdHandle ||= Win32API.new( "kernel32", "GetStdHandle", ['L'], 'L' ) @@apiGetStdHandle.call( handle_type ) end def GetConsoleMode( console_handle ) @@apiGetConsoleMode ||= Win32API.new( "kernel32", "GetConsoleMode", ['L', 'P'], 'I' ) mode = ' ' * 4 @@apiGetConsoleMode.call(console_handle, mode) mode.unpack('L')[0] end def SetConsoleMode( console_handle, mode ) @@apiSetConsoleMode ||= Win32API.new( "kernel32", "SetConsoleMode", ['L', 'L'], 'I' ) @@apiSetConsoleMode.call(console_handle, mode) != 0 end def GetConsoleScreenBufferInfo( console_handle ) @@apiGetConsoleScreenBufferInfo ||= Win32API.new( "kernel32", "GetConsoleScreenBufferInfo", ['L', 'P'], 'L' ) format = 'SSSSSssssSS' buf = ([0] * format.size).pack(format) @@apiGetConsoleScreenBufferInfo.call(console_handle, buf) buf.unpack(format) end end end ansi-1.5.0/lib/ansi/terminal/stty.rb0000644000004100000410000000241412465501305017344 0ustar www-datawww-datamodule ANSI module Terminal module_function #COLS_FALLBACK = 80 #ROWS_FALLBACK = 25 #CHARACTER_MODE = "stty" # For Debugging purposes only. # # Unix savvy getc(). (second choice) # # *WARNING*: This method requires the external "stty" program! # def get_character(input = STDIN) raw_no_echo_mode begin input.getc ensure restore_mode end end # # Switched the input mode to raw and disables echo. # # *WARNING*: This method requires the external "stty" program! # def raw_no_echo_mode @state = `stty -g` system "stty raw -echo cbreak isig" end # # Restores a previously saved input mode. # # *WARNING*: This method requires the external "stty" program! # def restore_mode system "stty #{@state}" end # A Unix savvy method to fetch the console columns, and rows. def terminal_size if /solaris/ =~ RUBY_PLATFORM && (`stty` =~ /\brows = (\d+).*\bcolumns = (\d+)/) w, r = [$2, $1] else w, r = `stty size`.split.reverse end w = `tput cols` unless w # last ditch effort to at least get width w = w.to_i if w r = r.to_i if r return w, r end end end ansi-1.5.0/lib/ansi/terminal/termios.rb0000644000004100000410000000334212465501305020024 0ustar www-datawww-datamodule ANSI module Terminal require "termios" # Unix, first choice. module_function #CHARACTER_MODE = "termios" # For Debugging purposes only. # # Unix savvy getc(). (First choice.) # # *WARNING*: This method requires the "termios" library! # def get_character( input = STDIN ) old_settings = Termios.getattr(input) new_settings = old_settings.dup new_settings.c_lflag &= ~(Termios::ECHO | Termios::ICANON) new_settings.c_cc[Termios::VMIN] = 1 begin Termios.setattr(input, Termios::TCSANOW, new_settings) input.getc ensure Termios.setattr(input, Termios::TCSANOW, old_settings) end end # A Unix savvy method to fetch the console columns, and rows. def terminal_size if /solaris/ =~ RUBY_PLATFORM && (`stty` =~ /\brows = (\d+).*\bcolumns = (\d+)/) w, r = [$2, $1] else w, r = `stty size`.split.reverse end w = `tput cols` unless w # last ditch effort to at least get width w = w.to_i if w r = r.to_i if r return w, r end # Console screen width (taken from progress bar) # # NOTE: Don't know how portable #screen_width is. # TODO: How to fit into system? # def screen_width(out=STDERR) default_width = ENV['COLUMNS'] || 76 begin tiocgwinsz = 0x5413 data = [0, 0, 0, 0].pack("SSSS") if out.ioctl(tiocgwinsz, data) >= 0 then rows, cols, xpixels, ypixels = data.unpack("SSSS") if cols >= 0 then cols else default_width end else default_width end rescue Exception default_width end end end end ansi-1.5.0/lib/ansi/constants.rb0000644000004100000410000000102112465501305016533 0ustar www-datawww-datamodule ANSI require 'ansi/chart' # Converts {CHART} and {SPECIAL_CHART} entries into constants. # So for example, the CHART entry for :red becomes: # # ANSI::Constants::RED #=> "\e[31m" # # The ANSI Constants are include into ANSI::Code and can be included # any where will they would be of use. # module Constants CHART.each do |name, code| const_set(name.to_s.upcase, "\e[#{code}m") end SPECIAL_CHART.each do |name, code| const_set(name.to_s.upcase, code) end end end ansi-1.5.0/lib/ansi/mixin.rb0000644000004100000410000001430112465501305015650 0ustar www-datawww-datamodule ANSI require 'ansi/code' # This module is designed specifically for mixing into # String-like classes or extending String-like objects. # # Generally speaking the String#ansi method is the more # elegant approach to modifying a string with codes # via a method call. But in some cases this Mixin's design # might be preferable. Indeed, it original intent was # as a compatability layer for the +colored+ gem. module Mixin def bold ; ANSI::Code.bold { to_s } ; end def dark ; ANSI::Code.dark { to_s } ; end def italic ; ANSI::Code.italic { to_s } ; end def underline ; ANSI::Code.underline { to_s } ; end def underscore ; ANSI::Code.underscore { to_s } ; end def blink ; ANSI::Code.blink { to_s } ; end def rapid ; ANSI::Code.rapid { to_s } ; end def reverse ; ANSI::Code.reverse { to_s } ; end def negative ; ANSI::Code.negative { to_s } ; end def concealed ; ANSI::Code.concealed { to_s } ; end def strike ; ANSI::Code.strike { to_s } ; end def black ; ANSI::Code.black { to_s } ; end def red ; ANSI::Code.red { to_s } ; end def green ; ANSI::Code.green { to_s } ; end def yellow ; ANSI::Code.yellow { to_s } ; end def blue ; ANSI::Code.blue { to_s } ; end def magenta ; ANSI::Code.magenta { to_s } ; end def cyan ; ANSI::Code.cyan { to_s } ; end def white ; ANSI::Code.white { to_s } ; end def on_black ; ANSI::Code.on_black { to_s } ; end def on_red ; ANSI::Code.on_red { to_s } ; end def on_green ; ANSI::Code.on_green { to_s } ; end def on_yellow ; ANSI::Code.on_yellow { to_s } ; end def on_blue ; ANSI::Code.on_blue { to_s } ; end def on_magenta ; ANSI::Code.on_magenta { to_s } ; end def on_cyan ; ANSI::Code.on_cyan { to_s } ; end def on_white ; ANSI::Code.on_white { to_s } ; end def black_on_red ; ANSI::Code.black_on_red { to_s } ; end def black_on_green ; ANSI::Code.black_on_green { to_s } ; end def black_on_yellow ; ANSI::Code.black_on_yellow { to_s } ; end def black_on_blue ; ANSI::Code.black_on_blue { to_s } ; end def black_on_magenta ; ANSI::Code.black_on_magenta { to_s } ; end def black_on_cyan ; ANSI::Code.black_on_cyan { to_s } ; end def black_on_white ; ANSI::Code.black_on_white { to_s } ; end def red_on_black ; ANSI::Code.red_on_black { to_s } ; end def red_on_green ; ANSI::Code.red_on_green { to_s } ; end def red_on_yellow ; ANSI::Code.red_on_yellow { to_s } ; end def red_on_blue ; ANSI::Code.red_on_blue { to_s } ; end def red_on_magenta ; ANSI::Code.red_on_magenta { to_s } ; end def red_on_cyan ; ANSI::Code.red_on_cyan { to_s } ; end def red_on_white ; ANSI::Code.red_on_white { to_s } ; end def green_on_black ; ANSI::Code.green_on_black { to_s } ; end def green_on_red ; ANSI::Code.green_on_red { to_s } ; end def green_on_yellow ; ANSI::Code.green_on_yellow { to_s } ; end def green_on_blue ; ANSI::Code.green_on_blue { to_s } ; end def green_on_magenta ; ANSI::Code.green_on_magenta { to_s } ; end def green_on_cyan ; ANSI::Code.green_on_cyan { to_s } ; end def green_on_white ; ANSI::Code.green_on_white { to_s } ; end def yellow_on_black ; ANSI::Code.yellow_on_black { to_s } ; end def yellow_on_red ; ANSI::Code.yellow_on_red { to_s } ; end def yellow_on_green ; ANSI::Code.yellow_on_green { to_s } ; end def yellow_on_blue ; ANSI::Code.yellow_on_blue { to_s } ; end def yellow_on_magenta ; ANSI::Code.yellow_on_magenta { to_s } ; end def yellow_on_cyan ; ANSI::Code.yellow_on_cyan { to_s } ; end def yellow_on_white ; ANSI::Code.yellow_on_white { to_s } ; end def blue_on_black ; ANSI::Code.blue_on_black { to_s } ; end def blue_on_red ; ANSI::Code.blue_on_red { to_s } ; end def blue_on_green ; ANSI::Code.blue_on_green { to_s } ; end def blue_on_yellow ; ANSI::Code.blue_on_yellow { to_s } ; end def blue_on_magenta ; ANSI::Code.blue_on_magenta { to_s } ; end def blue_on_cyan ; ANSI::Code.blue_on_cyan { to_s } ; end def blue_on_white ; ANSI::Code.blue_on_white { to_s } ; end def magenta_on_black ; ANSI::Code.magenta_on_black { to_s } ; end def magenta_on_red ; ANSI::Code.magenta_on_red { to_s } ; end def magenta_on_green ; ANSI::Code.magenta_on_green { to_s } ; end def magenta_on_yellow ; ANSI::Code.magenta_on_yellow { to_s } ; end def magenta_on_blue ; ANSI::Code.magenta_on_blue { to_s } ; end def magenta_on_cyan ; ANSI::Code.magenta_on_cyan { to_s } ; end def magenta_on_white ; ANSI::Code.magenta_on_white { to_s } ; end def cyan_on_black ; ANSI::Code.cyan_on_black { to_s } ; end def cyan_on_red ; ANSI::Code.cyan_on_red { to_s } ; end def cyan_on_green ; ANSI::Code.cyan_on_green { to_s } ; end def cyan_on_yellow ; ANSI::Code.cyan_on_yellow { to_s } ; end def cyan_on_blue ; ANSI::Code.cyan_on_blue { to_s } ; end def cyan_on_magenta ; ANSI::Code.cyan_on_magenta { to_s } ; end def cyan_on_white ; ANSI::Code.cyan_on_white { to_s } ; end def white_on_black ; ANSI::Code.white_on_black { to_s } ; end def white_on_red ; ANSI::Code.white_on_red { to_s } ; end def white_on_green ; ANSI::Code.white_on_green { to_s } ; end def white_on_yellow ; ANSI::Code.white_on_yellow { to_s } ; end def white_on_blue ; ANSI::Code.white_on_blue { to_s } ; end def white_on_magenta ; ANSI::Code.white_on_magenta { to_s } ; end def white_on_cyan ; ANSI::Code.white_on_cyan { to_s } ; end # Move cursor to line and column, insert +self.to_s+ and return to # original positon. def display(line, column=0) result = "\e[s" result << "\e[#{line.to_i};#{column.to_i}H" result << to_s result << "\e[u" result end end end ansi-1.5.0/lib/ansi.yml0000644000004100000410000000276712465501305014737 0ustar www-datawww-data--- revision: 2013 type: ruby sources: - INDEX.yml authors: - name: Thomas Sawyer email: transfire@gmail.com - name: Florian Frank organizations: [] requirements: - groups: - build development: true name: mast - groups: - build development: true name: indexer - groups: - build development: true name: ergo - groups: - test development: true name: qed - groups: - test development: true name: ae - groups: - test development: true name: lemon conflicts: [] alternatives: [] resources: - type: home uri: http://rubyworks.github.com/ansi label: Homepage - type: docs uri: http://rubydoc.info/gems/ansi/frames label: Documentation - type: code uri: http://github.com/rubyworks/ansi label: Source Code - type: bugs uri: http://github.com/rubyworks/ansi/issues label: Issue Tracker - type: mail uri: http://groups.google.com/group/rubyworks-mailinglist label: Mailing List repositories: - name: upstream scm: git uri: git://github.com/rubyworks/ansi.git categories: [] copyrights: - holder: Rubyworks year: '2009' license: BSD-2-Clause customs: [] paths: lib: - lib name: ansi title: ANSI version: 1.5.0 summary: ANSI at your fingertips! description: The ANSI project is a superlative collection of ANSI escape code related libraries eabling ANSI colorization and stylization of console output. Byte for byte ANSI is the best ANSI code library available for the Ruby programming language. orgranizations: - Rubyworks created: '2009-08-01' date: '2015-01-16' ansi-1.5.0/lib/ansi.rb0000644000004100000410000000065212465501305014530 0ustar www-datawww-data# ANSI namespace module contains all the ANSI related classes. module ANSI end require 'ansi/version' require 'ansi/core' require 'ansi/code' require 'ansi/bbcode' require 'ansi/columns' require 'ansi/diff' require 'ansi/logger' require 'ansi/mixin' require 'ansi/progressbar' require 'ansi/string' require 'ansi/table' require 'ansi/terminal' # Kernel method def ansi(string, *codes) ANSI::Code.ansi(string, *codes) end ansi-1.5.0/metadata.yml0000644000004100000410000001050712465501305015006 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: ansi version: !ruby/object:Gem::Version version: 1.5.0 platform: ruby authors: - Thomas Sawyer - Florian Frank autorequire: bindir: bin cert_chain: [] date: 2015-01-17 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: mast requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: indexer requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: ergo requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: qed requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: ae requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: lemon requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' description: The ANSI project is a superlative collection of ANSI escape code related libraries eabling ANSI colorization and stylization of console output. Byte for byte ANSI is the best ANSI code library available for the Ruby programming language. email: - transfire@gmail.com executables: [] extensions: [] extra_rdoc_files: - LICENSE.txt - NOTICE.md - README.md - HISTORY.md - DEMO.md files: - .index - .yardopts - lib/ansi/bbcode.rb - lib/ansi/chain.rb - lib/ansi/chart.rb - lib/ansi/code.rb - lib/ansi/columns.rb - lib/ansi/constants.rb - lib/ansi/core.rb - lib/ansi/diff.rb - lib/ansi/hexdump.rb - lib/ansi/logger.rb - lib/ansi/mixin.rb - lib/ansi/progressbar.rb - lib/ansi/string.rb - lib/ansi/table.rb - lib/ansi/terminal/curses.rb - lib/ansi/terminal/stty.rb - lib/ansi/terminal/termios.rb - lib/ansi/terminal/win32.rb - lib/ansi/terminal.rb - lib/ansi/version.rb - lib/ansi.rb - lib/ansi.yml - demo/01_ansicode.md - demo/02_core.md - demo/03_logger.md - demo/04_progressbar.md - demo/05_mixin.md - demo/06_string.md - demo/07_columns.md - demo/08_table.md - demo/09_diff.md - demo/10_bbcode.md - demo/11_terminal.md - demo/applique/ae.rb - demo/applique/output.rb - test/case_ansicode.rb - test/case_bbcode.rb - test/case_mixin.rb - test/case_progressbar.rb - test/test_helper.rb - NOTICE.md - README.md - HISTORY.md - DEMO.md - LICENSE.txt homepage: http://rubyworks.github.com/ansi licenses: - BSD-2-Clause metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.0.3 signing_key: specification_version: 4 summary: ANSI at your fingertips! test_files: - test/case_bbcode.rb - test/case_progressbar.rb - test/case_ansicode.rb - test/case_mixin.rb - test/test_helper.rb has_rdoc: ansi-1.5.0/test/0000755000004100000410000000000012465501305013457 5ustar www-datawww-dataansi-1.5.0/test/case_ansicode.rb0000644000004100000410000000127712465501305016573 0ustar www-datawww-datarequire 'test_helper' require 'ansi/code' testcase ANSI::Code do method :red do test do str = ANSI::Code.red out = "\e[31m" out.assert == str end test "with block notation" do str = ANSI::Code.red { "Hello" } out = "\e[31mHello\e[0m" out.assert == str end end method :blue do test do str = ANSI::Code.blue out = "\e[34m" out.assert == str end test "with block notation" do str = ANSI::Code.blue { "World" } out = "\e[34mWorld\e[0m" out.assert == str end end method :hex do test do str = ANSI::Code.hex("#000000") out = "0" out.assert == str end end end ansi-1.5.0/test/case_bbcode.rb0000644000004100000410000000216112465501305016215 0ustar www-datawww-datarequire 'test_helper' require 'ansi/bbcode' testcase ANSI::BBCode do class_method :bbcode_to_ansi do test do str = "this is [COLOR=red]red[/COLOR], this is [B]bold[/B]" out = "this is \e[0;31mred\e[0m, this is \e[1mbold\e[0m\n" out.assert == ANSI::BBCode.bbcode_to_ansi(str) end end class_method :bbcode_to_html do test do str = "this is [COLOR=red]red[/COLOR], this is [B]bold[/B]" out = "this is red, this is bold
    \n" out.assert == ANSI::BBCode.bbcode_to_html(str) end end class_method :ansi_to_html do test do str = "this is \e[0;31mred\e[0m, this is \e[1mbold\e[0m\n" + "this is a line without any ansi code\n" + "this is \e[0;31mred\e[0m, this is \e[1mbold\e[0m\n" out = "this is red, this is bold
    \n" + "this is a line without any ansi code
    \n" + "this is red, this is bold
    \n" out.assert == ANSI::BBCode.ansi_to_html(str) end end end ansi-1.5.0/test/case_progressbar.rb0000644000004100000410000000057612465501305017340 0ustar www-datawww-datarequire 'test_helper' require 'stringio' require 'ansi/progressbar' testcase ANSI::Progressbar do method :initialize do test do stio = StringIO.new pbar = ANSI::Progressbar.new("Test Bar", 10, stio) do |b| b.style(:title => [:red], :bar=>[:blue]) end 10.times do |i| sleep 0.1 pbar.inc end true end end end ansi-1.5.0/test/test_helper.rb0000644000004100000410000000003612465501305016321 0ustar www-datawww-datarequire 'lemon' require 'ae' ansi-1.5.0/test/case_mixin.rb0000644000004100000410000000102212465501305016116 0ustar www-datawww-datarequire 'test_helper' require 'ansi/mixin' testcase ANSI::Mixin do # TODO: subclass class ::String include ANSI::Mixin end method :red do test do str = "Hello".red out = "\e[31mHello\e[0m" out.assert == str end end method :blue do test do str = "World".blue out = "\e[34mWorld\e[0m" out.assert == str end end method :display do test do str = "Hello".display(4,10) out = "\e[s\e[4;10HHello\e[u" out.assert == str end end end ansi-1.5.0/.yardopts0000644000004100000410000000007412465501305014347 0ustar www-datawww-data--title ANSI --protected --private lib - QED.rdoc [A-Z]*.* ansi-1.5.0/NOTICE.md0000644000004100000410000001507312465501305014011 0ustar www-datawww-data# COPYRIGHT NOTICES ## ANSI Copyright © 2009 [Rubyworks](http://rubyworks.github.com) · License [BSD-2-Clause](http://spdx.org/licenses/BSD-2-Clause) · Website http://rubyworks.github.com/ansi Copyright 2009 Rubyworks. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (https://raw.github.com/rubyworks/ansi/master/LICENSE.txt) ## ProgressBar Copyright © 2001 *Satoru Takabayashi* · License [Ruby](http://spdx.org/licenses/Ruby) · Website http://0xcc.net/ruby-progressbar ProgressBar class is based on the original ProgressBar by Satoru Takabayashi. Ruby/ProgressBar - a text progress bar library Copyright (C) 2001-2005 Satoru Takabayashi All rights reserved. This is free software with ABSOLUTELY NO WARRANTY. You can redistribute it and/or modify it under the terms of Ruby's license. ## HighLine (Terminal Extensions) Copyright © 2006 *Gray Productions* · License [Ruby](http://spdx.org/licenses/Ruby) · Website http://highline.rubyforge.org The terminal extensions are based on HighLine's SystemExtensions by James Edward Gray II. Copyright 2006 Gray Productions Distributed under the user's choice of the {GPL Version 2}[http://www.gnu.org/licenses/old-licenses/gpl-2.0.html] (see GPL-2.0.txt for details) or the {Ruby software license}[http://www.ruby-lang.org/en/LICENSE.txt] by James Edward Gray II and Greg Brown. Please email James[mailto:james@grayproductions.net] with any questions. (https://github.com/JEG2/highline/blob/master/LICENSE) ## BBCode Copyright © 2002 *Thomas-Ivo Heinen* · License [Ruby](http://spdx.org/licenses/Ruby) BBCode module is a derivative of BBCode by Thomas-Ivo Heinen. Copyright (c) 2002 Thomas-Ivo Heinen This module is free software. You may use, modify, and/or redistribute this software under the same terms as Ruby. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ## Rainbow (XTerm Color Support) Copyright © *Marcin Kulik* · License [MIT](http://spdx.org/licenses/MIT) · Website http://github.com/sickill/rainbow Rainbox provided the bases for building the XTerm 256 color code support into the ANSI::Code module. Copyright (c) Marcin Kulik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (https://raw.github.com/sickill/rainbow/master/LICENSE) ## Paint (ANSI Code Names) Copyright © 2011 *Jan Lelis* · License [MIT](http://spdx.org/licenses/MIT) · Website https://github.com/janlelis/paint Some of the latest ANSI code names, and inspiration to check out Rainbow and include XTerm 256 color codes, came from Paint. Copyright (c) 2011 Jan Lelis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (https://raw.github.com/janlelis/paint/master/LICENSE.txt) ## ANSIColor _Acknowlegement_ Copyright © 2002 *Florian Frank* · Website http://flori.github.com/term-ansicolor Albeit the code no long bares much, if any, resemblance to it, the ANSI Code module (and subsequently the Constants module) originated with the ANSIColor library by Florian Frank. Copyright (c) 2002 Florian Frank ansi-1.5.0/README.md0000644000004100000410000000476412465501305013772 0ustar www-datawww-data# ANSI [HOME](http://rubyworks.github.com/ansi) · [API](http://rubydoc.info/gems/ansi/frames) · [MAIL](http://googlegroups.com/group/rubyworks-mailinglist) · [ISSUES](http://github.com/rubyworks/ansi/issues) · [SOURCE](http://github.com/rubyworks/ansi) [![Build Status](https://secure.travis-ci.org/rubyworks/ansi.png)](http://travis-ci.org/rubyworks/ansi)
    The ANSI project is a collection of ANSI escape code related libraries enabling ANSI code based colorization and stylization of output. It is very nice for beautifying shell output. This collection is based on a set of scripts spun-off from Ruby Facets. Included are Code (used to be ANSICode), Logger, ProgressBar and String. In addition the library includes Terminal which provides information about the current output device. ## Features * ANSI::Code provides ANSI codes as module functions. * String#ansi makes common usage very easy and elegant. * ANSI::Mixin provides an alternative mixin (like +colored+ gem). * Very Good coverage of standard ANSI codes. * Additional clases for colorized columns, tables, loggers and more. ## Synopsis There are a number of modules and classes provided by the ANSI package. To get a good understanding of them it is best to pursue the [QED documents](http://github.com/rubyworks/ansi/tree/master/qed/) or the [API documentation](http://rubyworks.github.com/ansi/api/index.html). At the heart of all the provided libraries lies the ANSI::Code module which defines ANSI codes as constants and methods. For example: require 'ansi/code' ANSI.red + "Hello" + ANSI.blue + "World" => "\e[31mHello\e[34mWorld" Or in block form. ANSI.red{ "Hello" } + ANSI.blue{ "World" } => "\e[31mHello\e[0m\e[34mWorld\e[0m" The methods defined by this module are used throughout the rest of the system. ## Installation ### RubyGems To install with RubyGems simply open a console and type: $ sudo gem install ansi ### Setup.rb (not recommended) Local installation requires Setup.rb (gem install setup), then [download](http://github.com/rubyworks/ansi/download) the tarball package and type: $ tar -xvzf ansi-1.0.0.tgz $ cd ansi-1.0.0 $ sudo setup.rb all Windows users use 'ruby setup.rb all'. ## Release Notes Please see HISTORY.md file. ## License & Copyrights Copyright (c) 2009 Rubyworks This program is redistributable under the terms of the *FreeBSD* license. Some pieces of the code are copyrighted by others. See LICENSE.txt and NOTICE.md files for details.