sublime text自定义clang format插件格式化C++代码

本文内容为在windows平台上通过 sublime text开发自定义插件实现调用clang format对C/C++代码进行格式化。需要安装LLVM,下载链接:https://github.com/llvm/llvm-project/releases

例如安装 LLVM-14.0.5-win64.exe。安装后C:\Program Files\LLVM\bin\clang-format.exe可用。

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创建一个format插件(by Tools > Developer > New Plugin),内容如上,保存为Sublime Text\Packages\User\format.py。

view.run_command('format'),字符串里面是插件名称

ctrl+`打开命令行,然后运行上述命令对当前文件进行格式化

创建自定义插件参考:

ref

Sublime Text 插件开发流程 - 简书

Creating Sublime Text 3 Plugins - Part 1 | CNP

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

扫描二维码关注公众号,回复: 15754074 查看本文章

猜你喜欢

转载自blog.csdn.net/u013701860/article/details/125335616
今日推荐