Sublime Forum

First plugin ever

#1

Could you help me with my first plugin? I have a file that is delimited by tilde’s “~”. I would like to insert a new line after the tilde character. I would also like to insert a new line before the string of characters “INS*”. I gave it a first stab, I had written some python years ago, by following the ROT13 example on the website. This is what I cam up with:

[code]import sublime, sublime_plugin

class X12Command(sublime_plugin.TextCommand):
def run(self, view, args):
for region in view.sel():
if not region.empty():
s = view.substr(region)
s = s.replace(’~’, ‘~\n’)
s = s.replace(‘INS*’, ‘\nINS*’)
view.replace(region, s)[/code]

When I run it in the console I don’t get any output:

view.run_command(‘X12’)

But there are no errors. The text in the editor window does not update and there is no other feedback. I tried dropping a print statement in the run method but it didn’t write to the command window like I thought it would.

Any help is appreciated. Thanks!

0 Likes

View.replace() regex
#2

Have you selected the whole document before running the command?

0 Likes

#3

I just tried that and it didn’t seem to change anything.

0 Likes

#4

Couple of things, try the following “view.run_command(“x12”)”. Also, I think your the arguments for view.replace is wrong. According to the API reference it should be “view.replace(edit, region, string)”

0 Likes

#5

Yes, the default plugin is:

[code]import sublime, sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.insert(edit, 0, “Hello, World!”)[/code]

which supplies edit, and view is available as self.view.

You may possible need ‘x_12’ to run your command.

0 Likes

#6

I am sorry that it took me so long to get back to this. I was off work Friday and swamped Monday. I cracked the plugin back open this morning and compared it to the one in the template. Evidently the source code I based my plugin on was from an older API. With your suggestions and using the template I was able to get it to work.

import sublime, sublime_plugin

class X12Command(sublime_plugin.TextCommand):
	def run(self, edit):
		for region in self.view.sel():
			if not region.empty():
				s = self.view.substr(region)
				s = s.replace('~', '~\n')
				s = s.replace('INS*', '\nINS*')
				self.view.replace(edit, region, s)

And this Run command:

>>> view.run_command('x12')

And it worked. Now all I have to do is get the command registered and I am in business.

I appreciate all of your help.

Thanks!

0 Likes

#7

One more question though. Is there a way I can make this run against all text in the file and not just the selected text?

0 Likes

#8
reg = sublime.Region(0, self.view.size())
text = self.view.substr(reg)
# ...
self.view.replace(edit, reg, text)
0 Likes

#9

Works like a charm. Thank you very much!

0 Likes