Guest User

Neopyter keymap

a guest
Nov 13th, 2025
8
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. -- <leader>jn – .ipynb → .ju.py via jupytext, then turn lone "#" lines into blank lines
  2. map("n", "<leader>jn", function()
  3. vim.cmd("silent update")
  4.  
  5. local infile = vim.fn.expand("%:p")
  6. if vim.fn.fnamemodify(infile, ":e") ~= "ipynb" then
  7. vim.notify("Current buffer is not an .ipynb", vim.log.levels.WARN)
  8. return
  9. end
  10.  
  11. local outpath = vim.fn.expand("%:r") .. ".ju.py"
  12.  
  13. local function run(args, on_ok, on_err)
  14. if vim.system then
  15. vim.system(args, { text = true }, function(res)
  16. vim.schedule(function()
  17. if res.code == 0 then
  18. on_ok()
  19. else
  20. on_err(res.stderr or "")
  21. end
  22. end)
  23. end)
  24. else
  25. vim.fn.jobstart(args, {
  26. stdout_buffered = true,
  27. stderr_buffered = true,
  28. on_exit = function(_, code)
  29. vim.schedule(function()
  30. if code == 0 then
  31. on_ok()
  32. else
  33. on_err("")
  34. end
  35. end)
  36. end,
  37. })
  38. end
  39. end
  40.  
  41. local function open_and_strip()
  42. -- Create/load the buffer for the new file WITHOUT depending on the current window
  43. local buf = vim.fn.bufadd(outpath)
  44. vim.fn.bufload(buf)
  45.  
  46. -- Make sure it's editable (preview/floating windows can set nomodifiable)
  47. vim.bo[buf].readonly = false
  48. vim.bo[buf].modifiable = true
  49.  
  50. -- Do the substitution INSIDE that buffer's context
  51. vim.api.nvim_buf_call(buf, function()
  52. -- Turn lines that are just "#" (with optional spaces) into blank lines.
  53. -- This keeps the newline; it does NOT delete the line.
  54. vim.cmd([[silent keeppatterns %s/^\s*#\s*$//e]])
  55. -- Optionally save the result:
  56. vim.cmd("silent write")
  57. end)
  58.  
  59. -- Show the converted file
  60. vim.api.nvim_set_current_buf(buf)
  61. vim.notify("Converted → " .. outpath .. " and stripped lone '#' lines", vim.log.levels.INFO)
  62. end
  63.  
  64. if vim.fn.executable("jupytext") == 1 then
  65. run({ "jupytext", "--to", "py:percent", "--output", outpath, infile }, open_and_strip, function(err)
  66. vim.notify("jupytext failed: " .. err, vim.log.levels.ERROR)
  67. end)
  68. elseif vim.fn.executable("jupyter") == 1 then
  69. -- Fallback: plain script via nbconvert if jupytext isn't available
  70. run({ "jupyter", "nbconvert", "--to", "script", "--output", outpath, infile }, open_and_strip, function(err)
  71. vim.notify("nbconvert failed: " .. err, vim.log.levels.ERROR)
  72. end)
  73. else
  74. vim.notify("Neither `jupytext` nor `jupyter nbconvert` found in PATH", vim.log.levels.ERROR)
  75. end
  76. end, { desc = "Convert .ipynb → .ju.py and blank-out lone '#' lines" })
  77.  
Advertisement
Add Comment
Please, Sign In to add comment