padding property

This commit is contained in:
Will McGugan 2025-06-22 15:10:56 +01:00
parent 2b0234ee83
commit d5f087045d
2 changed files with 18 additions and 3 deletions

View file

@ -11,10 +11,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Removed `typing_extensions` from runtime dependencies https://github.com/Textualize/rich/pull/3763
- Live objects (including Progress) may now be nested https://github.com/Textualize/rich/pull/3768
- Added padding property to Syntax which returns a tuple of four integers
### Fixed
- Fixed extraction of recursive exceptions https://github.com/Textualize/rich/pull/3772
- Fixed padding applied to Syntax
## [14.0.0] - 2025-03-30

View file

@ -293,11 +293,20 @@ class Syntax(JupyterMixin):
Style(bgcolor=background_color) if background_color else Style()
)
self.indent_guides = indent_guides
self.padding = padding
self._padding = Padding.unpack(padding)
self._theme = self.get_theme(theme)
self._stylized_ranges: List[_SyntaxHighlightRange] = []
@property
def padding(self) -> tuple[int, int, int, int]:
"""Padding around the Syntax."""
return self._padding
@padding.setter
def padding(self, padding: PaddingDimensions) -> None:
self._padding = Padding.unpack(padding)
@classmethod
def from_path(
cls,
@ -607,7 +616,7 @@ class Syntax(JupyterMixin):
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> "Measurement":
_, right, _, left = Padding.unpack(self.padding)
_, right, _, left = self.padding
padding = left + right
if self.code_width is not None:
width = self.code_width + self._numbers_column_width + padding + 1
@ -626,7 +635,7 @@ class Syntax(JupyterMixin):
self, console: Console, options: ConsoleOptions
) -> RenderResult:
segments = Segments(self._get_syntax(console, options))
if self.padding:
if any(self.padding):
yield Padding(segments, style=self._get_base_style(), pad=self.padding)
else:
yield segments
@ -640,15 +649,19 @@ class Syntax(JupyterMixin):
Get the Segments for the Syntax object, excluding any vertical/horizontal padding
"""
transparent_background = self._get_base_style().transparent_background
_pad_top, pad_right, _pad_bottom, pad_left = self.padding
horizontal_padding = pad_left + pad_right
code_width = (
(
(options.max_width - self._numbers_column_width - 1)
if self.line_numbers
else options.max_width
)
- horizontal_padding
if self.code_width is None
else self.code_width
)
code_width = max(0, code_width)
ends_on_nl, processed_code = self._process_code(self.code)
text = self.highlight(processed_code, self.line_range)