Sublime Forum

Help needed with a plugin in development

#1

I’m new to python but making some progress. I’m developing a plugin to clean up code in R based on a style guide. I just need to make one replacement work and I can deal with the rest.

Here is one such clean up operation that I would need to do on a .r script. A standard function definition looks like this:

function_name <- function(params) {
# stuff
}

The above is the right style. Sometimes code can look like one of the following:

function_name <- function(params) 
{
# stuff
}

or like this:

function_name <- function(params) 
            {
# stuff
}

etc.

I’ve written a regexp to capture anything between a ) and a {. I just need to reduce that to a single space between the two and add a newline after {

Below is a prototype of a package that I have going with filler comments where I can’t figure stuff out.

[code]import sublime, sublime_plugin

class PrettyRCommand(sublime_plugin.TextCommand):
def run(self, edit):
sel = self.view.sel()[0]

  poorly_formatted_functions = self.view.find('\\)\\s*(.*?)\\s\\{', sel.begin())
 #split poorly formatted code into two regions
 # add single space between region A and region B
 # insert new line after region B
 #insert corrected_code back into same spot

  self.view.insert(edit, sel.begin(), corrected_code)

[/code]

Currently this would work with a keybinding that looks like this:

{ "keys": "ctrl+shift+k"], "command": "pretty_r" }

Issues: Not sure how to get the replacement in. Second, I don’t just want to do this on just selected text, I want to do this for the entire document. Ideas?

0 Likes

#2

Try this:

[code]import sublime, sublime_plugin

class PrettyRCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0,self.view.size())
results = self.view.find_all("\)\s*\n\s*\{")
for r in results:
self.view.replace(edit, r, “) {”)[/code]

0 Likes

#3

This version will only run within files with extension ‘.r’:

[code]import sublime, sublime_plugin

class PrettyRCommand(sublime_plugin.TextCommand):
def run(self, edit):
if not self.view.file_name()-2:] == ‘.r’:
print ‘not in r’
return
region = sublime.Region(0,self.view.size())
results = self.view.find_all("\)\s*\n\s*\{")
for r in results:
self.view.replace(edit, r, “) {”)[/code]

0 Likes

#4

[quote=“maiasaura”]
I’ve written a regexp to capture anything between a ) and a {. I just need to reduce that to a single space between the two and add a newline after {

Issues: Not sure how to get the replacement in. Second, I don’t just want to do this on just selected text, I want to do this for the entire document. Ideas?[/quote]

View
substr
size
find_all
replace

0 Likes