Return the concatenated executable code from all non-verbatim ``.. ipython::`` blocks in a single .rst document, in order.
(rst_text)
| 32 | |
| 33 | |
| 34 | def _extract_ipython_code(rst_text): |
| 35 | """Return the concatenated executable code from all non-verbatim |
| 36 | ``.. ipython::`` blocks in a single .rst document, in order.""" |
| 37 | lines = rst_text.splitlines() |
| 38 | code_chunks = [] |
| 39 | i, n = 0, len(lines) |
| 40 | while i < n: |
| 41 | if lines[i].lstrip().startswith(".. ipython::"): |
| 42 | i += 1 |
| 43 | verbatim = False |
| 44 | # directive option lines (":verbatim:", ":okexcept:", ...) |
| 45 | while i < n and lines[i].strip().startswith(":"): |
| 46 | if "verbatim" in lines[i]: |
| 47 | verbatim = True |
| 48 | i += 1 |
| 49 | # the indented directive body (until a non-indented, non-blank line) |
| 50 | body = [] |
| 51 | while i < n: |
| 52 | ln = lines[i] |
| 53 | if ln.strip() == "": |
| 54 | body.append("") |
| 55 | i += 1 |
| 56 | continue |
| 57 | if not ln.startswith((" ", "\t")): |
| 58 | break |
| 59 | body.append(ln) |
| 60 | i += 1 |
| 61 | if not verbatim: |
| 62 | chunk = _parse_block(body) |
| 63 | if chunk.strip(): |
| 64 | code_chunks.append(chunk) |
| 65 | else: |
| 66 | i += 1 |
| 67 | return "\n".join(code_chunks) |
| 68 | |
| 69 | |
| 70 | def _parse_block(body): |
no test coverage detected