sublimehq / sublime_text

Issue tracker for Sublime Text
https://www.sublimetext.com
804 stars 39 forks source link

Code Folding should be based on syntax, not on indentation level #101

Closed iamntz closed 2 years ago

iamntz commented 11 years ago

Just to prevent things like #100

OliverJAsh commented 11 years ago

:+1: I see this as quite important.

FichteFoll commented 11 years ago

It's, by the way, the highest voted feature on userecho.

andrewchen5678 commented 9 years ago

This makes me want to use another text editor instead because it is important for me to fold not based on indentation just like all other editors

RonnyPfannschmidt commented 9 years ago

as a partial hopefully more easy solution to this, how about making folding aware of basic syntax groups

for example :

iamntz commented 9 years ago

Hi guys. I was digging into default packages and it seems that there is a fold.py file, that deal with (almost?) everything related to folding.

Although I'm not sure how, I think this can be fixed by overwriting this default package.

What do you think?

FichteFoll commented 9 years ago

I think that the folding arrows are decoupled from fold.py and call the internal api directly.

iamntz commented 9 years ago

Hmm, yeah, i guess you're right. I was too excited about my great discovery and I didn't looked further :-1:

TWiStErRob commented 9 years ago

Here's another example of this:

<inventory>
    <item name="Convector Heater">
        <description>Sencor 750W + 1250W = 2000W
Dial temperature setting
Fan heat distribution</description>
    </item>
</inventory>

If I fold this at <inventory> I get:

<inventory>...
Dial temperature setting
Fan heat distribution</description>
    </item>
</inventory>

Note that I can't change the format of the xml because then the description would have weird whitespaces in it when read by applications (unlike HTML whitespace collapsing). I tried CDATA blocks and the result is the same.

Another thing to note is that I can't even fold at <item> for some reason.

These two issues essentially render xml/html folding useless (dare to say IE does a better job ;). I think severity needs a little bump on this 2-year-old bug.

FichteFoll commented 9 years ago

Sublime Text does not offer folding arrows for single further-indented lines.

wiktor-obrebski commented 8 years ago

it would be very nice to have it. it's quite a shame that such good editor have problems with so basic thing.

jnwatts commented 8 years ago

I just spent a few hours digging into this, and for my own needs I've arrived at a plugin+keymap work-around that provides a keyboard shortcut that folds based on scope rather than indent. Using the Chain of Command plugin:

    {
        "keys": ["ctrl+shift+["],
        "command": "chain", "args": {
            "commands": [
                ["expand_selection", {"to": "scope"}],
                ["fold"],
                ["move", {"by": "lines", "forward": true}]
            ]
        },
    },
    {
        "keys": ["ctrl+shift+]"],
        "command": "chain", "args": {
            "commands": [
                ["unfold"],
                ["move", {"by": "lines", "forward": true}]
            ]
        },
    },

With a real plugin or modification of Sublime itself, additional logic could be added to search specific types of scope, as the above will happily collapse a single word if it has its own scope.

For those who are interested in going deeper/further, the built in folding logic can be found in default.sublime-package's fold.py (Not sure where the official source for this is).

FichteFoll commented 8 years ago

There is no official source online because it's a "core" package. You can technically only refer to the bundled version.

The other packages have been released here: https://github.com/sublimehq/Packages

ghost commented 8 years ago

If implemented, please make sure Plain Text is included in the syntax definition because I use code folding for text files a lot.

I organize my lists in .txt files like outined info, and indent sections for better navigation because of no Go To Symbol support.

juanitogan commented 7 years ago

At the moment, I would be happy to just fold a block of data that has no indent. No syntax folding required. Would be useful for folding comments as well like some editors do. Basic logic: If three or more sequential lines have no indent (before a blank or indented line, or EOF), allow the leading block of lines to be folded, leaving the last line unfolded to allow current folding (required, logically, whether the last line is currently foldable or not).

Fold this:

0000
1111
2222
3333
  foo

to this:

0000 [...]
3333
  foo
braver commented 7 years ago

I'd say a lot of the strength of Sublime's folding actually comes from a complete lack of understanding or logic. Perhaps it's a bit weird if you're used to other systems, but it's super flexible and works the same way for any file.

Which results in problems for the default indentation action when indentation is missing, or indentation is broken as in the example xml's. However, you usually don't want to see indentation like that in pretty much any language.

Examples demonstrating what you're asking for:

foldit

Here I created a selection simply by holding shift, then moving the caret up. The selection can then be folded using the keyboard shortcut or the menu entry.

Another example demonstrating how to deal with the xml example:

foldit-xml

Here, a selection was created by hitting the keyboard shortcut for Expand Selection To Tag, and then folded by hitting the shortcut for that.

Sure, in each case creating the selection and then folding is more work that simply hitting the Fold shortcut, but that's the price you pay for being able to fold absolutely any range you want.

I'm not saying it couldn't be better. Some language hints might help the default fold action to guess the correct range to fold more often. Not because Sublime can't fold it right now, but because it would make folding more discoverable and a tiny bit more efficient. I'd wager Sublime's folding limitations are more serious when it comes to unfolding.

FichteFoll commented 6 years ago

A random idea I just had would be to write a plugin that takes care of folding certain syntax-specific regions, such as #pragma region ARegion (to #pragma endregion) in C++ or a similar thing in VB.NET, whose syntax I forgot.

It could display an inline phantom at the end of the line where the fold begins and upon clicking on that, fold the respective region. The hardest part would be finding the end of the region, actually, though that's still quite manageable. User experience is basically the same as currently, except the folding indicator is on the right side of the line.

MReome commented 6 years ago

If this was fixed I would happily pay for sublime text, but the folding breaks so frequently in the C/C++ code-bases I work on that it's blocking me from making sublime-text my IDE of choice. Why is a way to define the start and ends of fold regions not just incorporated into the language syntaxes?

A 5-year old bug report to get something as fundamental as code-folding working correctly does not shine a positive light on sublime-text as a product, nor does the fact that such an significant bug is listed as a feature request.

FHTheron commented 6 years ago

Would be nice to have yes, but worth mentioning that VSCode does this the same way as SublimeText. SciTE and VS2008 does it by syntax though.

TWiStErRob commented 6 years ago

@FHTheron someone else doing a bad job shouldn't justify following suit. It should be the opposite: lead by example.

FichteFoll commented 6 years ago

Note that C and C++ are particularly dodgy because of their preprocessor, which can insert arbitrary strings at arbitrary locations and modify syntax flow with it – not even considering that through #ifdef branches you get to close the same scope at potentially multiple locations or even open different scopes which should then be closed at the same location.

TWiStErRob commented 6 years ago

Exception, not the norm. Even if the implementation falls back for C files containing preprocessor directives, it is still possible to support the other 100 languages with a better behaviour.

FHTheron commented 6 years ago

I'm using the (wonderful) BracketHighlighter plugin to get folding that works on syntax. It also lets you fold ifdef preproc blocks.

I use the normal unfold command to expand the block again. So at this point if I could only make the folding arrow in the gutter do what my keybinding now does it would be great. Perhaps it is possible (or feature-request it) to override a normal built-in command, in this case replace the fold command for C/C++ (and others) with the BracketHighlighter fold command.

Reference: bh_core.sublime-settings:

"match_only_adjacent": false,
"bracket_outside_adjacent": false, // Avoids an oddity when next to the end of a string.

Keymap:

    // Unbind these (indent/unindent) so that the key-chord below works.
    { "keys": ["ctrl+["], "command": "unbound" },
    { "keys": ["ctrl+]"], "command": "unbound" },

    { "keys": ["ctrl+\\", "ctrl+["],
        "command": "bh_async_key",
        "args": {
            "plugin": {
                "type": ["__all__"],
                "command" : "bh_modules.foldbracket"
            }
        },
// This means to disable folding a string, but in turn doesn't work if the cursor is at
// the left outside a string. The context check should be replaced with a regex check,
// but simpler just to not have it.
//        "context": [
//            { "key": "selector", "operator": "not_equal",
//                "operand": "string" }
//        ]
    },
    { "keys": ["ctrl+\\", "ctrl+]"],
        "command": "chain",
        "args": {
            "commands": [
                ["unfold"],
                // Now trigger a cursor move to cancel the selection and make it look like 
                // we popped the block open without moving the cursor.
                ["move", {"by": "characters", "forward": false}],
            ]
        },
    },
Carpette commented 6 years ago

This is still an issue 5 years later. What does it need to get this fixed ? What can we do ?

jokoon commented 6 years ago

FHTheron do you have a shortcut binding that does the same, but fold either everything or everything which is at the same scope?

dotbmp commented 6 years ago

Honestly this is the biggest thing that bugs me about Sublime. I use ctrl+k+1 and friends to collapse code across entire files, but when I'm going through and unfolding/refolding sections reviewing or editing code and I hit a one-liner, it drives me crazy. To refold that section, I'd have to fold everything in the entire file. A good example of why this is annoying is editing my custom assembler: Image Everything is neatly folded except that glaring one-liner.

The logic for this is very simple, it's an intuitive extension of the current folding scheme, and there's no clear reason it doesn't make sense to do. I don't know how an editor as exceptional as Sublime winds up with such an obvious issue for so long.

FHTheron commented 6 years ago

FHTheron do you have a shortcut binding that does the same, but fold either everything or everything which is at the same scope?

No, but you could combine selection and fold commands. For example:

command: expand_selection {"to": "indentation"}
command: fold

Then bind that sequence to a key using the Chain of Command plugin.

If you want to do that but get multiple selections at a time, maybe look for another plugin that does something like select regions by scope identifier or such.

jokoon commented 5 years ago

I even wonder, are the devs working on it, are they aware at all, did the dev responsible quit dev'ing ST?

For the anecdote, when using a braced language, I just indent the last brace like this:

void f(){
    int stuff = 3;
    }

As I was asked on IRC, I want to explain why I'm using a lot of functions, in a file which can reach 1000 lines, so folding is mandatory if I want to find back code. CTRL+F is not always useful.

I admit that I was told about "open in a new view" which is useful, but folding makes browsing code so, so comfortable. I won't miss the opportunity to mention that so far, only MSVC and atom fold code using syntax. I tried atom but abandoned using it since I could not modify grammar files without making a huge bloated package.

Brackets is also an editor that fold brackets, it doesn't seem like a very complex editor, but it's web oriented.

I guess we won't even see a sublime text V4? I'm still a fan of ST on linux since CLion is so expensive.

wbond commented 5 years ago

We are actively working on Sublime Text. The forum is our official channel of communication about things like development work. https://www.sublimetext.com/3dev is where new dev releases are posted.

I am aware of this issue. We are not currently working on it.

AmjadHD commented 5 years ago

just curious, what are you working on now ?

stofte commented 5 years ago

Sublimes almost perfect. But this is really an eye sore that lowers the daily usability, esp for quick inspection tasks. I guess I should go back to Notepad++ and its insane plugin system, at least that works.

bland328 commented 5 years ago

To whom might I send money to get syntax-driven, user-customizable folding? Or, at least, exposure of the folding API so that the community can make it happen?

And how much would it take? Does Kickstarter allow fund-raising for bribes? ;)

Sublime Text is a thing of beauty, and I'll use it all day, every day, as soon as this is addressed.

For now, back to TextMate, which is...fine enough, I guess. Sigh.

OdatNurd commented 5 years ago

The api includes view.fold() to fold the text of a given region, view.unfold() to unfold the text in a list of regions, view.is_folded() to detect if a region is folded or not and view.folded_regions() to get a list of folded regions that already exist (these last two are undocumented).

So fundamentally it seems like most of the missing part is someone willing to write the code that would analyze the file to determine where the folding should happen.

wbond commented 5 years ago

I don't believe we are currently accepting financial incentives to influence feature development, sorry! 🙂

I have seen this request, but it hasn't been something that has come to the front of development priorities.

TWiStErRob commented 5 years ago

Would contribute to that Kickstarter...

bland328 commented 5 years ago

I have seen this request, but it hasn't been something that has come to the front of development priorities.

Thanks for your response to my somewhat tongue-in-cheek post, @wbond!

Does your response mean that there's no philosophical or strategic opposition at Sublime HQ, but simply that enhanced code folding isn't a priority?

I ask so that I can figure out whether to keep my fingers crossed, as they are starting to cramp ;)

wbond commented 5 years ago

For more fundamental components to the editor component, things such as folding, word wrapping, syntax definitions, completions, etc it can be hard to make significant changes without breaking existing functionality or the workflow of users.

From my perspective, it would seem logical that syntax-based folding could be opt-in on a syntax basis. That is to say, if the syntax indicates it provides sufficient info, then perhaps we could build a system that would fold using the syntax scopes.

That said, I've only been working on the ST codebase a couple of years, and have not worked on folding at all. Jon wrote it all a number of years before I joined the company. He would know what potential issues we could run into, and generally makes the call on major bits of development.

All that to say, I don't think syntax-based folding is ruled out at this point, but I just know that we haven't discussed it for the next dev cycle.

idzikovsky commented 5 years ago

FYI: code folding based on indentation does not suit almost for all cases of using HEREDOC, which affects experience of editing code written in languages like Python, PHP, Perl and especially Shell.

Carpette commented 5 years ago

You would make a looooot fo devs really happy with that feature (it's quite a basic one btw. I don't know any other text editor that doesn't have it... but i don't know all of them of course).

As a dev who has worked with Java, Php, AS2, AS3, C++, LUA, C#, and maybe some others that i've forgotten, i still don't understand why this isn't a feature in ST.

jokoon commented 5 years ago

You would make a looooot fo devs really happy with that feature

And me! This features is quite expected when you have a long files with a lot of code.

(it's quite a basic one btw. I don't know any other text editor that doesn't have it... but i don't know all of them of course).

So far I only see MSVC, and maybe intelliJ but I'm not sure. It's not really a basic feature as it require the editor to have functionalities that approach the ones of an actual parser/compiler, which are not trivial.

TWiStErRob commented 5 years ago

require the editor to have functionalities that approach the ones of an actual parser/compiler, which are not trivial.

All the prerequisites are there: highlighting gives you the parsing, and there's also matching braces highlight which is where the folding points should be.

stormriderstudios commented 5 years ago

I too would LOVE to see this feature. The trailing } when working in PHP is obnoxious and while indenting the } is an option it's not a very pleasant one!

Please, please, please consider elevating this issue - even as a disabled-by-default beta test!

qgates commented 5 years ago

I too would love to see 'intelligent' folding based on syntax definitions and scopes. Hope it's going to get some attention soon.

However there are cases where dumb 'indent based' folding is still useful, especially when dealing with text formats/syntaxes not known to Sublime. So I'd like the old behaviour to remain in as an option or fallback.

dsideb commented 5 years ago

I'd raise the importance of this issue as well. It's a small cut but that keep happening hundred of times each week.

Remillard commented 5 years ago

I'm at a point where I would really appreciate syntax based code folding support as well for daily use as well as additional package development projects.

Gotterbild commented 4 years ago

I would appreciate very much if it will become available to fold between comments. It is handy to group something by adding comments like this: image

To add folding feature in this case I will need to add additional indentation, which mill make project linter mad (for a good purpose).

It would be great if my favorite Sublime Text (which I payed for BTW) to detect such cases and add folding icon to the left of // Images, // Presets and // Resets. So I can fold from comment to comment.

FichteFoll commented 4 years ago

It would be great if my favorite Sublime Text (which I payed for BTW) to detect such cases and add folding icon to the left of // Images, // Presets and // Resets.

That's a special use case, however, because not everyone uses comments like that. Also, it's not really related to syntax, although it may be related to being unable to define custom fold regions for ST to show fold arrows at. Maybe an API that allows providing regions to be folded would be useful for your particular case, but that isn't exactly in line with what this issue requests.

Either way, you can provide this functionality through a custom plugin. Refer to Fold Python Docstrings for a package with a similar use case.

aone2020 commented 4 years ago

unbelievable, 2020, still NO

troygilbert commented 3 years ago

To be honest, I'd be thrilled to simply have the current code-folding but have it work on single-line blocks. Like, I've tried and I can't imagine a scenario where it makes sense to not give the user the option to fold a block that has a single line in it (but folding a block with 2 lines in it works perfectly!).

sanyi0411 commented 3 years ago

First comment here is from 2013. Now it's 2021 and still no change. Please someone do something

boycce commented 3 years ago

wadamygonnadooo! image