goerz / jupytext.vim

Vim plugin for editing Jupyter ipynb files via jupytext
MIT License
316 stars 27 forks source link

Detect notebook language #24

Open johngodlee opened 3 years ago

johngodlee commented 3 years ago

I know that it's possible to set jupytext_fmt to convert the .ipynb to a given format, either, py, jl, md, etc. But I use both Julia and Python Jupyter Notebooks in my work. Is it possible to detect the notebook language and dynamically convert to .py or .jl?

I could convert to .md, but this would prevent me using [https://github.com/jalvesaq/vimcmdline]() to run code in a repl.

I thought it might be possible to add support for reading metadata:language in the Notebook JSON, e.g.:

 "metadata": {
  "kernelspec": {
   "display_name": "Julia 1.6.2",
   "language": "julia",
   "name": "julia-1.6"

Is this a feature that already exists? Or could it be implemented?

goerz commented 3 years ago

This would be a nice feature indeed. Not sure how easy it would be to implement

mwouts commented 3 years ago

Hi, I just wanted to point out that one can use the auto extension for this in Jupytext, cf https://jupytext.readthedocs.io/en/latest/config.html?highlight=auto#per-notebook-configuration

GreenCourt commented 3 years ago

This function may help.

function s:get_language_name(ipynb_path)
  try
    " https://nbformat.readthedocs.io/en/latest/format_description.html#top-level-structure
    " only the `name` field always exists in the `language_info` (if `language_info` is defined).
    return a:ipynb_path->readfile()->join("")->json_decode()["metadata"]["language_info"]["name"]
  catch
    " failed to detect language name
    return ""
  endtry
endfunction

echo s:get_language_name("Untitled.ipynb")