Sublime Forum

How to find function body regions?

#1

Hello, I’m trying to make a plugin for the first time, but I’ve hit a roadblock right away. I’m trying to make a simple plugin to fold all anonymous functions in a Javascript file.

For example I want:

var sum = function (a, b) { return a + b; };

to become:

var sum = function (a, b) { [...] };

But how do I select the function body?
So far I was trying something like

import sublime, sublime_plugin

class FoldCommand(sublime_plugin.TextCommand): def run(self, edit): regions = self.view.find_by_selector('entity.name.function.js') self.view.fold(regions)

But this actually folds the word “function”. How do I get the region insid the function body?

0 Likes

#2

Not sure off the top of my head, but ScopeHunter might help you find the info you need.

Another option is to write a custom RegEx pattern & use:

view.find_all ( your_RegEx_Pattern )

0 Likes

#3

You can try the scope meta.function
And to know the scope you can use the built-in command ctrl+alt+shift+p (available in menu Tools->developer->Show scope name)

0 Likes

#4

@Clams

I just checked & I do not have access to either of those functions ( Tools/Developer & Show Scope Name ),

Do you have to enable those somehow?

0 Likes

#5

It’s added since ST 3105, however, ctrl+alt+shift+p still shows the scope on the status bar.

0 Likes

#6

Thanks for the answers! That helps a lot!

However, i’ve been checking everywhere the scope and it always seems to be something like meta.group.braces.curly, it doesn’t seem to detect specifically that it’s a function body. In a lot of cases, this also collapses object literals, which is not what I want.
Maybe I need to create my own syntax first…?

Using regexp also seems interesting. Though I’m a little worried about nested functions, but this could potentially be a solution.

0 Likes

#7

If I remember correctly you cannot do this on a reliable way, as ST has no idea what JavaScript is about. It cannot tell when a function ends… however, you may be able to move from the function declaration, to the first “{” to the right, and then select the scope (manually done with CTRL+SHIFT+SPACE), which kinda… in probably most situations will select the function body…

You may be able to do all that programativelly (I cannot spell this word)

0 Likes

#8

The ‘function (a,b) {…}’ pattern is totally recognizable with Sublime syntaxes, if it’s not recognized it should be added to the Javascript syntax.

0 Likes

#9

Well, in the end I got it working… In a probably very inefficient way of collecting all braces and then checking if the left of the brace has a punctuation.definition.parameters.end.js region.

The sublime syntax definitions go way over my head. But this definitely seems like something sublime should be able to handle easily. If there’s a proper solution I’d love to know about it.

0 Likes