summaryrefslogtreecommitdiff
path: root/bs4/formatter.py
diff options
context:
space:
mode:
authorLeonard Richardson <leonardr@segfault.org>2021-12-21 12:57:04 -0500
committerLeonard Richardson <leonardr@segfault.org>2021-12-21 12:57:04 -0500
commit3ac8524a1263f170ae0a9096d255d3e28aa76340 (patch)
treee6aab155135f553f3043a425dcf8e61884091919 /bs4/formatter.py
parent792a9e485e1b110534345a4f96fd65099879421e (diff)
It's now possible to customize the way output is indented by
providing a value for the 'indent' argument to the Formatter constructor. The 'indent' argument works very similarly to the argument of the same name in the Python standard library's json.dump() method. [bug=1955497]
Diffstat (limited to 'bs4/formatter.py')
-rw-r--r--bs4/formatter.py22
1 files changed, 21 insertions, 1 deletions
diff --git a/bs4/formatter.py b/bs4/formatter.py
index 3bd9f85..65e57b5 100644
--- a/bs4/formatter.py
+++ b/bs4/formatter.py
@@ -49,7 +49,7 @@ class Formatter(EntitySubstitution):
def __init__(
self, language=None, entity_substitution=None,
void_element_close_prefix='/', cdata_containing_tags=None,
- empty_attributes_are_booleans=False,
+ empty_attributes_are_booleans=False, indent=1,
):
"""Constructor.
@@ -69,6 +69,15 @@ class Formatter(EntitySubstitution):
:param blank_attributes_are_booleans: Render attributes whose value
is the empty string as HTML-style boolean attributes.
(Attributes whose value is None are always rendered this way.)
+
+ :param indent: If indent is a non-negative integer or string,
+ then the contents of elements will be indented
+ appropriately when pretty-printing. An indent level of 0,
+ negative, or "" will only insert newlines. Using a
+ positive integer indent indents that many spaces per
+ level. If indent is a string (such as "\t"), that string
+ is used to indent each level. The default behavior to
+ indent one space per level.
"""
self.language = language
self.entity_substitution = entity_substitution
@@ -77,6 +86,17 @@ class Formatter(EntitySubstitution):
language, cdata_containing_tags, 'cdata_containing_tags'
)
self.empty_attributes_are_booleans=empty_attributes_are_booleans
+ if indent is None:
+ indent = 0
+ if isinstance(indent, int):
+ if indent < 0:
+ indent = 0
+ indent = ' ' * indent
+ elif isinstance(indent, str):
+ indent = indent
+ else:
+ indent = ' '
+ self.indent = indent
def substitute(self, ns):
"""Process a string that needs to undergo entity substitution.