Sublime Forum

Chage "Hello, World!" to insert at cursor position

#1

Can anyone please explain to me how to change the insertion point of the text (“Hello, World!”) to wherever the cursor happens to be whenever the plugin is activated?

[code]import sublime, sublime_plugin

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

0 Likes

#2

You will use view.sel() to get the cursors. This returns a list of regions, since multiple cursors are supported :smile:. Anyways, if you want to assume the first cursor, and the beginning of the region you can do the following.

import sublime, sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
   def run(self, edit):
      self.view.insert(edit, self.view.sel()[0].begin(), "Hello, World!")

Probably worthwhile to take a look at the api if you haven’t already.

ST2: sublimetext.com/docs/2/api_reference.html
ST3: sublimetext.com/docs/3/api_reference.html

0 Likes

#3

Thank you – here are my lessons learned so far:

  1. Variables are set AFTER self.view.insert, not in the middle of.

  2. Python is sensitive to indentations in the form of white space, with incremental white space indentations.

  3. Saving a file with the Python console open helps to debug.

  4. To try out the plugin in the Python console, I need to be aware that this syntax is no longer supported in ST2 [view.runCommand(‘example’)] – instead, I should use: view.run_command(‘example’)

  5. To utilize dir() in the Python console, there are many variables that could be inserted in between the parenthesis – I will need to read more documentation regarding the various usages.

  6. Examples of code that will work in the Sublime Text plugins can be found in unrelated Python scripts, because the language is the same.
    docs.python.org/2/library/os.path.html

0 Likes

#4

You must be looking at old versions of the api documentation. You want view.run_command. Not view.runCommand. Check the links I provided. Also, as kind of a getting started for plugins, consider going through the following tutorial (link). You may also want to go through some general python tutorials first anyways. Diving straight into plugin development without some understanding of the language can make it more difficult than it needs to be. “dir(variable)” will list the attributes (well I guess it really depends on how the dir method was implemented for that class) for that class. Normally this will show you things like methods and variables associated with that class.

As a future reference, you may want to look at the porting guide, for when you decided to write plugins for ST3 (link). There are some changes to the ST3 api, when compared to ST2, so you should probably look at that as well.

0 Likes

#5

This tutorial has been extremely helpful. I have updated my list of lessons learned so far. Thank you very much! :smiley:

0 Likes