Format new/changed code when save-time formatting is enabled.
(self, plan: list[_PlanEntry])
| 1761 | # ------------------------------------------------------------------ |
| 1762 | |
| 1763 | async def _format_plan(self, plan: list[_PlanEntry]) -> list[_PlanEntry]: |
| 1764 | """Format new/changed code when save-time formatting is enabled.""" |
| 1765 | if not self._kernel.user_config["save"]["format_on_save"]: |
| 1766 | return plan |
| 1767 | |
| 1768 | existing_code = {cell.id: cell.code for cell in self._document.cells} |
| 1769 | |
| 1770 | to_format: dict[CellId_t, str] = {} |
| 1771 | for entry in plan: |
| 1772 | if entry.code is not None and entry.code != existing_code.get( |
| 1773 | entry.cell_id |
| 1774 | ): |
| 1775 | to_format[entry.cell_id] = entry.code |
| 1776 | |
| 1777 | if not to_format: |
| 1778 | return plan |
| 1779 | |
| 1780 | try: |
| 1781 | line_length = self._kernel.user_config["formatting"]["line_length"] |
| 1782 | formatter = DefaultFormatter(line_length=line_length) |
| 1783 | formatted = await formatter.format( |
| 1784 | to_format, |
| 1785 | stdin_filename=self._kernel.app_metadata.filename, |
| 1786 | ) |
| 1787 | except Exception: |
| 1788 | LOGGER.debug("Auto-format skipped: no formatter available") |
| 1789 | return plan |
| 1790 | |
| 1791 | for entry in plan: |
| 1792 | if entry.cell_id in formatted: |
| 1793 | entry.code = formatted[entry.cell_id] |
| 1794 | return plan |
| 1795 | |
| 1796 | # ------------------------------------------------------------------ |
| 1797 | # UI elements |
no test coverage detected