From 1b5d4b7ecefbeb462032f7d64089d54b8406df75 2011-06-20 23:39:12 From: MinRK Date: 2011-06-20 23:39:12 Subject: [PATCH] allow utils.text.indent to [optionally] flatten existing indentation. --- diff --git a/IPython/config/application.py b/IPython/config/application.py index 4d695a6..44da984 100644 --- a/IPython/config/application.py +++ b/IPython/config/application.py @@ -161,7 +161,7 @@ class Application(SingletonConfigurable): help = trait.get_metadata('help') print alias, "(%s)"%longname, ':', trait.__class__.__name__ if help: - print indent(help) + print indent(help, flatten=True) print def print_flag_help(self): @@ -176,7 +176,7 @@ class Application(SingletonConfigurable): for m, (cfg,help) in self.flags.iteritems(): print '--'+m - print indent(help) + print indent(help, flatten=True) print def print_help(self): diff --git a/IPython/config/configurable.py b/IPython/config/configurable.py index 89e6038..4b8b1a8 100755 --- a/IPython/config/configurable.py +++ b/IPython/config/configurable.py @@ -44,7 +44,6 @@ class MultipleInstanceError(ConfigurableError): # Configurable implementation #----------------------------------------------------------------------------- - class Configurable(HasTraits): config = Instance(Config,(),{}) @@ -151,7 +150,7 @@ class Configurable(HasTraits): header = "%s.%s : %s" % (cls.__name__, k, v.__class__.__name__) final_help.append(header) if help is not None: - final_help.append(indent(help)) + final_help.append(indent(help, flatten=True)) return '\n'.join(final_help) @classmethod diff --git a/IPython/utils/text.py b/IPython/utils/text.py index e00266c..bf72ee1 100644 --- a/IPython/utils/text.py +++ b/IPython/utils/text.py @@ -391,15 +391,39 @@ def igrep(pat,list): return grep(pat,list,case=0) -def indent(str,nspaces=4,ntabs=0): +def indent(instr,nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. + + Parameters + ---------- + + instr : basestring + The string to be indented. + nspaces : int (default: 4) + The number of spaces to be indented. + ntabs : int (default: 0) + The number of tabs to be indented. + flatten : bool (default: False) + Whether to scrub existing indentation. If True, all lines will be + aligned to the same indentation. If False, existing indentation will + be strictly increased. + + Returns + ------- + + str|unicode : string indented by ntabs and nspaces. + """ - if str is None: + if instr is None: return ind = '\t'*ntabs+' '*nspaces - outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) + if flatten: + pat = re.compile(r'^\s*', re.MULTILINE) + else: + pat = re.compile(r'^', re.MULTILINE) + outstr = re.sub(pat, ind, instr) if outstr.endswith(os.linesep+ind): return outstr[:-len(ind)] else: