Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make cells (# %%) collapsible python files #1527

Closed
oerpli opened this issue Apr 12, 2019 · 28 comments · Fixed by #11418
Closed

Make cells (# %%) collapsible python files #1527

oerpli opened this issue Apr 12, 2019 · 28 comments · Fixed by #11418
Assignees
Labels
feature-request Request for new features or functionality interactive-window Impacts interactive window

Comments

@oerpli
Copy link

oerpli commented Apr 12, 2019

Environment data

  • VS Code version: 1.33
  • Extension version (available under the Extensions sidebar): Current
  • OS and version: Win10 1703
  • Python version (& distribution if applicable, e.g. Anaconda): Anaconda 3.7
  • Type of virtual environment used (N/A | venv | virtualenv | conda | ...): Conda
  • Relevant/affected Python packages and their versions: n/a

Expected behaviour

In a document with multiple cells, collapsing some of them improves usability.

Actual behaviour

It is not possible to collapse cells.

Some Details

I think defining #%% as (collapsible region start) shouldn't be very hard (I can try to submit a PR in 1-2 weekends if you agree with the idea).

Some implementation details should be evaluated though:

  • Behavior of Shift+Enter in the cell above
  • What to display if a region is collapsed (#%% Comment ... would be the default I think)
  • Behavior of collapsed regions affected by Run below|above
  • Visibility of Run Cell | Run Above | Run Below
@rchiodo
Copy link
Contributor

rchiodo commented Apr 18, 2019

I believe the only way to do this would be with the outline support VS Code has already:
https://code.visualstudio.com/api/references/vscode-api#FoldingRangeProvider

As far as I can tell, the start line remains visible, so you'd probably end up with something like:

#%%

#%%

#%%

With no clear indication what cell was what. Maybe combined with a decorator provider, it could also stick in the first line of code after the cell header.

@Diogo-Rossi
Copy link

I am also waiting for this feature. It may be simple as described by @DonJayamanne in microsoft/vscode-python#10503

As far as I can tell, the start line remains visible, so you'd probably end up with something like:

#%%

#%%

#%%

With no clear indication what cell was what. Maybe combined with a decorator provider, it could also stick in the first line of code after the cell header

The feature may be very similar to the #region/#endregion folding, already supported (#33).
Like in #region folding, it could accept comments after key word that defines the cell.

@richarddwang
Copy link

Is there anything new ? This should be set to important because I believe most of data science and ml guys write long jupyter notebook. And we are used to collapse those cells in Colab.

@rchiodo
Copy link
Contributor

rchiodo commented Jun 1, 2020

Sorry but this isn't on our radar at the moment. It's waiting for more people to up vote it.

@BBirdselllab
Copy link

BBirdselllab commented Jun 29, 2020

I upvoted. Both the other notebook platforms I use, Google Colabs & Mathematica, have this feature natively. The reasoning is sound: A lot of times in data sci applications certain cells are no longer required to be updated frequently and it reduces clutter. Not being able to collapse cells in VS Code's implementation of Jupyter notebooks has been being bugging me for months, and I was just thinking this weekend about porting some project files over to Colabs because it's a cleaner coding experience. It can't really be considered an edge feature request anymore. It's a minimal viable product requirement now in my opinion.

@Yannl
Copy link

Yannl commented Jul 14, 2020

I upvoted. It is the reason preventing me to use VSCode as a notebook editor.

The Microsoft team working on https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-github-issue-notebooks already implemented collaspsible section as well as drag and drop of cells in notebooks. (cf screenshot or VSCode insider required to test for now) Could you reuse their work?

@rchiodo
Copy link
Contributor

rchiodo commented Jul 14, 2020

The Microsoft team working on https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-github-issue-notebooks already implemented collaspsible section as well as drag and drop of cells in notebooks. (cf screenshot or VSCode insider required to test for now) Could you reuse their work?

Yes this is the plan. We'll be using that same API to rewrite how we support jupyter notebooks.

@mmcguffi
Copy link

Is there any update on this? I agree with previous comments that this is a huge headache when using VScode for Jupyter notebooks

@DonJayamanne

This comment has been minimized.

@rchiodo
Copy link
Contributor

rchiodo commented Aug 17, 2020

It should be noted that this issue microsoft/vscode-python#5227 is actually about adding another collapse region into a python file with cells. Cells are usually delineated with # %%.

This issue is not actively being pursued by our team but we welcome PRs if somebody else finds the time to get to this.

@rchiodo rchiodo changed the title Make cells collapsible Make cells collapsible in python files Aug 17, 2020
@PrateekArya
Copy link

PrateekArya commented Sep 4, 2020

@rchiodo Not sure if u are joking or serious but I think the original request was about collapsing the cells only. 😊

image

Also, isn't this same as microsoft/vscode-python#10503 and #957??

For those who are very desperate can type "if True:" on the top of the cells which you want to hide. Then u can fold them. It is surely not very efficient but it will serve the purpose for the time being. 😉

@rchiodo
Copy link
Contributor

rchiodo commented Sep 4, 2020

@PrateekArya not sure what you are wondering what I'm joking about? Submitting PRs? External contributors have done a bunch of work in the past. Collapsable regions is not high on our backlog at the moment but if somebody else really wants it, we would certainly love any submission.

I believe the solution to this request would be to add a FoldingRangeProvider:
https://code.visualstudio.com/api/references/vscode-api#FoldingRange

In our code where we create code lenses, it probably wouldn't be too hard to add a folding range provider somewhere there.

@DonJayamanne
Copy link
Contributor

For anyone interested here's a sample implementation (created for folding of docstrings).
We'd just need to identify cell markers (we have code for that too - to get the cell ranges).
We're happy to help anyone who wants to take a stab at this.

https://github.com/microsoft/vscode-python/blob/7c81cfcd06cdbfd91224489864ac3c9ae2c16d59/src/client/providers/docStringFoldingProvider.ts#L1-L2

@Diogo-Rossi
Copy link

@PrateekArya

For those who are very desperate can type "if True:" on the top of the cells which you want to hide. Then u can fold them. It is surely not very efficient but it will serve the purpose for the time being. 😉

I think it is better to use the region/endregion comment approach, which is somehow official.
Use if True: may lead to indentation erros in some cases . . .

Sorry, I really thought this issue was easy to provide (replacing region/endregion for two %% in sequence)

@DonJayamanne DonJayamanne transferred this issue from microsoft/vscode-python Nov 13, 2020
@pythlang
Copy link

Temp comment bump for now as I've just stumbled across this while working and also desire this... I may be able to take a stab at this in a few weeks here with some guidance while I have some free time.

Let me get back to this comment later.

Screen Shot 2020-11-30 at 13 37 04

@retorquere
Copy link

I believe the only way to do this would be with the outline support VS Code has already:
https://code.visualstudio.com/api/references/vscode-api#FoldingRangeProvider

As far as I can tell, the start line remains visible, so you'd probably end up with something like:

#%%

Would # %% # some comment work?

@ruestefa
Copy link

Would # %% # some comment work?

You can add comments directly after # %% even without an additional #.

@greazer greazer changed the title Make cells collapsible in python files Make cells collapsible in interactive window (i.e. python files) (This issue is NOT about collapsing cells in VS Code Notebook files) Apr 1, 2021
@chenhao1umbc
Copy link

It has been more than 2 years, since the original post...

@Diogo-Rossi
Copy link

For anyone still waiting for this (like me), I found a way that worked for me. It is the simple setting bellow (in case it help someone):

Expand the "Regular expression used to identify code cells" (in the settings) to also recognize the expression #\\s*region

"jupyter.codeRegularExpression": "^(#\\s*%%|#\\s*\\<codecell\\>|#\\s*In\\[\\d*?\\]|#\\s*In\\[ \\]|#\\s*region)" <- here

Now the cells also starts with # region and I can close the folding area with # endregion, making the cells collapsible.

@PrateekArya
Copy link

PrateekArya commented Jul 2, 2021

Yes, it works! But I am using a modified version as follows so that I can also write comments on the top of my cells:

image

Here if u just want to copy it:
^(#\s*region\s*%%|#\s*\<codecell\>|#\s*In\[\d*?\]|#\s*In\[ \])

Now, I write the cell headers as:

image

and the end of cell and starting of next cell as:

image

My folded cells looks like this:

image

@Diogo-Rossi
Copy link

Diogo-Rossi commented Jul 5, 2021

@PrateekArya

Nice! But just to make it clear: you regular expression requires that the cell starts with # region %%.

Basically, you have not added a new pattern but modified the regular # %% to # region %%.

That is ok. But if you find working with some file with the previous pattern %% that won't be a cell anymore.

BTW, any of that patterns allow you to write comments on the top of cells.

@PrateekArya
Copy link

Yes. I agree! :)

@greazer greazer removed the P2 label Jul 26, 2021
@greazer greazer added the interactive-window Impacts interactive window label Aug 3, 2021
@ghost
Copy link

ghost commented Sep 2, 2021

@Diogo-Rossi Thanks your fix works...I am currently using VSCode Insider V.1.60. Accidently I was able to make the usual # %% collapsible. Write # %% + press enter + tab + # region.

"# %%" folding works...
Folding_VSCode

@greazer greazer changed the title Make cells collapsible in interactive window (i.e. python files) (This issue is NOT about collapsing cells in VS Code Notebook files) Make cells (# %%) collapsible python files Oct 8, 2021
@greazer
Copy link
Member

greazer commented Oct 8, 2021

Really creative and interesting! Given the above you could take it to the next step and create a snippet.

  1. Ctrl+Shift+P -> Preferences: Configure User Snippets
  2. Pick a snippet config
  3. Use this as a snippet...
"Collapsible Python Cell": {
"scope": "python",
"prefix": "cc",
"body": [
	"# %%",
	"	# region",
	"$0"
	"   # endregion"
],
"description": "Insert a collapsible pythoh cell for execution in the Interactive Window"
}
  1. Use the snippet with Ctrl+Space, cc, <enter>

It's not the perfect solution, and you'll probably want to turn off the setting Jupyter: Collapse Cell Input Code By Default, but until we are able to create (or receive) a PR to bring a first-class experience, it may get you by.

@Diogo-Rossi
Copy link

Diogo-Rossi commented Jan 19, 2022

I found a better solution. Maybe you are interesting too.

  1. Install this extension
  2. Config the setting "editor.foldingStrategy" to "auto" (i.e.: "editor.foldingStrategy":"auto")
  3. Add the following in the settings:
"explicitFolding.rules": {
    "python": [
        {
            "separatorRegex": <PUT HERE THE SAME REGEX USED IN THE SETTING "jupyter.codeRegularExpression">
            "foldEOF":true
        },
        {
            "indentation": true,
            "offSide": true
        }
    ]
}

Now everything works.

  • All the expressions used in "jupyter.codeRegularExpression" define cells that are collapsible. (including #%%)
  • There is no need of any additional line (i.e. # endregion) to close the collapsible regions.
  • It now works exactly the same as the cells in spyder

@greazer greazer added feature-request Request for new features or functionality and removed enhancement labels May 4, 2022
@rebornix
Copy link
Member

rebornix commented May 6, 2022

@Diogo-Rossi thanks for the solution, it works seamlessly.

"explicitFolding.rules": {
        "python": [
            {
                "separatorRegex": "# %%",
                "foldEOF":true
            }
        ]
    }

We could probably register a similar folding range provider in Jupyter oob.

@otaolafranc
Copy link

Hello,
doing what was mentionned above, added the possibility to fold using "# %%" but it removed the possibility to fold for functions (def) or (for). anyone that could give me a hand to solve this issue?

I found a better solution. Maybe you are interesting too.

  1. Install this extension
  2. Config the setting "editor.foldingStrategy" to "auto" (i.e.: "editor.foldingStrategy":"auto")
  3. Add the following in the settings:
"explicitFolding.rules": {
    "python": [
        {
            "separatorRegex": <PUT HERE THE SAME REGEX USED IN THE SETTING "jupyter.codeRegularExpression">
            "foldEOF":true
        },
        {
            "indentation": true,
            "offSide": true
        }
    ]
}

Now everything works.

  • All the expressions used in "jupyter.codeRegularExpression" define cells that are collapsible. (including #%%)
  • There is no need of any additional line (i.e. # endregion) to close the collapsible regions.
  • It now works exactly the same as the cells in spyder

@Diogo-Rossi
Copy link

@otaolafranc
It seems we don't need this suggestion anymore to fold using #%%. It is now part of the extension.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 29, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feature-request Request for new features or functionality interactive-window Impacts interactive window
Projects
None yet
Development

Successfully merging a pull request may close this issue.