1

I am trying to add uncrustify for my C++ code formatting in Sublime Editor 2.

I know that there are some ways to run external process in SE2. But the main problem is that cannot update the buffer (view) with my code, when the formatting is done.

Can somebody sketch a plugin which will run external process on the content of the current buffer and then update it?

Daniel Beck
  • 111,893
user14416
  • 378

1 Answers1

2

The following text plugin replaces all lowercase letters in the file with their uppercase equivalent. The bash -c call was a workaround to provide a useful example for the (uncommon) case of a command acting on large argument input: usually they deal with files or standard in.

To use your own command, replace the first three list entries in the first Popen argument with your own, the last is the entire buffer content.

import sublime, sublime_plugin, subprocess

def insert_output(view, edit):
    r = sublime.Region(0, view.size())
    try:
        proc = subprocess.Popen( [ "bash", "-c", 'echo "$0" | tr [a-z] [A-Z]', view.substr(r) ], stdout=subprocess.PIPE )
        output = proc.communicate()[0]
        view.replace(edit, r, output)
    except:
        pass


class ReplaceWithOutputCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        e = self.view.begin_edit()
        insert_output(self.view, e)
        self.view.end_edit(e)

To create a menu item, add an entry such as the following to Main.sublime-menu in the User package:

{"command": "replace_with_output", "caption": "Replace with Output" }

Before:

Screenshot

After:

Screenshot

Daniel Beck
  • 111,893