2015-03-24 80 views
10

在IPython Notebook环境中,可以使用IPython Javascript API定义自定义键盘快捷键。使用%%javascript魔法,可以写出如下IPython中的互动控制台中一个JavaScript(例如描述here):在编辑模式下复制当前行的自定义IPython Notebook键盘快捷键

%%javascript 

IPython.keyboard_manager.command_shortcuts.add_shortcut('r', { 
    help : 'run cell', 
    help_index : 'zz', 
    handler : function (event) { 
     IPython.notebook.execute_cell(); 
     return false; 
    }} 
); 

我想编写创建结合按住Ctrl的Alt在编辑模式的快捷方式一个javascript直到“重复当前行”的动作---即将光标移动到当前行的开始位置,选择行,复制行,返回,粘贴。本质上,我想模拟Eclipse的键盘快捷键,或记事本++中的Ctrl-d或Emacs中的C-CACE-C-n M-W C-y。 JavaScript文件将采取以下形式:

%%javascript 

IPython.keyboard_manager.edit_shortcuts.add_shortcut('ctrl-alt-down', { 
    help : 'run cell', 
    help_index : 'zz', 
    handler : function (event) { 
     [Code that duplicates the line]; 
     return false; 
    }} 
); 

虽然我尝试提出“CTRL-ALT-下”是代表快捷顺序不正确的方式,我无法找到一个keyboard_manager任何文件。

我宁愿不使用(例如)AutoHotKey解决方案,因为我想限制此快捷方式到IPython Notebook的编辑模式。

回答

6

添加到〜/ .jupyter /自定义/ custom.js下一个代码

/** 
* 
* Duplicate a current line in the Jupyter Notebook 
* Used only CodeMirror API - https://codemirror.net 
* 
**/ 
CodeMirror.keyMap.pcDefault["Ctrl-Down"] = function(cm){ 

    // get a position of a current cursor in a current cell 
    var current_cursor = cm.doc.getCursor(); 

    // read a content from a line where is the current cursor 
    var line_content = cm.doc.getLine(current_cursor.line); 

    // go to the end the current line 
    CodeMirror.commands.goLineEnd(cm); 

    // make a break for a new line 
    CodeMirror.commands.newlineAndIndent(cm); 

    // filled a content of the new line content from line above it 
    cm.doc.replaceSelection(line_content); 

    // restore position cursor on the new line 
    cm.doc.setCursor(current_cursor.line + 1, current_cursor.ch); 
}; 

结果

enter image description here

测试在未来环境

[email protected] ~ $ google-chrome --version 
Google Chrome 53.0.2785.116 
[email protected] ~ $ jupyter --version 
4.1.0 
[email protected] ~ $ uname -a 
Linux wlysenko-Aspire 3.13.0-37-generiC#64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux