1"""Text related utils."""
2
3import os
4import re
5
6
7def indent(instr, nspaces=4, ntabs=0, flatten=False):
8 """Indent a string a given number of spaces or tabstops.
9
10 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
11
12 Parameters
13 ----------
14
15 instr : basestring
16 The string to be indented.
17 nspaces : int (default: 4)
18 The number of spaces to be indented.
19 ntabs : int (default: 0)
20 The number of tabs to be indented.
21 flatten : bool (default: False)
22 Whether to scrub existing indentation. If True, all lines will be
23 aligned to the same indentation. If False, existing indentation will
24 be strictly increased.
25
26 Returns
27 -------
28
29 str|unicode : string indented by ntabs and nspaces.
30
31 """
32 if instr is None:
33 return None
34 ind = "\t" * ntabs + " " * nspaces
35 pat = re.compile("^\\s*", re.MULTILINE) if flatten else re.compile("^", re.MULTILINE)
36 outstr = re.sub(pat, ind, instr)
37 if outstr.endswith(os.linesep + ind):
38 return outstr[: -len(ind)]
39 return outstr