2

I'm trying to create a snippets to automatically generate getters and setters in java

The problem is that i don't know how to split the string taken from $TM_SELECTED_TEXT

The code needs to be inserted below the constructor

After I select the text it's look like this String name

Here's the code, I miss split string and the insert of the code under constructor because I have no idea how to do it

<snippet>
  <content><![CDATA[
    public void set$TM_SELECTED_TEXT($TM_SELECTED_TEXT $TM_SELECTED_TEXT) {
      this.$TM_SELECTED_TEXT = $TM_SELECTED_TEXT;
    }

    public $TM_SELECTED_TEXT get$TM_SELECTED_TEXT {
      return this.$TM_SELECTED_TEXT;
    }
  ]]></content>
  <tabTrigger>getter_setter</tabTrigger>
  <scope>source.java</scope>
</snippet>

I also would like to know how to change the first letter of the varname to uppercase just to make it look getName and setName instead of setname and getname*

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
nautilor
  • 106
  • 12

1 Answers1

2

You can split string in snippet using regexp. But I advice to create plugin instad of snippet. You can use python split() function in sublime plugin and capitalize() to change the first letter of the varname to uppercase.

To access selection in plugin use this construction:

self.view.sel()[0]

to insert getter or setter code use:

self.view.replace(edit, region, content)

or:

self.view.insert(edit, position, content)

This code works for me:

import sublime, sublime_plugin

class javamagicCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        snippet_code = ''' public void set$TM_SELECTED_PART1($TM_SELECTED_PART1 $TM_SELECTED_PART2) {
      this.$TM_SELECTED_PART1 = $TM_SELECTED_PART1;
    }'''
        new_content = ''

        for selection in self.view.sel():
            selection_content = self.view.substr(selection)
            if selection_content.find('.') > 0:
                parts = selection_content.split('.')
                new_content = snippet_code.replace('$TM_SELECTED_PART1', parts[0])
                new_content = new_content.replace('$TM_SELECTED_PART2', parts[1])
                self.view.insert(edit, selection.begin(), new_content)
            else:
                sublime.status_message('wrong selection') # statusline message
                # sublime.message_dialog('wrong selection') # popup message

        for selection in self.view.sel():
            self.view.erase(edit, selection)

        #print('done') # debug output to console
Community
  • 1
  • 1
Vasin Yuriy
  • 484
  • 5
  • 13