栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 FilesLLVMbinclang-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 FilesLLVMbinclang-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:Usersmain.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 TextPackagesUserformat.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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号