Turn off auto-closing parentheses in ipython - ipython

I stay up-to-date with ipython's dev branch (because ipython is pretty much the most awesome thing ever). Fairly recently (before yesterday's awesome ipython 2.0 release) I noticed that it has started to automatically close parentheses, brackets, quotes, etc., as I type them. It happens in both terminal [nothing else I use in terminal does it] and notebook sessions, so I assume it was an intentional choice on the part of the developers. I can respect that other people might like this feature, but it drives me completely nuts.
I can't find any option for it in the configuration files. I can't even google for it, because I don't know what it's called. The only thing that comes up is the different feature of automatic parentheses. I did actually find this question, but that's old, and suggests that the behavior I'm seeing can't happen.
How can I turn this feature off?
[I mostly just use the notebook interface anyway, so just turning it off there would be fine, but I'd prefer to turn it off in both notebooks and ipython sessions at the terminal.]

#minrk's answer is the meat and bones of the fix, but you'll need to wrap it in an initialization callback, at least with IPython-3.1.0. In your custom.js:
require(['base/js/namespace', 'base/js/events'], function(IPython, events) {
events.on('app_initialized.NotebookApp', function() {
IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
});
});
Thanks #Mike for your comment about IPython's RequireJS dependency loading and the pointer to a better formulation at IPython/Jupyter Installing Extensions.
Edit for Jupyter 4.0.x:
The current IPython notebook implementation, Jupyter 4.0.0, revamped JS customizations. It now uses ~/.jupyter/custom/custom.js by default, and you'll need to replace that whole require(... events.on(...)) snippet with just the following in global scope:
IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
Likewise, if you want to use jQuery to manipulate anything, just use the jQuery global directly. For example, I like to hide the fixed header by default, which gives me another 40px of space for my code, which I find a bit more valuable than looking at the Jupyter logo all the time:
jQuery('#header-container').hide();
Edit for Jupyter ≥ 4.0.6 (but < Jupyter Lab):
If the custom.js solution above doesn't work, try adding the following to your ~/.jupyter/nbconfig/notebook.json:
{
"CodeCell": {
"cm_config": {
"autoCloseBrackets": false
}
}
}

The notebook behavior is the result of the CodeMirror autoCloseBrackets plugin. You can turn this off by editing (create it with ipython profile create if you haven't already) ~/.ipython/profile_default/static/custom/custom.js and adding:
if (IPython.CodeCell) {
IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
}
As for the terminal, I don't see the parenthesis behavior you describe. Do you perhaps have a PYTHONSTARTUP defined? IPython executes this file by default, which you can disable by adding to ~/.ipython/profile_default/ipython_config.py:
c.InteractiveShellApp.exec_PYTHONSTARTUP = False

If you want to do it just from python:
from notebook.services.config import ConfigManager
c = ConfigManager()
c.update('notebook', {"CodeCell": {"cm_config": {"autoCloseBrackets": False}}})

This is what works for me in Jupyter 4.0.6:
require(['notebook/js/codecell'], function (codecell) {
codecell.CodeCell.options_default.cm_config.autoCloseBrackets = false;
})
in ~/.jupyter/custom/custom.js.
BTW, If you additionally want to switch off the syntax higlighting of matching parentheses:
codecell.CodeCell.options_default.cm_config.matchBrackets = false;

In the JupyterLab Notebook you can turn off the autoClosingBrackets plugin in the settings menu. Go to Settings --> Advanced Settings Editor and add the following in the User Overrides section:
{
"codeCellConfig": {
"autoClosingBrackets": false
}
}
Screenshot
This worked with JupyterLab 0.32.1 and jupyter_core 4.4.0

The above suggestions didn't worked for me in Jupyter 4.3.0 with Jupyter Notebook 5.0.0
I found that I needed to create a file called ~/.jupyter/custom/custom.js with the following contents:
var cell = Jupyter.notebook.get_selected_cell();
var patch = {
CodeCell: {
cm_config: {
autoCloseBrackets: false,
}
}
}
cell.config.update(patch);
Note that the directory ~/.juypter/custom didn't exist before I did this.
This was hacked together from suggestions in v5.0 docs, and for future readers these are the latest

For Jupyter Notebook 5.1 use the same thing as for 4.2, i.e. put the following snippet into ~/.jupyter/custom/custom.js:
require(['notebook/js/codecell'], function (codecell) {
codecell.CodeCell.options_default.cm_config.autoCloseBrackets = false;
})

I found it was not mentioned in other answers. In my case(OS X, Jupyter 4.2.0), custom.js is located in
~/anaconda/lib/python3.5/site-packages/notebook/static/custom/custom.js
I think it may help somebody like me.

We can do that from jupyter console, try it.

Related

Get notification in a VS Code extension when the Python interpreter is changed

I am writing a VS Code extension that depends on the currently set Python interpreter. When I change the Python Interpreter via the VS Code UI, the extension needs to refresh and get the latest Python path (mainly to show the right environment settings in the TreeView). For now, I have a refresh button in my custom TreeView that I need to press after selecting a different Python interpreter.
However, this is a second manual step. Is there a way to get a notification in my extension, when a user changes the Python Interpreter, e.g., an event the extension can listen to?
I only found VS Code's Activation Events, but it doesn't look like this would help. I didn't find any other events that get triggered after the command python.setInterpreter is executed
Finally found it. The right config to watch for is python.defaultInterpreterPath
vscode.workspace.onDidChangeConfiguration(event => {
let affected = event.affectsConfiguration("python.defaultInterpreterPath");
if (affected) {
doSomething();
}
});
To support the usingNewInterpreterStorage case (default today), add:
const extension = vscode.extensions.getExtension('ms-python.python')!;
await extension.activate();
extension.exports.settings.onDidChangeExecutionDetails((event: any) => {
doSomething();
});

Sentry: All console logs show breadcrumb rather than file in browser

I have an Ionic app and after adding sentry-cordova, I noticed that my console logs (in browser) now show the following:
Previously, it would name the file and line number rather than "breadcrumbs" and I have no idea how to change this behavior.
It's worth noting that when I hover over breadcrumbs.js in the logs it references: #sentry/browser
This is not so much a solution as a potential workaround but it did the trick for me and should work for anyone using environment variables.
Sentry.init({
dsn: "___DSN___",
integrations: function(integrations) {
return integrations.filter(function(integration) {
if (!environment.production) {
// Disables breadcrumbs unless in production mode
return integration.name !== "Breadcrumbs"
}
})
}
});

Using Chrome Dev Tools Code Folding Shortcuts

On the Settings > Preferences > Source we can enable Code Folding on the Chrome Dev. But I didn't find a way to use keyboard shortcuts to, eg. collapse all, etc. Did look for in the Shortcuts section window and in the Full Listings also, but no success. I'm assuming we can't do it on the current version. In case someone knows about it, I'll be very happy to know it too.
There's no such hotkey so try suggesting this feature on https://crbug.com.
Meanwhile you can add it manually:
make sure "code folding" is enabled in devtools settings (in the "Sources" group)
run this code in devtools-on-devtools (see the instruction below)
[
['Shift-Ctrl-[', 'fold'],
['Shift-Ctrl-]', 'unfold'],
['Shift-Ctrl--', 'foldAll'],
['Shift-Ctrl-=', 'unfoldAll'],
].forEach(([key, cmd]) => {
CodeMirror.keyMap['devtools-common'][key] = CodeMirror.commands[cmd];
});
close devtools-on-devtools
This will last only for the current devtools instance.
For convenience you can save the code in snippets and run it later from there or by typing the snippet name in the commands palette (Ctrl-P or Cmd-P hotkey).
How to open devtools-on-devtools:
Open devtools first and switch its Dock side in the menu to a detached (floating) window
in the now detached devtools press CtrlShifti or ⌘⌥i on MacOS,
which will open devtools-on-devtools in a new window
The top answer is great, but chrome devtools has been updated since to use CodeMirror 6, which requires a codeMirror instance to be passed to the functions:
CodeMirror.commands.foldAll();
Uncaught TypeError: Cannot read properties of undefined (reading 'operation')
at CodeMirror.commands.foldAll (foldcode.js:105:8)
at <anonymous>:1:21
line 104-109 from foldcode.js:
CodeMirror.commands.foldAll = function(cm) {
cm.operation(function() {
for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
});
};
I could solve it by debugging a codemirror event to save the cm instance as a global variable (temp1), but I would appreciate if someone could have a better solution to this that can be automated.
Edit: I found the codeMirror instance at document.getElementsByClassName("CodeMirror")[1].CodeMirror, so a working solution is:
CodeMirror.commands.foldAll(document.getElementsByClassName("CodeMirror")[1].CodeMirror)
the shortcut setting still doesn't seem to work though.
(with
CodeMirror.keyMap["devtools-common"]["Ctrl-k"]=function()
{let {CodeMirror:instance}=
document.getElementsByClassName("CodeMirror")[1];
CodeMirror.commands.foldAll(instance);
};
)
Edit 2: oh, it just needed capital K, so "Ctrl-K". Now the shortcut works too. hurrah
btw i've commented on the folding feature's thread on chromium bugtracker to include this, because it is incredibly useful for skimming files while editing/reading. No response yet, idk if anyone's even paying attention to comments there anymore:
https://bugs.chromium.org/p/chromium/issues/detail?id=328431
CodeMirror 6 supports the folding shortcuts natively (per foldKeymap):
Ctrl-Shift-[ (Cmd-Alt-[ on macOS): Fold the lines that are selected, if possible.
Ctrl-Shift-] (Cmd-Alt-] on macOS): Unfold folded ranges on selected lines.
Ctrl-Alt-[: Fold all top-level foldable ranges.
Ctrl-Alt-]: Unfold all folded code.

adding syntax highlighting to Jupyter notebook cell magic

I'm trying to figure out how to activate CodeMirror syntax highlighting for a CodeMirror-supported language (cypher) within a cell for a custom Jupyter cell magic (%%mymagic). The magic isn't associated with a special kernel - it just runs Python commands that process the string entered into the cell that I want to highlight. From what I can tell, this ostensibly can be done using something like
from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})
within the class that implements the magic.
I can't seem to get this to work, however; no change in highlighting occurs when I enter stuff in a cell that starts with %%mymagic. Is the above approach accurate? Does 'magic_cypher' need to have a specific format? Does the magic need to somehow specify the MIME type CodeMirror associates with the desired highlighting language? I'm using notebook 5.0.0, jupyter_core 4.3.0, and python 2.7.13.
The following code works for SQL when placed in ~/.jupyter/custom/custom.js with notebook 5.x:
require(['notebook/js/codecell'], function(codecell) {
codecell.CodeCell.options_default.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
Jupyter.notebook.events.one('kernel_ready.Kernel', function(){
Jupyter.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});
});
Credit goes to Thomas K for this info!
The case where I've been successful doing this was in adding SQL highlighting for the %%sql magic. I did this by adding the following to ~/.jupyter/custom/custom.js. The first line adds the mode to the Codemirror configuration, the rest apply the style to any existing cells in the workbook that need it (later cells will get styled appropriately as they are created). I haven't been successful in having it happen when the magic is installed, although I expect that it is possible.
IPython.CodeCell.config_defaults.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
IPython.notebook.events.one('kernel_ready.Kernel', function(){
IPython.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});

IPython/Jupyter Installing Extensions

I'm having troubles installing extensions in IPython. The problem is that i can't get the extensions load automatically, i have followed the instructions in the github page but it just doesn't work. According the the homepage i need to modify the custom.js file by adding some lines. I want to install the codefolding, hide_input_all and runtools extensions. This is how my custom.js file looks:
// activate extensions only after Notebook is initialized
require(["base/js/events"], function (events) {
$([IPython.events]).on("app_initialized.NotebookApp", function () {
/* load your extension here */
IPython.load_extensions('usability/codefolding/codefolding')
IPython.load_extensions('usability/runtools/runtools')
require(['/static/custom/hide_input_all.js'])
});
});
The extensions work well if i call them manually, for example, if i type
%%javascript
IPython.load_extensions('usability/runtools/runtools/main');
the runtools appear and works perfectly, but i want the extensions to be loaded automatically and not to have to call them manually every time. Could someone tell me where is my mistake?
There's been a little change to the syntax. Nowadays, $ might not be defined by the time your custom.js loads, so instead of something like
$([IPython.events]).on("app_initialized.NotebookApp", function () {
IPython.load_extensions("whatever");
});
you should do something like
require(['base/js/namespace', 'base/js/events'], function(IPython, events) {
events.on('app_initialized.NotebookApp', function(){
IPython.load_extensions("whatever");
})
});
with the appropriate changes to braces and parentheses. For me, the former will work more often than not, but certainly not always; it fails maybe ~1/3 of the time.
If that doesn't do it for you, open up Developer Tools (or whatever is relevant for your browser) and look at the javascript console for errors. That'll help figure out what's going wrong.