调整 Jupyter Notebook 缩进的方法

引言:好久没在博客园发文了,忙里偷闲,一时兴起,履践有感,故作此篇。


背景

  笔者最初使用 Jupyter Notebook 时,曾因缩进量过小而将其调整为 8 字符(Tab),前段时间又觉得太大想要恢复原来的 4 字符,但没有查到恢复方法,也不想重装,于是硬着头皮把相关配置文件都排查了一遍,终于恢复成功(后来也查到了方法),顺便在此整理一下。


Jupyter Notebook 简介

  Jupyter Notebook 是一个基于 Web 的交互工具,支持运行多种编程语言,可以对代码、数学公式、可视化图表、Markdown 等文本进行组合和共享,操作轻便,实时性强,适合做统计建模、机器学习(逐步运行)等。

image

Jupyter Notebook 的内核是基于 IPython 的,非常适合做 Python 数据分析,而 Python 又是严格缩进的,因此缩进量会直接影响代码的美观程度和编写心情。


  作为使用者,我们有必要掌握一些调整缩进的方法,笔者总结了如下三种方法。


调整缩进的三种方法

1. 设置 indentWithTabs

  • 普遍能查到的一种方法,在 cell 里运行修改 indentWithTabs 的 js 代码,即可将缩进量改为一个 Tab(8 字符)。

    %%javascript
    
    // apply setting to all current CodeMirror instances
    IPython.notebook.get_cells().map(
    	function(c) {	return c.code_mirror.options.indentWithTabs=true;  }
    );
    
    // make sure new CodeMirror instances created in the future also use this setting
    CodeMirror.defaults.indentWithTabs=true;
    
  • 另一种相似方法大同小异:

    %%javascript
    
    IPython.tab_as_tab_everywhere = function(use_tabs) {
    	if (use_tabs === undefined) {
    		use_tabs = true;
    	}
    
    // apply setting to all current CodeMirror instances
    IPython.notebook.get_cells().map(
    	function(c) {  return c.code_mirror.options.indentWithTabs=use_tabs;  }
    );
    
    // make sure new CodeMirror instances created in the future also use this setting
    CodeMirror.defaults.indentWithTabs=use_tabs;
    };
    
  • 这种做法的缺点是,当我想恢复 4 字符缩进量时,便将 indentWithTabs 改为 false,但并未生效。

    笔者也是很久之前尝试的,现在可能不太有效了。


2. 在控制台修改 indentUnit

  • 打开 Web 端浏览器的 JavaScript 控制台,输入:
    var cell = Jupyter.notebook.get_selected_cell();
    var config = cell.config;
    var patch = {
    	  CodeCell:{
    		cm_config:{indentUnit:4}  // 自定义缩进量
    	  }
    	}
    config.update(patch)
    
    运行后,刷新界面即可生效(重启界面需再次运行)。

3. 修改配置文件中的 indentUnit

  • 最踏实的方法当然要放到最后,然而探索的过程花费了笔者不少精力,事后也终于搜索到这种方法:
    首先进入配置文件的安装目录,一般是 C:\Users\{用户名}\.jupyter\nbconfig,找到 notebook.json 文件,修改 indentUnit 为你想要的缩进量,保存即可:
    image

其他

  除了调整缩进之外,我们还可以通过修改 codemirror.css 配置文件,去调整代码字体大小及样式来增加界面的美观程度,这里不再赘述,放在第三个参考资料链接里了。
  最后,笔者还想补充一个值得思考的问题:今天是什么日子?(doge)
image


参考资料

posted @ 2022-07-14 22:21  N-Liu  阅读(1067)  评论(0编辑  收藏  举报