2015-03-24 16 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