在 jupyter 中通过 custom.js 获取当前行

get current line through custom.js in jupyter

我想通过 custom.js 在 jupyter 单元格中光标所在的行插入文本。有没有类似 Jupyter.notebook.get_current_line() 的方法?我会搜索文档,但找不到 Jupyter.notebook.

上所有可调用方法的概述

Jupyter 将 CodeMirror 用作文本编辑器,因此您在 CodeMirror 中查找会更好API。

因此,您可以使用Jupyter.notebook.get_selected_cell().code_mirror获取当前单元格的CodeMirror实例。

然后你可以使用CodeMirror的getCursor函数来return光标的位置。 return 行号和光标所在行的字符数(格式为 {line: 0, ch: 0} 第一行第一个字符)

最后,您可以使用replaceRange插入文本。只需保存当前光标位置并使用 replaceRange("Your text here",cursor,cursor)

所以,最终代码看起来像

var cm = Jupyter.notebook.get_selected_cell().code_mirror;
var cursor = cm.getCursor();
cm.replaceRange("Your text here",cursor,cursor);