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+`打开命令行,然后运行上述命令对当前文件进行格式化

导出配置,例如

clang-format -style=Google -dump-config > .clang-format

clang-format常用配置参考

SortIncludes:  true
TabWidth:    2
ColumnLimit:   120

创建自定义插件参考:

ref

Sublime Text 插件开发流程 - 简书

Creating Sublime Text 3 Plugins - Part 1 | CNP

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Luchang-Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值