Format code in given cell of Jupyter notebook. General idea is: - if cell has trailing semicolon, remove it; - if cell has IPython magics, mask them; - format cell; - reinstate IPython magics; - reinstate trailing semicolon (if originally present); - strip t
(src: str, *, fast: bool, mode: Mode)
| 1128 | |
| 1129 | |
| 1130 | def format_cell(src: str, *, fast: bool, mode: Mode) -> str: |
| 1131 | """Format code in given cell of Jupyter notebook. |
| 1132 | |
| 1133 | General idea is: |
| 1134 | |
| 1135 | - if cell has trailing semicolon, remove it; |
| 1136 | - if cell has IPython magics, mask them; |
| 1137 | - format cell; |
| 1138 | - reinstate IPython magics; |
| 1139 | - reinstate trailing semicolon (if originally present); |
| 1140 | - strip trailing newlines. |
| 1141 | |
| 1142 | Cells with syntax errors will not be processed, as they |
| 1143 | could potentially be automagics or multi-line magics, which |
| 1144 | are currently not supported. |
| 1145 | """ |
| 1146 | validate_cell(src, mode) |
| 1147 | src_without_trailing_semicolon, has_trailing_semicolon = remove_trailing_semicolon( |
| 1148 | src |
| 1149 | ) |
| 1150 | try: |
| 1151 | masked_src, replacements = mask_cell(src_without_trailing_semicolon) |
| 1152 | except SyntaxError: |
| 1153 | raise NothingChanged from None |
| 1154 | masked_dst = format_str(masked_src, mode=mode) |
| 1155 | if not fast: |
| 1156 | check_stability_and_equivalence(masked_src, masked_dst, mode=mode) |
| 1157 | dst_without_trailing_semicolon = unmask_cell(masked_dst, replacements) |
| 1158 | dst = put_trailing_semicolon_back( |
| 1159 | dst_without_trailing_semicolon, has_trailing_semicolon |
| 1160 | ) |
| 1161 | dst = dst.rstrip("\n") |
| 1162 | if dst == src: |
| 1163 | raise NothingChanged from None |
| 1164 | return dst |
| 1165 | |
| 1166 | |
| 1167 | def validate_metadata(nb: MutableMapping[str, Any]) -> None: |