Sublime text custom clang format plugin to format C++ code

The content of this article is to develop a custom plug-in through sublime text on the windows platform to call clang format to format the C/C++ code. LLVM needs to be installed, download link: https://github.com/llvm/llvm-project/releases

For example install  LLVM-14.0.5-win64.exe . C:\Program Files\LLVM\bin\clang-format.exe is available after installation.

import sublime
import sublime_plugin
import subprocess

class FormatCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # self.format1(edit)
        self.format2(edit)

    def format_file(self, file_path):
        clang_format_path = r'"C:\Program Files\LLVM\bin\clang-format.exe"'

        cfg_file = r"D:\Users\.clang-format"
        cfg_cmd = ' -style=file:' + cfg_file

        # need llvm > 14.0
        cmd_str = clang_format_path + cfg_cmd + ' -i ' + file_path
        p = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE).communicate()[0]

    def format1(self, edit):
        """direct format current file"""
        file_path = self.view.window().active_view().file_name()
        self.format_file(file_path)

    def format2(self, edit):
        """save file to temp file and format"""
        whole_region = sublime.Region(0, self.view.size())
        text = self.view.substr(sublime.Region(0, self.view.size()))

        file_path = r'D:\Users\main.cpp'
        with open(file_path, "w") as f:
            f.write(text)

        self.format_file(file_path)

        with open(file_path, "r") as f:
            formatted_text = f.read()

        self.view.replace(edit, whole_region, formatted_text)

clang format creates a format plugin (by Tools > Developer > New Plugin), the content is as above, save it as Sublime Text\Packages\User\format.py.

view.run_command('format'), the string is the plug-in name

ctrl+`Open the command line, and then run the above command to format the current file

Create a custom plugin reference:

ref

Sublime Text plug-in development process - short book

Creating Sublime Text 3 Plugins - Part 1 | CNP

https://betterprogramming.pub/how-to-create-your-own-sublime-text-plugin-2731e75f52d5

Guess you like

Origin blog.csdn.net/u013701860/article/details/125335616