Skip to content

Commit

Permalink
Port dedent from Python
Browse files Browse the repository at this point in the history
  • Loading branch information
ConradIrwin committed Sep 12, 2011
1 parent 47bebad commit ca5d6b3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Expand Up @@ -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

Expand Down
41 changes: 41 additions & 0 deletions lib/pry/helpers/command_helpers.rb
Expand Up @@ -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
Expand Down

0 comments on commit ca5d6b3

Please sign in to comment.