Skip to content

Commit f4707ad

Browse files
authored
Merge pull request #4870 from felixxm/issue-dedent
Fixed `dedent` for tab indent.
2 parents 2ec3db8 + b99272c commit f4707ad

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

rest_framework/utils/formatting.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,23 +32,18 @@ def dedent(content):
3232
unindented text on the initial line.
3333
"""
3434
content = force_text(content)
35-
whitespace_counts = [
36-
len(line) - len(line.lstrip(' '))
37-
for line in content.splitlines()[1:] if line.lstrip()
38-
]
39-
tab_counts = [
40-
len(line) - len(line.lstrip('\t'))
41-
for line in content.splitlines()[1:] if line.lstrip()
42-
]
35+
lines = [line for line in content.splitlines()[1:] if line.lstrip()]
4336

4437
# unindent the content if needed
45-
if whitespace_counts:
46-
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
47-
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
48-
elif tab_counts:
49-
whitespace_pattern = '^' + ('\t' * min(whitespace_counts))
50-
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
51-
38+
if lines:
39+
whitespace_counts = min([len(line) - len(line.lstrip(' ')) for line in lines])
40+
tab_counts = min([len(line) - len(line.lstrip('\t')) for line in lines])
41+
if whitespace_counts:
42+
whitespace_pattern = '^' + (' ' * whitespace_counts)
43+
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
44+
elif tab_counts:
45+
whitespace_pattern = '^' + ('\t' * tab_counts)
46+
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
5247
return content.strip()
5348

5449

tests/test_description.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,8 @@ def test_markdown(self):
124124

125125

126126
def test_dedent_tabs():
127-
assert dedent("\tfirst string\n\n\tsecond string") == 'first string\n\n\tsecond string'
127+
result = 'first string\n\nsecond string'
128+
assert dedent(" first string\n\n second string") == result
129+
assert dedent("first string\n\n second string") == result
130+
assert dedent("\tfirst string\n\n\tsecond string") == result
131+
assert dedent("first string\n\n\tsecond string") == result

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy