How do I change the autoindent to 2 space in IPython notebook - jupyter-notebook

I find that developing functions in IPython notebook allows me to work quickly. When I'm happy with the results I copy-paste to a file. The autoindent is 4 spaces, but the coding style for indentation at my company is 2 spaces. How do I change the autoindent to 2 spaces?

The official documentation has an example answering this specific question. This worked for me with IPython 4.
Summary: Paste the following into your browser's javascript console
var cell = Jupyter.notebook.get_selected_cell();
var config = cell.config;
var patch = {
CodeCell:{
cm_config:{indentUnit:2}
}
}
config.update(patch)
The setting is persisted. You can roll back by exchanging : 2 for : null.

From the official documentation for CodeMirror Code Cells:
Open an Ipython Notebook
Create a Code Cell e.g. by pressing b
Open your browser’s JavaScript console and run the following
snippet:
var cell = Jupyter.notebook.get_selected_cell();
var config = cell.config;
var patch = {
CodeCell:{
cm_config:{indentUnit:2}
}
}
config.update(patch)
Reload the notebook page in the browser e.g. by pressing F5
This will fix it permanently. I assume this works only on recent versions, not sure though!

AdamAL's answer is correct. It worked for me.
However it only changes the indentation in the Jupyter Notebook and leaves the indentation in the Jupyter Editor unaffected.
A more direct way to change the indentation is to directly edit the Jupyter config files in the .jupyter/nbconfig directory. This directory contains 2 files:
edit.json
notebook.json
The option you must set in either one is indentUnit. Here is the content of my Jupyter config files:
edit.json:
{
"Editor": {
"codemirror_options": {
"indentUnit": 2,
"vimMode": false,
"keyMap": "default"
}
}
}
notebook.json:
{
"CodeCell": {
"cm_config": {
"indentUnit": 2
}
}
}
With this approach I've set the default indentation to 2 in both the Jupyter Notebook and the Jupyter Editor.

Based on this question and the options found here:
In your custom.js file (location depends on your OS) put
IPython.Cell.options_default.cm_config.indentUnit = 2;
On my machine the file is located in ~/.ipython/profile_default/static/custom
Update:
In IPython 3 the plain call does not work any more, thus it is required to place the setting within an appropriate event handler. A possible solution could look like
define([
'base/js/namespace',
'base/js/events'
],
function(IPython, events) {
events.on("app_initialized.NotebookApp",
function () {
IPython.Cell.options_default.cm_config.indentUnit = 2;
}
);
}
);

If you use jupyterlab, there seems to be an easier way:
1) Click jupyterlab menu Settings > Advanced Setting Editor
2) Click "Notebook" on the left hand pane, make sure you are on "Raw View"
3) On the right pane, under "User Overrides", enter this:
{
"codeCellConfig": {
"tabSize": 2
}
}
If you look at the System Defaults, that will give you hint on whats overridable and you can repeat this for other settings.
I tried this on Google Platform AI Notebook which uses Jupyterlab.

I believe this is now best wrapped in a event handler to load once per notebook load:
$([IPython.events]).on('app_initialized.NotebookApp', function(){
IPython.CodeCell.options_default['cm_config']['indentUnit'] = 2;
});

In addition to adding
IPython.Cell.options_default.cm_config.indentUnit = 2;
to your custom.js file as suggested by Jakob, be sure to clear your browser cache as well before restarting ipython notebook!
Also, you may have to first create the ~/.config/ipython/profile_default/static/custom/ directory (use echo $(ipython locate default) to find your default directory) before adding the custom.js file.

Related

Nix config outside of NixOS

So I’m trying to make a development environment that’s easily reproducible (staying away from home-manager currently to understand Nix better). After enough searching around I figured out how to make a few custom derivations, use buildEnv for package sets, and use ~/.config/nixpkgs/config.nix to do overrides. I’m working now to setup zsh and oh-my-zsh which have a ton of configuration options, but the only documentation I can find seems to suggest adding them to configuration.nix, which is a NixOS option I can’t use.
Currently my config.nix code looks something like this:
let
pkgs = import <nixpkgs> {};
in {
allowUnfree = true;
programs = {
zsh = {
enable = true;
promptInit = "source ${pkgs.zsh-powerlevel9k}/share/zsh-powerlevel9k/powerlevel9k.zsh-theme";
ohMyZsh = {
enable = true;
plugins = ["autojump"];
theme = "powerlevel9k/powerlevel9k";
};
};
};
packageOverrides = pkgs: with pkgs; rec {
all = buildEnv {
name = "all";
paths = with pkgs; [
tmuxinator
zsh
oh-my-zsh
autojump
...
];
};
};
}
My understanding so far is that within ~/.config/nixpkgs/config.nix, there should be a single config set which contains things like the overrides function and corresponds to documentation examples of config.programs.zsh.enable, etc. However, nothing I write in that programs section affects or causes a different ouput of any of my programs.
What am I missing? How can I affect the configuration options listed here (https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/programs/zsh/zsh.nix)?
You seem to be trying to use home-manager's config without using home-manager itself. As you can see in the NixOS module you linked, this actually sets up /etc/zshrc etc, so it's not intended for use in a user-local config and won't do anything there. If you look at the corresponding home-manager module, you'll see that it basically reimplements the whole module for user-local purposes. So you won't get far with this approach without relying on home-manager.

how to change atom-live-server default browser

Does anyone have experience changing the default browser for atom-live-server? The documentation says to add, {"browser" : "browser-name"}, to atom-live-server.json. I did that and the default live server browser did not change from Chrome which is my default browser for macos 10.14.1. Here is the atom-live-server.json file, but it didn't work.
{
"atom-workspace": {
"ctrl-alt-3": "atom-live-server:start-3000",
"ctrl-alt-4": "atom-live-server:start-4000",
"ctrl-alt-5": "atom-live-server:start-5000",
"ctrl-alt-8": "atom-live-server:start-8000",
"ctrl-alt-9": "atom-live-server:start-9000",
"ctrl-alt-l": "atom-live-server:startServer",
"ctrl-alt-q": "atom-live-server:stopServer"
}
{
"browser" : "Firefox"
}
}
Does atom-live-server always use the macos default browser so you can't actually change it?
Thanks for your help.
It looks like this is caused by a simple syntax error in your JSON file. You need to separate keys with a comma. Your file should look like the following (note the comma on line 10):
{
"atom-workspace": {
"ctrl-alt-3": "atom-live-server:start-3000",
"ctrl-alt-4": "atom-live-server:start-4000",
"ctrl-alt-5": "atom-live-server:start-5000",
"ctrl-alt-8": "atom-live-server:start-8000",
"ctrl-alt-9": "atom-live-server:start-9000",
"ctrl-alt-l": "atom-live-server:startServer",
"ctrl-alt-q": "atom-live-server:stopServer"
},
{
"browser" : "Firefox"
}
}
I think you just need to put the following code in your .atom-live-server.json file. This file should be in your project folder.
{
"browser" : "Firefox"
}
It works on my windows 7 system. The first few lines seem to make things worse. I don't know why.
I think you've solved somehow, but I wrote this answer because I got in same situation.
(I work on Mac OS Mojave)
I did the same way Bill Zhao said.
Create a json file .atom-live-server.json in project file, and put
{
"browser":"Firefox(or firefox)"
}
It's working for me. July 6 2019
Only change your predetermined browser in your operating system.

Show code line numbers in JupyterLab

In Jupyter notebook, cntrl+ m L toggles code line numbers in current cell but how to bring the code line numbers in JupyterLab?
Referred a similar issue opened in github
https://github.com/jupyterlab/jupyterlab/issues/2395 - Shift+L toggles line number visibility.
you can turn this on by default by going into Settings --> Advanced Settings Editor:
As you can see from the screenshot, you can edit other features as well and easily set them back to default by deleting your 'User Overrides'
Go to Settings > Advanced configuration and add:
{
"codeCellConfig": {
"lineNumbers": true
}
}
You can go to View -> Show Line Numbers:
which will display line numbers in the notebook:
Late reply, but it'll still help others!
For Windows users, just hit Shift + L
In your Jupyter Lab, click the chain, View -> Line numbers. This solution is from this GitHub issue.
I'm new at this so don't flame me. But Frank said from View -> Show Line Numbers. I did this from main JupyterLab window. I'm using version 3.5.0.

Is there a way to jump to last edited cell in Jupyter?

Often in Jupyter I'd move to different parts of the notebook to look at something, and when I am done I want to jump back to where I was working on previously. Right now I'd have to navigate to the closest Markdown section (through the Jupyter Notebook Extensions) and move up or down to get to where I was. Is there a way to jump directly to the last cell that I have made an edit (preferably through keyboard shortcut)? Thanks!
Ideally this would be a built-in shortcut of course, but in the meantime:
Option 1: Custom JavaScript
If you get a browser extension like Custom JavaScript for Websites 2 (open-source), then you can use this code to record a stack of scroll position histories and jump backwards with Ctrl+Shift+X:
// Visit JupyterLab in browser and click the Custom JS browser extension icon and then paste this:
if(location.href.startsWith("http://localhost:8888/lab")) {
let scrollLocationsHistories = new Map();
let scrollBinHeight = 100;
window.addEventListener("keydown", (e) => {
let notebookEl = document.querySelector(".jp-mod-searchable .jp-NotebookPanel-notebook");
if(!scrollLocationsHistories.has(notebookEl)) scrollLocationsHistories.set(notebookEl, [])
let scrollLocationsHistory = scrollLocationsHistories.get(notebookEl);
if(e.ctrlKey && e.shiftKey && e.key === "X") {
if(scrollLocationsHistory.length > 0) {
e.preventDefault();
let origScrollPos = notebookEl.scrollTop;
notebookEl.scrollTo(0, scrollLocationsHistory.pop()*scrollBinHeight);
let newScrollPos = notebookEl.scrollTop;
if(Math.abs(origScrollPos-newScrollPos) < scrollBinHeight && scrollLocationsHistory.length > 0) {
notebookEl.scrollTo(0, scrollLocationsHistory.pop()*scrollBinHeight); // jump back again because last edit position was close to current position
}
console.log("Scroll History (newest locations at end):", scrollLocationsHistory.map(v => v*scrollBinHeight))
}
} else if(!e.ctrlKey && !e.shiftKey && document.activeElement.tagName.toLowerCase() === "textarea") {
let scrollBin = Math.round(notebookEl.scrollTop/scrollBinHeight);
if(scrollLocationsHistory[scrollLocationsHistory.length-1] !== scrollBin) {
scrollLocationsHistory.push(scrollBin);
if(scrollLocationsHistory.length > 500) scrollLocationsHistory = scrollLocationsHistory.slice(-250);
}
}
});
}
It's just an initial prototype, but it seems to work quite well so far. You may want to adjust it a bit - e.g. scrollBinHeight causes nearby edits that are within scrollBinHeight pixels of one another to not create a second history entry. You'll need to edit http://localhost:8888/lab to match the URL that you want to enable it on. If you're reading this long after I've written it, then you may also need to change document.querySelector(".jp-mod-searchable .jp-NotebookPanel-notebook") (i.e. the main scrolling element of the active notebook) in case they've updated the HTML class names, or HTML structure.
Option 2: Fold Often
Another possible option (which may be impractical depending on your use case) is to get used to folding cells that you're not currently working on. That makes it much easy to quickly scroll between cells that you're working on.
Option 3: Search Hack
If you're working on a particular cell but often have to jump to another one, you can add a comment like #vv (or any random easy-to-type string) to both of those cells and then whenever you need to jump between them, just press Ctrl+F and then Enter. The first time you do this you'll obviously need to type vv in the search box, but after that it'll be remembered (unless you use the search for another string). The disadvantage of this approach is that you need to "prune" the #vvs from cells that you're no longer working on.
echap to go to command mode, then Ctrl + z will undo your last change, which will bring the focus on the last edited cell. ctrl + y will redo the last modification.
(Only tested on python3 kernel)
EDIT Actually if you press ctrl + z just once, you only get the focus part, without modifying your cell. Then press enter to go to edit mode, which scrolls the page to the active cell.

Aptana 3 Code Folding

Ive started using Aptana 3 today and really like it,
However I'm struggling to find out if I can code fold to specific levels.
For example I can push Ctrl+Shift+Divide and will collapse EVERYTHING imaginable.
Including the class.
lets just say my doc is as follows:
class Kill_model extends Game_Model{
function shoot(){
//code
//code
//code
//code
//code
}
function respawn(){
//code
//code
//code
//code
//code
}
function spectate(){
//code
//code
//code
//code
//code
}
}
The default will collapse to
class Kill_model extends Game_Model{}
I've been using PHPEdit in the past, and like to "Fold to Level 2"
This gives me the appearance of
class Kill_model extends Game_Model{
function shoot(){}
function respawn(){}
function spectate(){}
}
I was wondering if its possible to just fold down to level 2, by level 2 I assume it means 2 levels deep. Level 1 = Class, level 2 = functions within.
Many thanks.
Ok, so level folding is available in Aptana, it just isn't built into PHP editing, only Source editing. To add it to PHP, you can go to Commands > Source > Edit this Bundle, and the Commands > PHP > Edit this Bundle and copy Source/commands/folding.rb to PHP/commands/folding.rb (this will be a new file). If you do not have Option and Command keys (Mac, I believe), you will want to change the keybindings in this file to something else, like Control and Alt. You will find the keybinding in the folding.rb file looking something like this:
with_defaults :input => :none, :output => :discard, :key_binding => "OPTION+COMMAND+0" do
and a second time like this:
cmd.key_binding = "CONTROL+ALT+" + level.to_s
Just change the OPTION to CONTROL and the COMMAND to ALT, and you will have a new Ctrl+Alt+ shortcut once you restart Aptana.
See my second answer for more direct info... I thought I'd leave this one in case it helps someone with a similar but not quite the same problem...
I can't speak for the keyboard shortcut because I don't know where numpad_divide is on my laptop (no numpad) - but if you look under Window > Preferences > Aptana Studio > Editors > PHP, you can choose to initially fold "these elements" - if you check "Functions" I think you may get the folding you are looking for. However, I do not think this preference will affect the behavior of Ctrl+Shift+Divide aka Collapse All.
There is also a command to collapse the current block (Ctrl+Numpad_minus) but I think this would be less useful to you.
You may also find the Quick Outline helpful, if you are looking for a short overview of the available classes and functions in your file. This can be accessed with Ctrl+O (or right click > Quick Outline).
Edit: Playing around with Aptana today I found, under Commands > Source > Folding > Toggle Foldings at Level > Level <x>. There appears to be a shortcut associated with each level, Alt+1, Alt+2, etc. but it doesn't work for me. I also don't see an option to configure a shortcut for these commands, but you can theoretically make your own.

Resources