Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- <leader>jn – .ipynb → .ju.py via jupytext, then turn lone "#" lines into blank lines
- map("n", "<leader>jn", function()
- vim.cmd("silent update")
- local infile = vim.fn.expand("%:p")
- if vim.fn.fnamemodify(infile, ":e") ~= "ipynb" then
- vim.notify("Current buffer is not an .ipynb", vim.log.levels.WARN)
- return
- end
- local outpath = vim.fn.expand("%:r") .. ".ju.py"
- local function run(args, on_ok, on_err)
- if vim.system then
- vim.system(args, { text = true }, function(res)
- vim.schedule(function()
- if res.code == 0 then
- on_ok()
- else
- on_err(res.stderr or "")
- end
- end)
- end)
- else
- vim.fn.jobstart(args, {
- stdout_buffered = true,
- stderr_buffered = true,
- on_exit = function(_, code)
- vim.schedule(function()
- if code == 0 then
- on_ok()
- else
- on_err("")
- end
- end)
- end,
- })
- end
- end
- local function open_and_strip()
- -- Create/load the buffer for the new file WITHOUT depending on the current window
- local buf = vim.fn.bufadd(outpath)
- vim.fn.bufload(buf)
- -- Make sure it's editable (preview/floating windows can set nomodifiable)
- vim.bo[buf].readonly = false
- vim.bo[buf].modifiable = true
- -- Do the substitution INSIDE that buffer's context
- vim.api.nvim_buf_call(buf, function()
- -- Turn lines that are just "#" (with optional spaces) into blank lines.
- -- This keeps the newline; it does NOT delete the line.
- vim.cmd([[silent keeppatterns %s/^\s*#\s*$//e]])
- -- Optionally save the result:
- vim.cmd("silent write")
- end)
- -- Show the converted file
- vim.api.nvim_set_current_buf(buf)
- vim.notify("Converted → " .. outpath .. " and stripped lone '#' lines", vim.log.levels.INFO)
- end
- if vim.fn.executable("jupytext") == 1 then
- run({ "jupytext", "--to", "py:percent", "--output", outpath, infile }, open_and_strip, function(err)
- vim.notify("jupytext failed: " .. err, vim.log.levels.ERROR)
- end)
- elseif vim.fn.executable("jupyter") == 1 then
- -- Fallback: plain script via nbconvert if jupytext isn't available
- run({ "jupyter", "nbconvert", "--to", "script", "--output", outpath, infile }, open_and_strip, function(err)
- vim.notify("nbconvert failed: " .. err, vim.log.levels.ERROR)
- end)
- else
- vim.notify("Neither `jupytext` nor `jupyter nbconvert` found in PATH", vim.log.levels.ERROR)
- end
- end, { desc = "Convert .ipynb → .ju.py and blank-out lone '#' lines" })
Advertisement
Add Comment
Please, Sign In to add comment