Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3....
File: textwrap.py
"""Text wrapping and filling.
[0] Fix | Delete
"""
[1] Fix | Delete
[2] Fix | Delete
# Copyright (C) 1999-2001 Gregory P. Ward.
[3] Fix | Delete
# Copyright (C) 2002, 2003 Python Software Foundation.
[4] Fix | Delete
# Written by Greg Ward <gward@python.net>
[5] Fix | Delete
[6] Fix | Delete
import re
[7] Fix | Delete
[8] Fix | Delete
__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
[9] Fix | Delete
[10] Fix | Delete
# Hardcode the recognized whitespace characters to the US-ASCII
[11] Fix | Delete
# whitespace characters. The main reason for doing this is that
[12] Fix | Delete
# some Unicode spaces (like \u00a0) are non-breaking whitespaces.
[13] Fix | Delete
_whitespace = '\t\n\x0b\x0c\r '
[14] Fix | Delete
[15] Fix | Delete
class TextWrapper:
[16] Fix | Delete
"""
[17] Fix | Delete
Object for wrapping/filling text. The public interface consists of
[18] Fix | Delete
the wrap() and fill() methods; the other methods are just there for
[19] Fix | Delete
subclasses to override in order to tweak the default behaviour.
[20] Fix | Delete
If you want to completely replace the main wrapping algorithm,
[21] Fix | Delete
you'll probably have to override _wrap_chunks().
[22] Fix | Delete
[23] Fix | Delete
Several instance attributes control various aspects of wrapping:
[24] Fix | Delete
width (default: 70)
[25] Fix | Delete
the maximum width of wrapped lines (unless break_long_words
[26] Fix | Delete
is false)
[27] Fix | Delete
initial_indent (default: "")
[28] Fix | Delete
string that will be prepended to the first line of wrapped
[29] Fix | Delete
output. Counts towards the line's width.
[30] Fix | Delete
subsequent_indent (default: "")
[31] Fix | Delete
string that will be prepended to all lines save the first
[32] Fix | Delete
of wrapped output; also counts towards each line's width.
[33] Fix | Delete
expand_tabs (default: true)
[34] Fix | Delete
Expand tabs in input text to spaces before further processing.
[35] Fix | Delete
Each tab will become 0 .. 'tabsize' spaces, depending on its position
[36] Fix | Delete
in its line. If false, each tab is treated as a single character.
[37] Fix | Delete
tabsize (default: 8)
[38] Fix | Delete
Expand tabs in input text to 0 .. 'tabsize' spaces, unless
[39] Fix | Delete
'expand_tabs' is false.
[40] Fix | Delete
replace_whitespace (default: true)
[41] Fix | Delete
Replace all whitespace characters in the input text by spaces
[42] Fix | Delete
after tab expansion. Note that if expand_tabs is false and
[43] Fix | Delete
replace_whitespace is true, every tab will be converted to a
[44] Fix | Delete
single space!
[45] Fix | Delete
fix_sentence_endings (default: false)
[46] Fix | Delete
Ensure that sentence-ending punctuation is always followed
[47] Fix | Delete
by two spaces. Off by default because the algorithm is
[48] Fix | Delete
(unavoidably) imperfect.
[49] Fix | Delete
break_long_words (default: true)
[50] Fix | Delete
Break words longer than 'width'. If false, those words will not
[51] Fix | Delete
be broken, and some lines might be longer than 'width'.
[52] Fix | Delete
break_on_hyphens (default: true)
[53] Fix | Delete
Allow breaking hyphenated words. If true, wrapping will occur
[54] Fix | Delete
preferably on whitespaces and right after hyphens part of
[55] Fix | Delete
compound words.
[56] Fix | Delete
drop_whitespace (default: true)
[57] Fix | Delete
Drop leading and trailing whitespace from lines.
[58] Fix | Delete
max_lines (default: None)
[59] Fix | Delete
Truncate wrapped lines.
[60] Fix | Delete
placeholder (default: ' [...]')
[61] Fix | Delete
Append to the last line of truncated text.
[62] Fix | Delete
"""
[63] Fix | Delete
[64] Fix | Delete
unicode_whitespace_trans = {}
[65] Fix | Delete
uspace = ord(' ')
[66] Fix | Delete
for x in _whitespace:
[67] Fix | Delete
unicode_whitespace_trans[ord(x)] = uspace
[68] Fix | Delete
[69] Fix | Delete
# This funky little regex is just the trick for splitting
[70] Fix | Delete
# text up into word-wrappable chunks. E.g.
[71] Fix | Delete
# "Hello there -- you goof-ball, use the -b option!"
[72] Fix | Delete
# splits into
[73] Fix | Delete
# Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
[74] Fix | Delete
# (after stripping out empty strings).
[75] Fix | Delete
word_punct = r'[\w!"\'&.,?]'
[76] Fix | Delete
letter = r'[^\d\W]'
[77] Fix | Delete
whitespace = r'[%s]' % re.escape(_whitespace)
[78] Fix | Delete
nowhitespace = '[^' + whitespace[1:]
[79] Fix | Delete
wordsep_re = re.compile(r'''
[80] Fix | Delete
( # any whitespace
[81] Fix | Delete
%(ws)s+
[82] Fix | Delete
| # em-dash between words
[83] Fix | Delete
(?<=%(wp)s) -{2,} (?=\w)
[84] Fix | Delete
| # word, possibly hyphenated
[85] Fix | Delete
%(nws)s+? (?:
[86] Fix | Delete
# hyphenated word
[87] Fix | Delete
-(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
[88] Fix | Delete
(?= %(lt)s -? %(lt)s)
[89] Fix | Delete
| # end of word
[90] Fix | Delete
(?=%(ws)s|\Z)
[91] Fix | Delete
| # em-dash
[92] Fix | Delete
(?<=%(wp)s) (?=-{2,}\w)
[93] Fix | Delete
)
[94] Fix | Delete
)''' % {'wp': word_punct, 'lt': letter,
[95] Fix | Delete
'ws': whitespace, 'nws': nowhitespace},
[96] Fix | Delete
re.VERBOSE)
[97] Fix | Delete
del word_punct, letter, nowhitespace
[98] Fix | Delete
[99] Fix | Delete
# This less funky little regex just split on recognized spaces. E.g.
[100] Fix | Delete
# "Hello there -- you goof-ball, use the -b option!"
[101] Fix | Delete
# splits into
[102] Fix | Delete
# Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
[103] Fix | Delete
wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
[104] Fix | Delete
del whitespace
[105] Fix | Delete
[106] Fix | Delete
# XXX this is not locale- or charset-aware -- string.lowercase
[107] Fix | Delete
# is US-ASCII only (and therefore English-only)
[108] Fix | Delete
sentence_end_re = re.compile(r'[a-z]' # lowercase letter
[109] Fix | Delete
r'[\.\!\?]' # sentence-ending punct.
[110] Fix | Delete
r'[\"\']?' # optional end-of-quote
[111] Fix | Delete
r'\Z') # end of chunk
[112] Fix | Delete
[113] Fix | Delete
def __init__(self,
[114] Fix | Delete
width=70,
[115] Fix | Delete
initial_indent="",
[116] Fix | Delete
subsequent_indent="",
[117] Fix | Delete
expand_tabs=True,
[118] Fix | Delete
replace_whitespace=True,
[119] Fix | Delete
fix_sentence_endings=False,
[120] Fix | Delete
break_long_words=True,
[121] Fix | Delete
drop_whitespace=True,
[122] Fix | Delete
break_on_hyphens=True,
[123] Fix | Delete
tabsize=8,
[124] Fix | Delete
*,
[125] Fix | Delete
max_lines=None,
[126] Fix | Delete
placeholder=' [...]'):
[127] Fix | Delete
self.width = width
[128] Fix | Delete
self.initial_indent = initial_indent
[129] Fix | Delete
self.subsequent_indent = subsequent_indent
[130] Fix | Delete
self.expand_tabs = expand_tabs
[131] Fix | Delete
self.replace_whitespace = replace_whitespace
[132] Fix | Delete
self.fix_sentence_endings = fix_sentence_endings
[133] Fix | Delete
self.break_long_words = break_long_words
[134] Fix | Delete
self.drop_whitespace = drop_whitespace
[135] Fix | Delete
self.break_on_hyphens = break_on_hyphens
[136] Fix | Delete
self.tabsize = tabsize
[137] Fix | Delete
self.max_lines = max_lines
[138] Fix | Delete
self.placeholder = placeholder
[139] Fix | Delete
[140] Fix | Delete
[141] Fix | Delete
# -- Private methods -----------------------------------------------
[142] Fix | Delete
# (possibly useful for subclasses to override)
[143] Fix | Delete
[144] Fix | Delete
def _munge_whitespace(self, text):
[145] Fix | Delete
"""_munge_whitespace(text : string) -> string
[146] Fix | Delete
[147] Fix | Delete
Munge whitespace in text: expand tabs and convert all other
[148] Fix | Delete
whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
[149] Fix | Delete
becomes " foo bar baz".
[150] Fix | Delete
"""
[151] Fix | Delete
if self.expand_tabs:
[152] Fix | Delete
text = text.expandtabs(self.tabsize)
[153] Fix | Delete
if self.replace_whitespace:
[154] Fix | Delete
text = text.translate(self.unicode_whitespace_trans)
[155] Fix | Delete
return text
[156] Fix | Delete
[157] Fix | Delete
[158] Fix | Delete
def _split(self, text):
[159] Fix | Delete
"""_split(text : string) -> [string]
[160] Fix | Delete
[161] Fix | Delete
Split the text to wrap into indivisible chunks. Chunks are
[162] Fix | Delete
not quite the same as words; see _wrap_chunks() for full
[163] Fix | Delete
details. As an example, the text
[164] Fix | Delete
Look, goof-ball -- use the -b option!
[165] Fix | Delete
breaks into the following chunks:
[166] Fix | Delete
'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
[167] Fix | Delete
'use', ' ', 'the', ' ', '-b', ' ', 'option!'
[168] Fix | Delete
if break_on_hyphens is True, or in:
[169] Fix | Delete
'Look,', ' ', 'goof-ball', ' ', '--', ' ',
[170] Fix | Delete
'use', ' ', 'the', ' ', '-b', ' ', option!'
[171] Fix | Delete
otherwise.
[172] Fix | Delete
"""
[173] Fix | Delete
if self.break_on_hyphens is True:
[174] Fix | Delete
chunks = self.wordsep_re.split(text)
[175] Fix | Delete
else:
[176] Fix | Delete
chunks = self.wordsep_simple_re.split(text)
[177] Fix | Delete
chunks = [c for c in chunks if c]
[178] Fix | Delete
return chunks
[179] Fix | Delete
[180] Fix | Delete
def _fix_sentence_endings(self, chunks):
[181] Fix | Delete
"""_fix_sentence_endings(chunks : [string])
[182] Fix | Delete
[183] Fix | Delete
Correct for sentence endings buried in 'chunks'. Eg. when the
[184] Fix | Delete
original text contains "... foo.\\nBar ...", munge_whitespace()
[185] Fix | Delete
and split() will convert that to [..., "foo.", " ", "Bar", ...]
[186] Fix | Delete
which has one too few spaces; this method simply changes the one
[187] Fix | Delete
space to two.
[188] Fix | Delete
"""
[189] Fix | Delete
i = 0
[190] Fix | Delete
patsearch = self.sentence_end_re.search
[191] Fix | Delete
while i < len(chunks)-1:
[192] Fix | Delete
if chunks[i+1] == " " and patsearch(chunks[i]):
[193] Fix | Delete
chunks[i+1] = " "
[194] Fix | Delete
i += 2
[195] Fix | Delete
else:
[196] Fix | Delete
i += 1
[197] Fix | Delete
[198] Fix | Delete
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
[199] Fix | Delete
"""_handle_long_word(chunks : [string],
[200] Fix | Delete
cur_line : [string],
[201] Fix | Delete
cur_len : int, width : int)
[202] Fix | Delete
[203] Fix | Delete
Handle a chunk of text (most likely a word, not whitespace) that
[204] Fix | Delete
is too long to fit in any line.
[205] Fix | Delete
"""
[206] Fix | Delete
# Figure out when indent is larger than the specified width, and make
[207] Fix | Delete
# sure at least one character is stripped off on every pass
[208] Fix | Delete
if width < 1:
[209] Fix | Delete
space_left = 1
[210] Fix | Delete
else:
[211] Fix | Delete
space_left = width - cur_len
[212] Fix | Delete
[213] Fix | Delete
# If we're allowed to break long words, then do so: put as much
[214] Fix | Delete
# of the next chunk onto the current line as will fit.
[215] Fix | Delete
if self.break_long_words:
[216] Fix | Delete
cur_line.append(reversed_chunks[-1][:space_left])
[217] Fix | Delete
reversed_chunks[-1] = reversed_chunks[-1][space_left:]
[218] Fix | Delete
[219] Fix | Delete
# Otherwise, we have to preserve the long word intact. Only add
[220] Fix | Delete
# it to the current line if there's nothing already there --
[221] Fix | Delete
# that minimizes how much we violate the width constraint.
[222] Fix | Delete
elif not cur_line:
[223] Fix | Delete
cur_line.append(reversed_chunks.pop())
[224] Fix | Delete
[225] Fix | Delete
# If we're not allowed to break long words, and there's already
[226] Fix | Delete
# text on the current line, do nothing. Next time through the
[227] Fix | Delete
# main loop of _wrap_chunks(), we'll wind up here again, but
[228] Fix | Delete
# cur_len will be zero, so the next line will be entirely
[229] Fix | Delete
# devoted to the long word that we can't handle right now.
[230] Fix | Delete
[231] Fix | Delete
def _wrap_chunks(self, chunks):
[232] Fix | Delete
"""_wrap_chunks(chunks : [string]) -> [string]
[233] Fix | Delete
[234] Fix | Delete
Wrap a sequence of text chunks and return a list of lines of
[235] Fix | Delete
length 'self.width' or less. (If 'break_long_words' is false,
[236] Fix | Delete
some lines may be longer than this.) Chunks correspond roughly
[237] Fix | Delete
to words and the whitespace between them: each chunk is
[238] Fix | Delete
indivisible (modulo 'break_long_words'), but a line break can
[239] Fix | Delete
come between any two chunks. Chunks should not have internal
[240] Fix | Delete
whitespace; ie. a chunk is either all whitespace or a "word".
[241] Fix | Delete
Whitespace chunks will be removed from the beginning and end of
[242] Fix | Delete
lines, but apart from that whitespace is preserved.
[243] Fix | Delete
"""
[244] Fix | Delete
lines = []
[245] Fix | Delete
if self.width <= 0:
[246] Fix | Delete
raise ValueError("invalid width %r (must be > 0)" % self.width)
[247] Fix | Delete
if self.max_lines is not None:
[248] Fix | Delete
if self.max_lines > 1:
[249] Fix | Delete
indent = self.subsequent_indent
[250] Fix | Delete
else:
[251] Fix | Delete
indent = self.initial_indent
[252] Fix | Delete
if len(indent) + len(self.placeholder.lstrip()) > self.width:
[253] Fix | Delete
raise ValueError("placeholder too large for max width")
[254] Fix | Delete
[255] Fix | Delete
# Arrange in reverse order so items can be efficiently popped
[256] Fix | Delete
# from a stack of chucks.
[257] Fix | Delete
chunks.reverse()
[258] Fix | Delete
[259] Fix | Delete
while chunks:
[260] Fix | Delete
[261] Fix | Delete
# Start the list of chunks that will make up the current line.
[262] Fix | Delete
# cur_len is just the length of all the chunks in cur_line.
[263] Fix | Delete
cur_line = []
[264] Fix | Delete
cur_len = 0
[265] Fix | Delete
[266] Fix | Delete
# Figure out which static string will prefix this line.
[267] Fix | Delete
if lines:
[268] Fix | Delete
indent = self.subsequent_indent
[269] Fix | Delete
else:
[270] Fix | Delete
indent = self.initial_indent
[271] Fix | Delete
[272] Fix | Delete
# Maximum width for this line.
[273] Fix | Delete
width = self.width - len(indent)
[274] Fix | Delete
[275] Fix | Delete
# First chunk on line is whitespace -- drop it, unless this
[276] Fix | Delete
# is the very beginning of the text (ie. no lines started yet).
[277] Fix | Delete
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
[278] Fix | Delete
del chunks[-1]
[279] Fix | Delete
[280] Fix | Delete
while chunks:
[281] Fix | Delete
l = len(chunks[-1])
[282] Fix | Delete
[283] Fix | Delete
# Can at least squeeze this chunk onto the current line.
[284] Fix | Delete
if cur_len + l <= width:
[285] Fix | Delete
cur_line.append(chunks.pop())
[286] Fix | Delete
cur_len += l
[287] Fix | Delete
[288] Fix | Delete
# Nope, this line is full.
[289] Fix | Delete
else:
[290] Fix | Delete
break
[291] Fix | Delete
[292] Fix | Delete
# The current line is full, and the next chunk is too big to
[293] Fix | Delete
# fit on *any* line (not just this one).
[294] Fix | Delete
if chunks and len(chunks[-1]) > width:
[295] Fix | Delete
self._handle_long_word(chunks, cur_line, cur_len, width)
[296] Fix | Delete
cur_len = sum(map(len, cur_line))
[297] Fix | Delete
[298] Fix | Delete
# If the last chunk on this line is all whitespace, drop it.
[299] Fix | Delete
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
[300] Fix | Delete
cur_len -= len(cur_line[-1])
[301] Fix | Delete
del cur_line[-1]
[302] Fix | Delete
[303] Fix | Delete
if cur_line:
[304] Fix | Delete
if (self.max_lines is None or
[305] Fix | Delete
len(lines) + 1 < self.max_lines or
[306] Fix | Delete
(not chunks or
[307] Fix | Delete
self.drop_whitespace and
[308] Fix | Delete
len(chunks) == 1 and
[309] Fix | Delete
not chunks[0].strip()) and cur_len <= width):
[310] Fix | Delete
# Convert current line back to a string and store it in
[311] Fix | Delete
# list of all lines (return value).
[312] Fix | Delete
lines.append(indent + ''.join(cur_line))
[313] Fix | Delete
else:
[314] Fix | Delete
while cur_line:
[315] Fix | Delete
if (cur_line[-1].strip() and
[316] Fix | Delete
cur_len + len(self.placeholder) <= width):
[317] Fix | Delete
cur_line.append(self.placeholder)
[318] Fix | Delete
lines.append(indent + ''.join(cur_line))
[319] Fix | Delete
break
[320] Fix | Delete
cur_len -= len(cur_line[-1])
[321] Fix | Delete
del cur_line[-1]
[322] Fix | Delete
else:
[323] Fix | Delete
if lines:
[324] Fix | Delete
prev_line = lines[-1].rstrip()
[325] Fix | Delete
if (len(prev_line) + len(self.placeholder) <=
[326] Fix | Delete
self.width):
[327] Fix | Delete
lines[-1] = prev_line + self.placeholder
[328] Fix | Delete
break
[329] Fix | Delete
lines.append(indent + self.placeholder.lstrip())
[330] Fix | Delete
break
[331] Fix | Delete
[332] Fix | Delete
return lines
[333] Fix | Delete
[334] Fix | Delete
def _split_chunks(self, text):
[335] Fix | Delete
text = self._munge_whitespace(text)
[336] Fix | Delete
return self._split(text)
[337] Fix | Delete
[338] Fix | Delete
# -- Public interface ----------------------------------------------
[339] Fix | Delete
[340] Fix | Delete
def wrap(self, text):
[341] Fix | Delete
"""wrap(text : string) -> [string]
[342] Fix | Delete
[343] Fix | Delete
Reformat the single paragraph in 'text' so it fits in lines of
[344] Fix | Delete
no more than 'self.width' columns, and return a list of wrapped
[345] Fix | Delete
lines. Tabs in 'text' are expanded with string.expandtabs(),
[346] Fix | Delete
and all other whitespace characters (including newline) are
[347] Fix | Delete
converted to space.
[348] Fix | Delete
"""
[349] Fix | Delete
chunks = self._split_chunks(text)
[350] Fix | Delete
if self.fix_sentence_endings:
[351] Fix | Delete
self._fix_sentence_endings(chunks)
[352] Fix | Delete
return self._wrap_chunks(chunks)
[353] Fix | Delete
[354] Fix | Delete
def fill(self, text):
[355] Fix | Delete
"""fill(text : string) -> string
[356] Fix | Delete
[357] Fix | Delete
Reformat the single paragraph in 'text' to fit in lines of no
[358] Fix | Delete
more than 'self.width' columns, and return a new string
[359] Fix | Delete
containing the entire wrapped paragraph.
[360] Fix | Delete
"""
[361] Fix | Delete
return "\n".join(self.wrap(text))
[362] Fix | Delete
[363] Fix | Delete
[364] Fix | Delete
# -- Convenience interface ---------------------------------------------
[365] Fix | Delete
[366] Fix | Delete
def wrap(text, width=70, **kwargs):
[367] Fix | Delete
"""Wrap a single paragraph of text, returning a list of wrapped lines.
[368] Fix | Delete
[369] Fix | Delete
Reformat the single paragraph in 'text' so it fits in lines of no
[370] Fix | Delete
more than 'width' columns, and return a list of wrapped lines. By
[371] Fix | Delete
default, tabs in 'text' are expanded with string.expandtabs(), and
[372] Fix | Delete
all other whitespace characters (including newline) are converted to
[373] Fix | Delete
space. See TextWrapper class for available keyword args to customize
[374] Fix | Delete
wrapping behaviour.
[375] Fix | Delete
"""
[376] Fix | Delete
w = TextWrapper(width=width, **kwargs)
[377] Fix | Delete
return w.wrap(text)
[378] Fix | Delete
[379] Fix | Delete
def fill(text, width=70, **kwargs):
[380] Fix | Delete
"""Fill a single paragraph of text, returning a new string.
[381] Fix | Delete
[382] Fix | Delete
Reformat the single paragraph in 'text' to fit in lines of no more
[383] Fix | Delete
than 'width' columns, and return a new string containing the entire
[384] Fix | Delete
wrapped paragraph. As with wrap(), tabs are expanded and other
[385] Fix | Delete
whitespace characters converted to space. See TextWrapper class for
[386] Fix | Delete
available keyword args to customize wrapping behaviour.
[387] Fix | Delete
"""
[388] Fix | Delete
w = TextWrapper(width=width, **kwargs)
[389] Fix | Delete
return w.fill(text)
[390] Fix | Delete
[391] Fix | Delete
def shorten(text, width, **kwargs):
[392] Fix | Delete
"""Collapse and truncate the given text to fit in the given width.
[393] Fix | Delete
[394] Fix | Delete
The text first has its whitespace collapsed. If it then fits in
[395] Fix | Delete
the *width*, it is returned as is. Otherwise, as many words
[396] Fix | Delete
as possible are joined and then the placeholder is appended::
[397] Fix | Delete
[398] Fix | Delete
>>> textwrap.shorten("Hello world!", width=12)
[399] Fix | Delete
'Hello world!'
[400] Fix | Delete
>>> textwrap.shorten("Hello world!", width=11)
[401] Fix | Delete
'Hello [...]'
[402] Fix | Delete
"""
[403] Fix | Delete
w = TextWrapper(width=width, max_lines=1, **kwargs)
[404] Fix | Delete
return w.fill(' '.join(text.strip().split()))
[405] Fix | Delete
[406] Fix | Delete
[407] Fix | Delete
# -- Loosely related functionality -------------------------------------
[408] Fix | Delete
[409] Fix | Delete
_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
[410] Fix | Delete
_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
[411] Fix | Delete
[412] Fix | Delete
def dedent(text):
[413] Fix | Delete
"""Remove any common leading whitespace from every line in `text`.
[414] Fix | Delete
[415] Fix | Delete
This can be used to make triple-quoted strings line up with the left
[416] Fix | Delete
edge of the display, while still presenting them in the source code
[417] Fix | Delete
in indented form.
[418] Fix | Delete
[419] Fix | Delete
Note that tabs and spaces are both treated as whitespace, but they
[420] Fix | Delete
are not equal: the lines " hello" and "\\thello" are
[421] Fix | Delete
considered to have no common leading whitespace.
[422] Fix | Delete
[423] Fix | Delete
Entirely blank lines are normalized to a newline character.
[424] Fix | Delete
"""
[425] Fix | Delete
# Look for the longest leading string of spaces and tabs common to
[426] Fix | Delete
# all lines.
[427] Fix | Delete
margin = None
[428] Fix | Delete
text = _whitespace_only_re.sub('', text)
[429] Fix | Delete
indents = _leading_whitespace_re.findall(text)
[430] Fix | Delete
for indent in indents:
[431] Fix | Delete
if margin is None:
[432] Fix | Delete
margin = indent
[433] Fix | Delete
[434] Fix | Delete
# Current line more deeply indented than previous winner:
[435] Fix | Delete
# no change (previous winner is still on top).
[436] Fix | Delete
elif indent.startswith(margin):
[437] Fix | Delete
pass
[438] Fix | Delete
[439] Fix | Delete
# Current line consistent with and no deeper than previous winner:
[440] Fix | Delete
# it's the new winner.
[441] Fix | Delete
elif margin.startswith(indent):
[442] Fix | Delete
margin = indent
[443] Fix | Delete
[444] Fix | Delete
# Find the largest common whitespace between current line and previous
[445] Fix | Delete
# winner.
[446] Fix | Delete
else:
[447] Fix | Delete
for i, (x, y) in enumerate(zip(margin, indent)):
[448] Fix | Delete
if x != y:
[449] Fix | Delete
margin = margin[:i]
[450] Fix | Delete
break
[451] Fix | Delete
[452] Fix | Delete
# sanity check (testing/debugging only)
[453] Fix | Delete
if 0 and margin:
[454] Fix | Delete
for line in text.split("\n"):
[455] Fix | Delete
assert not line or line.startswith(margin), \
[456] Fix | Delete
"line = %r, margin = %r" % (line, margin)
[457] Fix | Delete
[458] Fix | Delete
if margin:
[459] Fix | Delete
text = re.sub(r'(?m)^' + margin, '', text)
[460] Fix | Delete
return text
[461] Fix | Delete
[462] Fix | Delete
[463] Fix | Delete
def indent(text, prefix, predicate=None):
[464] Fix | Delete
"""Adds 'prefix' to the beginning of selected lines in 'text'.
[465] Fix | Delete
[466] Fix | Delete
If 'predicate' is provided, 'prefix' will only be added to the lines
[467] Fix | Delete
where 'predicate(line)' is True. If 'predicate' is not provided,
[468] Fix | Delete
it will default to adding 'prefix' to all non-empty lines that do not
[469] Fix | Delete
consist solely of whitespace characters.
[470] Fix | Delete
"""
[471] Fix | Delete
if predicate is None:
[472] Fix | Delete
def predicate(line):
[473] Fix | Delete
return line.strip()
[474] Fix | Delete
[475] Fix | Delete
def prefixed_lines():
[476] Fix | Delete
for line in text.splitlines(True):
[477] Fix | Delete
yield (prefix + line if predicate(line) else line)
[478] Fix | Delete
return ''.join(prefixed_lines())
[479] Fix | Delete
[480] Fix | Delete
[481] Fix | Delete
if __name__ == "__main__":
[482] Fix | Delete
#print dedent("\tfoo\n\tbar")
[483] Fix | Delete
#print dedent(" \thello there\n \t how are you?")
[484] Fix | Delete
print(dedent("Hello there.\n This is indented."))
[485] Fix | Delete
[486] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function