You need to enable JavaScript to run this app. 如何在Atom的自定义命令脚本中切换为JSON语法模式?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Atom的自定义命令脚本中切换为JSON语法模式?

Atom自定义JSON格式化一键命令解决方案

直接替换为以下完整配置即可实现全部需求:

atom.commands.add("atom-workspace", {
  "custom:prettify-json": function() {
    const editor = atom.workspace.getActiveTextEditor()
    // 无激活编辑器时直接返回,避免报错
    if (!editor) return true
    const view = atom.views.getView(editor)
    
    // 1. 全选文本内容
    atom.commands.dispatch(view, "core:select-all")
    // 2. 执行JSON格式化
    atom.commands.dispatch(view, "pretty-json:prettify")
    // 3. 直接切换为JSON语法模式
    const jsonGrammar = atom.grammars.getGrammar('source.json')
    if (jsonGrammar) editor.setGrammar(jsonGrammar)

    return true
  }
})

核心逻辑说明

不需要调用grammar-selector:show弹出选择框,Atom提供了直接修改当前编辑器语法的原生API:

  • 调用atom.grammars.getGrammar('source.json')即可获取JSON语法对应的配置对象,source.json是JSON语法的唯一scope标识
  • 调用当前激活编辑器实例的setGrammar()方法,传入上面获取的语法对象,即可直接完成语法模式切换

内容的提问来源于stack exchange,提问作者Gerry Gry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 23:54:05