Replace magics within body of cell. Note that 'src' will already have been processed by IPython's TransformerManager().transform_cell. Example, this get_ipython().run_line_magic('matplotlib', 'inline') 'foo' becomes "5e67db56d490fd39" 'foo' T
(src: str)
| 262 | |
| 263 | |
| 264 | def replace_magics(src: str) -> tuple[str, list[Replacement]]: |
| 265 | """Replace magics within body of cell. |
| 266 | |
| 267 | Note that 'src' will already have been processed by IPython's |
| 268 | TransformerManager().transform_cell. |
| 269 | |
| 270 | Example, this |
| 271 | |
| 272 | get_ipython().run_line_magic('matplotlib', 'inline') |
| 273 | 'foo' |
| 274 | |
| 275 | becomes |
| 276 | |
| 277 | "5e67db56d490fd39" |
| 278 | 'foo' |
| 279 | |
| 280 | The replacement, along with the transformed code, are returned. |
| 281 | """ |
| 282 | replacements = [] |
| 283 | existing_tokens: set[str] = set() |
| 284 | magic_finder = MagicFinder() |
| 285 | magic_finder.visit(ast.parse(src)) |
| 286 | new_srcs = [] |
| 287 | for i, line in enumerate(src.split("\n"), start=1): |
| 288 | if i in magic_finder.magics: |
| 289 | offsets_and_magics = magic_finder.magics[i] |
| 290 | if len(offsets_and_magics) != 1: # pragma: nocover |
| 291 | raise AssertionError( |
| 292 | f"Expecting one magic per line, got: {offsets_and_magics}\n" |
| 293 | "Please report a bug on https://github.com/psf/black/issues." |
| 294 | ) |
| 295 | col_offset, magic = ( |
| 296 | offsets_and_magics[0].col_offset, |
| 297 | offsets_and_magics[0].magic, |
| 298 | ) |
| 299 | mask = get_token(src, magic, existing_tokens) |
| 300 | replacements.append(Replacement(mask=mask, src=magic)) |
| 301 | existing_tokens.add(mask) |
| 302 | line = line[:col_offset] + mask |
| 303 | new_srcs.append(line) |
| 304 | return "\n".join(new_srcs), replacements |
| 305 | |
| 306 | |
| 307 | def unmask_cell(src: str, replacements: list[Replacement]) -> str: |
no test coverage detected