Code folding group of lines inside a cell in Jupyter Lab - jupyter-lab

Is there a way to fold code inside a cell in Jupyter Lab. The code folding in my notebooks works fine for loops, classes, methods but I'd like to fold sections of at will without creating a new section.
I can do something similar in Mathematica with 'iconize/uniconize' and even in RStudio like they do here.

Whilst searching for a more elegant solution myself I came across your question; this is an example of a workaround I have been using:
Just define the code you want to call in a function and call the function straight after.
Example code unfolded
Example code folded
Edit:
if True:
data1 = [1, 3, 4]
is another short option but it will not be very clear what it represents when the code is collapsed.

Related

Add formatting to certain lines that begin with specific strings in Sublime Text 3?

I am working with a fixed-width file where all lines start with certain strings to denote what they contain.
TXX 12345 1111
TXY 123 1 2222
TXZ 1 2 3 4 5
What I want to happen is that I want to be able to add rulers or any form of formatting to rows that start with the specified text. (For example, I want to be able to set the line to red if the line starts with TXX, but blue if the row starts wtih TXY and so on)
What is the first step towards being able to do this?
Generally speaking, most roads here lead to a plugin of some sort that's doing work for you, though conceivably you could also get some coloring going using a custom syntax definition and alterations to your color scheme.
Which one is the correct one depends on circumstance and what works best for you. The following are some samples, which will work with the output you provided above but which could probably be made more robust (again depending on your use case); think proof of concept stuff.
Rulers
Rulers can only be applied to the file as a whole, not to specific lines. So for something like that you're looking at a plugin which, every time the cursor moves, tries to look at the current line to see what it is and then sets up rulers based on knowing what the line looks like.
A quick example of that is the following; the event listener will only apply to files that have the _fixed_rulers setting applied; simplistically, while you have your file open you can enter view.settings().set("_fixed_rulers", True) in the Sublime console, or if you have a syntax you could put the setting into syntax specific settings, etc.
import sublime
import sublime_plugin
def _get_rulers(line):
if line.startswith('TXX'):
return [4, 10]
if line.startswith('TXY'):
return [4, 8, 10]
if line.startswith('TXZ'):
return [4, 6, 8, 10, 12]
return []
class RulerListener(sublime_plugin.ViewEventListener):
#classmethod
def is_applicable(cls, settings):
return settings.get("_fixed_rulers", False)
def on_selection_modified_async(self):
# Cursor position of the first selection; get the full text of the
# line its on
pt = self.view.sel()[0].b
line = self.view.substr(self.view.line(pt))
self.view.settings().set("rulers", _get_rulers(line))
Since there can be multiple selections but rulers are not line specific, this uses the line the first cursor (based on position, not selection order) and applies rulers to the file based on that.
Regions
Colors can be applied to regions of content via a plugin, in a variety of styles (outlined only, underlined, filled, etc), and the API also allows you to find text regions via regex.
So it's also possible to have regions assigned that give things the color you want. A simple example of that would be this command, which will add/update the regions in the file that's active when you execute the color_line_regions command.
import sublime
import sublime_plugin
class ColorLineRegionsCommand(sublime_plugin.TextCommand):
def run(self, edit):
v = self.view
v.add_regions('_txx', v.find_all('^TXX.*$'), 'region.redish')
v.add_regions('_txy', v.find_all('^TXY.*$'), 'region.bluish')
v.add_regions('_txz', v.find_all('^TXZ.*$'), 'region.purplish')
This example is hard coded and requires you to manually invoke the command; you could also have this trigger in response to a file with a specific name opening, and so on.
As defined here this is a one time thing; if you are actively modifying the content of files, adding or changing lines will not adjust regions unless you run the command again (or, have an event listener listen for on_modified_async and trigger this after a delay, etc).
Syntax Definition
Another potential option is creating a custom syntax definition that recognizes the content of the file and applies the appropriate scopes to color things.
This is a much more complex option (the example below is very bare bones and not nearly production ready, but is a good simple test) in that it requires you to construct the syntax definition, but can yield good results if you put in the work.
What you would actually want to do is create your own custom scopes in your syntax, probably with much more robust rules, and then augment your color scheme to match those. Here we're just hackily using scopes that equate to the proper colors if you happen to be using Mariana as your color scheme.
%YAML 1.2
---
# See http://www.sublimetext.com/docs/syntax.html
file_extensions:
- fixed
scope: text.plain.fixed
name: Fixed Field Data
contexts:
main:
- match: '^TXX.*'
scope: variable.language.python
- match: '^TXY.*'
scope: variable.function.python
- match: '^TXZ.*'
scope: keyword.declaration.class.python
A Mix
The ultimate solution may be a mixture of these; perhaps you want the syntax to provide colors and the rulers plugin to make things easier to view as well (as a bonus, with a custom syntax you can have syntax specific settings, which makes the first plugin easy to deploy when files open).
The above examples just scratch the surface; be sure to check out the API Reference for information on how the plugins are working and for more details. There are also a variety of videos that teach how to create and use plugins on my YouTube channel.

How to transform lines of code into a comment in Python3

just wondering how to convert a set of code into comments, without having to go through each individual line of code and put a # at the beginning. Was thinking that maybe there was a quick way to highlight the code and then convert it into comment, atm i'm just cutting it off the code and then re-pasting it in later on.
Much appreciated :)
P.S. i m using Pycharm as my IDE
In jupyter notebook, we select lines of code and press ctrl and / key simultaneously to convert a set of code into comments. Also same for vice versa.
You can try it in Pycharm.
You can use the (""") symbol before and after the text you want to comment out. It is not exactly a comment and more of a text constant, but either way it is often used for documentation, so you can use it for multiline comments except for some cases when it causes unexpected errors
To avoid such cases you could simply use multiple single line comments by selecting the desired lines and using ctrl+/ to comment them out

Writing an autocomplete plugin in Sublime Text

Within my company we have an XML-based notation. Among other features, it is possible to define references from one XML document into another. I would like to enable autocompletion in Sublime so that whenever I am adding a reference, the possible files (i.e. XML files within the same project) and link points (i.e. symbols within that file) get offered as recommendations.
So far, I have found a lot of plugins that enable autocomplete for, say, HTML, PHP or LaTeX. However, I have the feeling the code base is too complex for a somewhat simple task. Is there, for instance, some vanilla function that generates completions based on an arbitrary array received as parameter? I would create the logic to determine what is a symbol and derive said array, but the whole process seems somewhat cumbersome to me.
(As a note: I can program in Python and have fiddled with other Sublime features, such as snippets, but these packages seem to be much more complex than it feels necessary.)
The base to create the completions entry is not to complicated. You now need to fill the array with the correct values (this could be done via a project setting or parsing other files).
import sublime
import sublime_plugin
# Your array, which contains the completions
arr = ["foo", "bar", "baz"]
class MyCompletionsListener(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
loc = locations[0]
# limit you completions scope
if not view.score_selector(loc, "text"):
return
completions = [(v + "\tYour Description", v) for v in arr]
return completions
OP's note: The answer works as advertised. However, the integration is so seamless that I thought for a while that something was missing. If the Python script above is on the right folder, all of the completions returned by the completions array will be suggested (depending on Sublime settings, it might be necessary to trigger the completions menu with Ctrl+Space). Also worth noting:
The completions may be None, in which case they just don't add any completion option, or an array of 2-tuples, where the first element is the description (which will be shown in the drop-down menu and trigger the completion) and the second is the value (i.e. the text that will be input if the completion is selected).
The score_selector method can be used to determine if the cursor position is within a given scope.

how to input multiline statements into arangosh?

as far as I know the only way to register aqlfunctions is via arangosh. JS functions very fastly get a few more lines of code which normally also have line breaks for better understanding. Whenever I paste them into the arangosh it gets corrupt as it excepts to get a "proper" end signal/sign. If I don't know it , the only way to reset it is a shotdown. My questions are:
Is there any shortcut like which resets the line input in such a case?
How can I write JS code into several lines and paste them into the arangosh directly?
Is there another way to register (more complex) JS functions I don't know?
Thanks for your help in advance.
<STRG> + D also works in windows.
Multiline doesn't work well with the CMD, it works partly with the cygwin shell window.
However, if the context shows that a function will start (using a brace) it will offer to add another line until the brace closes.
Probably the easiest way to get in more complex code is:
require("internal").load("c:\\tmp\\test.js")
which will be executed right away, so if you define functions in that, they will be usable in the shell context from then on.

Is it possible to save Sub-Folds in Sublime? Bufferscroll doesn't seem to do it

Using Bufferscroll for sublime is great in that it saves all my folds between saves. The issue I'm having is that I have many subfolds, and everytime i hide and then expand a parent-fold, all the subfolds are re-expanded. Is there a way to just fold/unfold the parent but keep all the children in their last state until explicitly unfolded?
#PatatjeNL thanks for the response, but i think that either i'm still doing something wrong, or i may not have fully explained the question. allow me to share an example:
def foo():
if a == b:
bar(a)
bar(b)
return 1
if c==d:
bar(c)
bar(d)
return 2
ok.. so with the above, i could fold on the def foo() line (1), the if a==b: line (2), or the if c==d: line (3). If i fold (2) and (3), all is good. I can then fold (1). But if i then UNfold 1, (2) and (3) are no longer folded. Everything that is contained by (1) unfolds, which is what i'm trying to keep in state.
i did try re-installing a few times,and certainly i may be continuing to have a technical issue in that regard, but i thought i'd lay it out this way just to make sure we were on the same wavelength.
thanks again for the attention!!
Well, it seems that BufferScroll actually did implement this feature. Somehow I didn't get it working before, which lead me to believe that it was not implemented - I've just tried it and it actually works.
According to a collaborator's answer at the issue report at the BufferScroll GitHub page, this feature was implemented.
When the saving of the folded code does not work, you could try reinstalling the BufferScroll package.

Resources