Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Port dedent from Python

  • Loading branch information...
commit ca5d6b34f1f3729c232dd640735bab23d6f1fdbe 1 parent 47bebad
Conrad Irwin ConradIrwin authored
Showing with 42 additions and 0 deletions.
  1. +1 −0  CHANGELOG
  2. +41 −0 lib/pry/helpers/command_helpers.rb
1  CHANGELOG
View
@@ -9,6 +9,7 @@
* cat --ex now works on exceptions in REPL-defined code
* play -m now uses eval_string.replace()
* play -m --open uses show-input to show play'd code
+* added "unindent" helper to make adding help to commands easier
8/9/2011 version 0.9.5
41 lib/pry/helpers/command_helpers.rb
View
@@ -443,6 +443,47 @@ def prompt(message, options="Yn")
end
end
+ # Remove any common leading whitespace from every line in `text`.
+ #
+ # This can be used to make a HEREDOC line up with the left margin, without
+ # sacrificing the indentation level of the source code.
+ #
+ # e.g.
+ # opt.banner unindent <<-USAGE
+ # Lorem ipsum dolor sit amet, consectetur adipisicing elit,
+ # sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
+ # "Ut enim ad minim veniam."
+ # USAGE
+ #
+ # @param [String] The text from which to remove indentation
+ # @return [String], The text with indentation stripped.
+ #
+ # @copyright Heavily based on textwrap.dedent from Python, which is:
+ # Copyright (C) 1999-2001 Gregory P. Ward.
+ # Copyright (C) 2002, 2003 Python Software Foundation.
+ # Written by Greg Ward <gward@python.net>
+ #
+ # Licensed under <http://docs.python.org/license.html>
+ # From <http://hg.python.org/cpython/file/6b9f0a6efaeb/Lib/textwrap.py>
+ #
+ def unindent(text)
+ # Empty blank lines
+ text = text.sub(/^[ \t]+$/, '')
+
+ # Find the longest common whitespace to all indented lines
+ margin = text.scan(/^[ \t]*(?=[^ \t\n])/).inject do |current_margin, next_indent|
+ if next_indent.start_with?(current_margin)
+ current_margin
+ elsif current_margin.start_with?(next_indent)
+ next_indent
+ else
+ ""
+ end
+ end
+
+ text.gsub(/^#{margin}/, '')
+ end
+
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.