Here is a script that will take an @jupytext tree and split it out into
child nodes, one node per cell. To use, make a script button for it,
select a @jupytext node, and run the script. The script tries to create
reasonable headlines for the nodes but of course it can't be perfect.
Please try it out so we can get a sense if it's going to be a useful
solution. WARNING: there is NO undo capability yet so ONLY TRY IT ON A COPY
of your file.
"""Move cells into child nodes of the root of an @jupytext node."""
CELL_MARKER = '# %%'
MARKER_LEN = len(CELL_MARKER)
def get_ipynb_header(notebook):
start = notebook.find('# ---')
end = notebook.find('# ---', 1) + 4
header = notebook[start:end]
return header
# Find root = root position for file
def optional_filter(p):
return p.h.startswith('@jupytext')
def find_current_atfile(p):
for p in c.p.copy().self_and_parents():
if optional_filter(p):
return p
else:
return None
def make_headline(cell: str) -> str:
lines = cell.split('\n')
for line in lines[1:]:
line = line.replace('#', '').strip()
if not line or line.startswith('%%'):
continue
words = line.split()
n = min(6, len(words))
return ' '.join(words[:n])
root = find_current_atfile(c.p)
if root is None:
g.es(' No .ipynb tree found')
else:
contents = root.b
header = get_ipynb_header(contents)
i0 = 0
n = -1 # Number of children
while True:
i0 = contents.find(CELL_MARKER, i0)
if i0 == -1:
break
i1 = contents.find(CELL_MARKER, i0 + 1)
cell = contents[i0:i1] if i1 > -1 else contents[i0:]
n += 1
p0 = root.insertAsNthChild(n)
p0.b = cell
p0.h = make_headline(cell)
if i1 == -1:
break
i0 = i1 - MARKER_LEN
root.b = header + '\n@others'
c.redraw()
--
You received this message because you are subscribed to the Google Groups
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/leo-editor/ccacd0b2-f53f-4af7-b423-89b1b924455cn%40googlegroups.com.