參加你附近的 ,瞭解 VS Code 中的 AI 輔助開發。

貢獻點

貢獻點是您在 package.json 擴充套件清單contributes 欄位中進行的一組 JSON 宣告。您的擴充套件透過註冊貢獻點來擴充套件 Visual Studio Code 中的各種功能。以下是所有可用貢獻點的列表:

contributes.authentication

貢獻身份驗證提供程式。這將為您的提供程式設定啟用事件,並將其顯示在擴充套件的功能中。

{
  "contributes": {
    "authentication": [
      {
        "label": "Azure DevOps",
        "id": "azuredevops"
      }
    ]
  }
}

contributes.breakpoints

通常,偵錯程式擴充套件也會有一個 contributes.breakpoints 條目,其中擴充套件列出了將啟用設定斷點的語言檔案型別。

{
  "contributes": {
    "breakpoints": [
      {
        "language": "javascript"
      },
      {
        "language": "javascriptreact"
      }
    ]
  }
}

contributes.colors

貢獻新的可主題化顏色。這些顏色可以由擴充套件在編輯器裝飾器和狀態列中使用。定義後,使用者可以在 workspace.colorCustomization 設定中自定義顏色,使用者主題可以設定顏色值。

{
  "contributes": {
    "colors": [
      {
        "id": "superstatus.error",
        "description": "Color for error message in the status bar.",
        "defaults": {
          "dark": "errorForeground",
          "light": "errorForeground",
          "highContrast": "#010203",
          "highContrastLight": "#feedc3"
        }
      }
    ]
  }
}

顏色預設值可以為淺色、深色和高對比度主題定義,並且可以是現有顏色的引用或十六進位制顏色值

擴充套件可以透過 ThemeColor API 使用新的和現有的主題顏色。

const errorColor = new vscode.ThemeColor('superstatus.error');

contributes.commands

為命令貢獻 UI,包括標題和(可選)圖示、類別和啟用狀態。啟用狀態透過when 子句表示。預設情況下,命令顯示在命令面板⇧⌘P(Windows, Linux Ctrl+Shift+P)中,但它們也可以顯示在其他選單中。

貢獻命令的呈現方式取決於包含的選單。例如,命令面板會在命令前加上其 category,以便於分組。然而,命令面板不顯示圖示,也不顯示已停用的命令。另一方面,編輯器上下文選單顯示已停用的專案,但不顯示類別標籤。

注意: 當命令被呼叫時(透過鍵繫結、命令面板、任何其他選單或以程式設計方式),VS Code 將發出一個啟用事件 onCommand:${command}

注意: 使用產品圖示中的圖示時,設定 lightdark 將停用圖示。正確的語法是 "icon": "$(book)"

命令示例

{
  "contributes": {
    "commands": [
      {
        "command": "extension.sayHello",
        "title": "Hello World",
        "category": "Hello",
        "icon": {
          "light": "path/to/light/icon.svg",
          "dark": "path/to/dark/icon.svg"
        }
      }
    ]
  }
}

請參閱命令擴充套件指南,瞭解如何在 VS Code 擴充套件中使用命令的更多資訊。

commands extension point example

命令圖示規範

  • 大小:圖示應為 16x16,帶 1 畫素內邊距(影像為 14x14),並居中。
  • 顏色:圖示應使用單一顏色。
  • 格式:建議圖示為 SVG 格式,但也接受任何影像檔案型別。

command icons

contributes.configuration

貢獻將暴露給使用者的設定。使用者可以在設定編輯器中設定這些配置選項,或透過直接編輯 settings.json 檔案來設定。

此部分可以是一個表示單個設定類別的物件,也可以是一個表示多個設定類別的物件陣列。如果存在多個設定類別,設定編輯器將在該擴充套件的目錄表中顯示一個子選單,並且標題鍵將用於子選單條目名稱。

配置示例

{
  "contributes": {
    "configuration": {
      "title": "Settings Editor Test Extension",
      "type": "object",
      "properties": {
        "settingsEditorTestExtension.booleanExample": {
          "type": "boolean",
          "default": true,
          "description": "Boolean Example"
        },
        "settingsEditorTestExtension.stringExample": {
          "type": "string",
          "default": "Hello World",
          "description": "String Example"
        }
      }
    }
  }
}

configuration extension point example

您可以使用 vscode.workspace.getConfiguration('myExtension') 從擴充套件中讀取這些值。

配置架構

您的配置條目既用於在 JSON 編輯器中編輯設定時提供智慧感知,也用於定義它們在設定 UI 中的顯示方式。

settings UI screenshot with numbers

標題 (title)

類別的 title 1️⃣️ 是該類別使用的標題。

{
  "configuration": {
    "title": "GitMagic"
  }
}

對於具有多個設定類別的擴充套件,如果其中一個類別的標題與擴充套件的顯示名稱相同,則設定 UI 會將該類別視為“預設類別”,忽略該類別的 order 欄位,並將其設定放在主擴充套件標題下方。

對於 titledisplayName 欄位,像“Extension”、“Configuration”和“Settings”這樣的詞是多餘的。

  • "title": "GitMagic"
  • "title": "GitMagic Extension"
  • "title": "GitMagic Configuration"
  • "title": "GitMagic Extension Configuration Settings"

屬性 (properties)

configuration 物件中的 properties 2️⃣ 將構成一個字典,其中鍵是設定 ID,值提供有關設定的更多資訊。儘管一個擴充套件可以包含多個設定類別,但擴充套件的每個設定仍然必須具有其自己的唯一 ID。設定 ID 不能是另一個設定 ID 的完整字首。

沒有顯式 order 欄位的屬性將按字典順序顯示在設定 UI 中(不是它們在清單中列出的順序)。

設定標題

在設定 UI 中,將使用多個欄位為每個設定構建顯示標題。鍵中的大寫字母用於指示單詞分隔符。

單類別和預設類別配置的顯示標題

如果配置只有一個設定類別,或者如果該類別與擴充套件的顯示名稱具有相同的標題,則對於該類別內的設定,設定 UI 將使用設定 ID 和擴充套件 name 欄位來確定顯示標題。

例如,對於設定 ID gitMagic.blame.dateFormat 和副檔名 authorName.gitMagic,由於設定 ID 的字首與副檔名的字尾匹配,因此設定 ID 中的 gitMagic 部分將在顯示標題中刪除:“Blame: Date Format”。

多類別配置的顯示標題

如果配置有多個設定類別,且類別標題與擴充套件顯示名稱不同,則對於該類別內的設定,設定 UI 將使用設定 ID 和類別 id 欄位來確定顯示標題。

例如,對於設定 ID css.completion.completePropertyWithSemicolon 和類別 ID css,由於設定 ID 的字首與類別 ID 的字尾匹配,css 部分將在設定 UI 中從設定 ID 中刪除,生成的設定標題將是“Completion: Complete Property With Semicolon”。

配置屬性架構

配置鍵使用 JSON Schema 的超集進行定義。

description / markdownDescription

您的 description 3️⃣ 出現在標題之後和輸入欄位之前,除了布林值,其描述用作複選框的標籤。6️⃣

{
  "gitMagic.blame.heatMap.enabled": {
    "description": "Specifies whether to provide a heatmap indicator in the gutter blame annotations"
  }
}

如果您使用 markdownDescription 而不是 description,您的設定描述將在設定 UI 中被解析為 Markdown。

{
  "gitMagic.blame.dateFormat": {
    "markdownDescription": "Specifies how to format absolute dates (e.g. using the `${date}` token) in gutter blame annotations. See the [Moment.js docs](https://momentjs.com/docs/#/displaying/format/) for valid formats"
  }
}

對於 markdownDescription,為了新增新行或多個段落,請使用字串 \n\n 來分隔段落,而不是僅僅使用 \n

type

number 4️⃣、string 5️⃣、boolean 6️⃣ 型別的條目可以直接在設定 UI 中編輯。

{
  "gitMagic.views.pageItemLimit": {
    "type": "number",
    "default": 20,
    "markdownDescription": "Specifies the number of items to show in each page when paginating a view list. Use 0 to specify no limit"
  }
}

如果字串設定在配置條目上設定了 "editPresentation": "multilineText",則可以使用多行文字輸入框呈現。

對於 boolean 條目,markdownDescription(如果未指定 markdownDescription 則為 description)將用作複選框旁邊的標籤。

{
  "gitMagic.blame.compact": {
    "type": "boolean",
    "description": "Specifies whether to compact (deduplicate) matching adjacent gutter blame annotations"
  }
}

某些 objectarray 型別設定將在設定 UI 中呈現。簡單的 numberstringboolean 陣列將呈現為可編輯列表。具有 stringnumberinteger 和/或 boolean 型別屬性的物件將呈現為可編輯的鍵值網格。物件設定還應將 additionalProperties 設定為 false 或具有適當 type 屬性的物件,以便在 UI 中呈現。

如果 objectarray 型別設定還包含其他型別,如巢狀物件、陣列或 null,則該值將不會在設定 UI 中呈現,並且只能透過直接編輯 JSON 進行修改。使用者將看到一個“在 settings.json 中編輯”連結,如上圖所示。8️⃣

order

類別和這些類別中的設定都可以採用整數 order 型別屬性,這提供了它們相對於其他類別和/或設定應該如何排序的參考。

如果兩個類別具有 order 屬性,則順序號較低的類別排在前面。如果類別未給定 order 屬性,則它出現在已給定該屬性的類別之後。

如果同一類別中的兩個設定具有 order 屬性,則順序號較低的設定排在前面。如果同一類別中的另一個設定未給定 order 屬性,則它將出現在該類別中已給定該屬性的設定之後。

如果兩個類別具有相同的 order 屬性值,或者同一類別中的兩個設定具有相同的 order 屬性值,則它們將在設定 UI 中按字典順序遞增排序。

enum / enumDescriptions / markdownEnumDescriptions / enumItemLabels

如果您在 enum 7️⃣ 屬性下提供專案陣列,設定 UI 將呈現這些專案的下拉選單。

您還可以提供 enumDescriptions 屬性,這是一個與 enum 屬性長度相同的字串陣列。enumDescriptions 屬性在設定 UI 中提供下拉選單底部與每個 enum 專案對應的描述。
您還可以使用 markdownEnumDescriptions 代替 enumDescriptions,並且您的描述將作為 Markdown 進行解析。markdownEnumDescriptions 優先於 enumDescriptions
要自定義設定 UI 中的下拉選項名稱,您可以使用 enumItemLabels

示例

{
  "settingsEditorTestExtension.enumSetting": {
    "type": "string",
    "enum": ["first", "second", "third"],
    "markdownEnumDescriptions": [
      "The *first* enum",
      "The *second* enum",
      "The *third* enum"
    ],
    "enumItemLabels": ["1st", "2nd", "3rd"],
    "default": "first",
    "description": "Example setting with an enum"
  }
}

settings UI screenshot of example enum setting above

deprecationMessage / markdownDeprecationMessage

如果您設定了 deprecationMessagemarkdownDeprecationMessage,則該設定將帶有指定訊息的警告下劃線。此外,該設定將從設定 UI 中隱藏,除非使用者對其進行了配置。如果您設定了 markdownDeprecationMessage,則 Markdown 不會在設定懸停或問題檢視中呈現。如果您同時設定了這兩個屬性,則 deprecationMessage 將顯示在懸停和問題檢視中,而 markdownDeprecationMessage 將以 Markdown 形式呈現在設定 UI 中。

示例

{
  "json.colorDecorators.enable": {
    "type": "boolean",
    "description": "Enables or disables color decorators",
    "markdownDeprecationMessage": "**Deprecated**: Please use `#editor.colorDecorators#` instead.",
    "deprecationMessage": "Deprecated: Please use editor.colorDecorators instead."
  }
}

其他 JSON 模式屬性

您可以使用任何驗證 JSON 模式屬性來描述配置值的其他約束

  • default 用於定義屬性的預設值
  • minimummaximum 用於限制數值
  • maxLengthminLength 用於限制字串長度
  • pattern 用於限制字串符合給定正則表示式
  • patternErrorMessage 用於在模式不匹配時提供定製的錯誤訊息。
  • format 用於限制字串符合已知格式,例如 datetimeipv4emailuri
  • maxItemsminItems 用於限制陣列長度
  • editPresentation 用於控制在設定編輯器中為字串設定呈現單行輸入框還是多行文字區域

不支援的 JSON 模式屬性

配置部分不支援以下內容:

  • $refdefinition:配置架構需要自包含,不能對聚合的設定 JSON 架構文件的外觀做出假設。

有關這些和其他功能的更多詳細資訊,請參閱 JSON Schema 參考

scope

配置設定可以具有以下可能的作用域之一

  • application - 適用於所有 VS Code 例項的設定,只能在使用者設定中配置。
  • machine - 機器特定的設定,只能在使用者設定或遠端設定中設定。例如,不應在機器之間共享的安裝路徑。這些設定的值將不會同步。
  • machine-overridable - 機器特定的設定,可以被工作區或資料夾設定覆蓋。這些設定的值將不會同步。
  • window - 視窗(例項)特定的設定,可以在使用者、工作區或遠端設定中配置。
  • resource - 資源設定,適用於檔案和資料夾,可以在所有設定級別(甚至資料夾設定)中配置。
  • language-overridable - 可以在語言級別覆蓋的資源設定。

配置範圍決定了使用者何時可以透過設定編輯器訪問設定,以及設定是否適用。如果未宣告 scope,則預設為 window

以下是內建 Git 擴充套件的示例配置範圍

{
  "contributes": {
    "configuration": {
      "title": "Git",
      "properties": {
        "git.alwaysSignOff": {
          "type": "boolean",
          "scope": "resource",
          "default": false,
          "description": "%config.alwaysSignOff%"
        },
        "git.ignoredRepositories": {
          "type": "array",
          "default": [],
          "scope": "window",
          "description": "%config.ignoredRepositories%"
        },
        "git.autofetch": {
          "type": ["boolean", "string"],
          "enum": [true, false, "all"],
          "scope": "resource",
          "markdownDescription": "%config.autofetch%",
          "default": false,
          "tags": ["usesOnlineServices"]
        }
      }
    }
  }
}

您可以看到 git.alwaysSignOff 具有 resource 範圍,可以按使用者、工作區或資料夾設定,而具有 window 範圍的忽略的倉庫列表更全域性地適用於 VS Code 視窗或工作區(可能是多根)。

ignoreSync

您可以將 ignoreSync 設定為 true,以防止該設定與使用者的設定同步。這對於非使用者特定的設定很有用。例如,remoteTunnelAccess.machineName 設定並非使用者特定,不應同步。請注意,如果您已將 scope 設定為 machinemachine-overridable,則無論 ignoreSync 的值如何,該設定都不會同步。

{
  "contributes": {
    "configuration": {
      "properties": {
        "remoteTunnelAccess.machineName": {
          "type": "string",
          "default": "",
          "ignoreSync": true
        }
      }
    }
  }
}

```json
{
  "remoteTunnelAccess.machineName": {
    "type": "string",
    "default": '',
    "ignoreSync": true
  }
}

連結到設定

您可以透過在 Markdown 型別屬性中使用此特殊語法 `#target.setting.id#` 插入指向另一個設定的連結,該連結將在設定 UI 中呈現為可單擊連結。這適用於 markdownDescriptionmarkdownEnumDescriptionsmarkdownDeprecationMessage。示例:

  "files.autoSaveDelay": {
    "markdownDescription": "Controls the delay in ms after which a dirty editor is saved automatically. Only applies when `#files.autoSave#` is set to `afterDelay`.",
    // ...
  }

在設定 UI 中,這會呈現為

setting link example

contributes.configurationDefaults

貢獻其他已註冊配置的預設值並覆蓋其預設值。

以下示例覆蓋了 files.autoSave 設定的預設行為,以在焦點更改時自動儲存檔案。

"configurationDefaults": {
      "files.autoSave": "onFocusChange"
}

您還可以為提供的語言貢獻預設編輯器配置。例如,以下程式碼片段為 markdown 語言貢獻了預設編輯器配置

{
  "contributes": {
    "configurationDefaults": {
      "[markdown]": {
        "editor.wordWrap": "on",
        "editor.quickSuggestions": {
          "comments": "off",
          "strings": "off",
          "other": "off"
        }
      }
    }
  }
}

contributes.customEditors

customEditors 貢獻點是您的擴充套件如何告知 VS Code 它提供的自定義編輯器。例如,VS Code 需要知道您的自定義編輯器適用於哪些檔案型別,以及如何在任何 UI 中識別您的自定義編輯器。

以下是自定義編輯器擴充套件示例的基本 customEditor 貢獻

"contributes": {
  "customEditors": [
    {
      "viewType": "catEdit.catScratch",
      "displayName": "Cat Scratch",
      "selector": [
        {
          "filenamePattern": "*.cscratch"
        }
      ],
      "priority": "default"
    }
  ]
}

customEditors 是一個數組,因此您的擴充套件可以貢獻多個自定義編輯器。

  • viewType - 自定義編輯器的唯一識別符號。

    這是 VS Code 如何將 package.json 中的自定義編輯器貢獻與程式碼中的自定義編輯器實現關聯起來。這在所有擴充套件中必須是唯一的,因此不要使用通用的 viewType,例如 "preview",請確保使用對您的擴充套件唯一的名稱,例如 "viewType": "myAmazingExtension.svgPreview"

  • displayName - 在 VS Code UI 中標識自定義編輯器的名稱。

    顯示名稱顯示在 VS Code UI 中,例如“檢視:重新開啟方式”下拉選單中。

  • selector - 指定自定義編輯器適用於哪些檔案。

    selector 是一個或多個全域性模式的陣列。這些全域性模式與檔名匹配,以確定自定義編輯器是否可用於它們。filenamePattern,例如 *.png,將為所有 PNG 檔案啟用自定義編輯器。

    您還可以建立更具體的模式,匹配檔案或目錄名稱,例如 **/translations/*.json

  • priority -(可選)指定何時使用自定義編輯器。

    priority 控制在開啟資源時何時使用自定義編輯器。可能的值是

    • "default" - 嘗試為與自定義編輯器的 selector 匹配的每個檔案使用自定義編輯器。如果給定檔案有多個自定義編輯器,使用者將需要選擇他們要使用的自定義編輯器。
    • "option" - 預設情況下不使用自定義編輯器,但允許使用者切換到它或將其配置為預設編輯器。

您可以在自定義編輯器擴充套件指南中瞭解更多資訊。

contributes.debuggers

向 VS Code 貢獻偵錯程式。偵錯程式貢獻具有以下屬性:

  • type 是一個唯一的 ID,用於在啟動配置中標識此偵錯程式。
  • label 是此偵錯程式在 UI 中使用者可見的名稱。
  • program 是除錯介面卡的路徑,該介面卡針對實際偵錯程式或執行時實現 VS Code 除錯協議。
  • runtime 如果除錯介面卡的路徑不是可執行檔案但需要執行時。
  • configurationAttributes 是此偵錯程式特有的啟動配置引數的模式。請注意,不支援 JSON 模式構造 $refdefinition
  • initialConfigurations 列出了用於填充初始 launch.json 的啟動配置。
  • configurationSnippets 列出了在編輯 launch.json 時可透過智慧感知獲得的啟動配置。
  • variables 引入了替換變數並將它們繫結到偵錯程式擴充套件實現的命令。
  • languages 除錯擴充套件可能被認為是“預設偵錯程式”的那些語言。

偵錯程式示例

{
  "contributes": {
    "debuggers": [
      {
        "type": "node",
        "label": "Node Debug",

        "program": "./out/node/nodeDebug.js",
        "runtime": "node",

        "languages": ["javascript", "typescript", "javascriptreact", "typescriptreact"],

        "configurationAttributes": {
          "launch": {
            "required": ["program"],
            "properties": {
              "program": {
                "type": "string",
                "description": "The program to debug."
              }
            }
          }
        },

        "initialConfigurations": [
          {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}/app.js"
          }
        ],

        "configurationSnippets": [
          {
            "label": "Node.js: Attach Configuration",
            "description": "A new configuration for attaching to a running node program.",
            "body": {
              "type": "node",
              "request": "attach",
              "name": "${2:Attach to Port}",
              "port": 9229
            }
          }
        ],

        "variables": {
          "PickProcess": "extension.node-debug.pickNodeProcess"
        }
      }
    ]
  }
}

有關如何整合 debugger 的完整演練,請參閱偵錯程式擴充套件

contributes.grammars

為語言貢獻 TextMate 語法。您必須提供此語法適用的 language、語法的 TextMate scopeName 和檔案路徑。

注意: 包含語法的檔案可以是 JSON 格式(檔名以 .json 結尾)或 XML plist 格式(所有其他檔案)。

語法示例

{
  "contributes": {
    "grammars": [
      {
        "language": "markdown",
        "scopeName": "text.html.markdown",
        "path": "./syntaxes/markdown.tmLanguage.json",
        "embeddedLanguages": {
          "meta.embedded.block.frontmatter": "yaml"
        }
      }
    ]
  }
}

請參閱語法高亮指南,瞭解如何註冊與語言關聯的 TextMate 語法以實現語法高亮。

grammars extension point example

contributes.icons

透過 ID 貢獻一個新圖示,以及一個預設圖示。然後,該圖示 ID 可以由擴充套件(或依賴於該擴充套件的任何其他擴充套件)在任何可以使用 ThemeIcon 的地方使用 new ThemeIcon("iconId"),在Markdown 字串中($(iconId)),以及作為某些貢獻點中的圖示使用。

{
  "contributes": {
    "icons": {
      "distro-ubuntu": {
        "description": "Ubuntu icon",
        "default": {
          "fontPath": "./distroicons.woff",
          "fontCharacter": "\\E001"
        }
      },
      "distro-fedora": {
        "description": "Ubuntu icon",
        "default": {
          "fontPath": "./distroicons.woff",
          "fontCharacter": "\\E002"
        }
      }
    }
  }
}

contributes.iconThemes

向 VS Code 貢獻檔案圖示主題。檔案圖示顯示在檔名旁邊,指示檔案型別。

您必須指定一個 id(在設定中使用)、一個標籤和檔案圖示定義檔案的路徑。

檔案圖示主題示例

{
  "contributes": {
    "iconThemes": [
      {
        "id": "my-cool-file-icons",
        "label": "Cool File Icons",
        "path": "./fileicons/cool-file-icon-theme.json"
      }
    ]
  }
}

file icon theme extension point example

請參閱檔案圖示主題指南,瞭解如何建立檔案圖示主題。

contributes.jsonValidation

為特定型別的 json 檔案貢獻驗證模式。url 值可以是擴充套件中包含的模式檔案的本地路徑,也可以是遠端伺服器 URL,例如 json 模式儲存

{
  "contributes": {
    "jsonValidation": [
      {
        "fileMatch": ".jshintrc",
        "url": "https://json.schemastore.org/jshintrc"
      }
    ]
  }
}

contributes.keybindings

貢獻一個鍵繫結規則,定義當用戶按下鍵組合時應呼叫哪個命令。請參閱鍵繫結主題,其中詳細解釋了鍵繫結。

貢獻鍵繫結將使“預設鍵盤快捷方式”顯示您的規則,並且命令的每個 UI 表示現在都將顯示您新增的鍵繫結。當然,當用戶按下鍵組合時,命令將被呼叫。

注意: 因為 VS Code 在 Windows、macOS 和 Linux 上執行,這些平臺上的修飾符不同,您可以使用“key”設定預設鍵組合,並用特定平臺覆蓋它。

注意: 當命令被呼叫時(透過鍵繫結或命令面板),VS Code 將發出一個啟用事件 onCommand:${command}

鍵繫結示例

定義 Windows 和 Linux 下的 Ctrl+F1 以及 macOS 下的 Cmd+F1 觸發 "extension.sayHello" 命令

{
  "contributes": {
    "keybindings": [
      {
        "command": "extension.sayHello",
        "key": "ctrl+f1",
        "mac": "cmd+f1",
        "when": "editorTextFocus"
      }
    ]
  }
}

keybindings extension point example

contributes.languages

貢獻程式語言的定義。這將引入一種新語言或豐富 VS Code 對某種語言的認知。

contributes.languages 的主要作用是

  • 定義一個 languageId,可以在 VS Code API 的其他部分(例如 vscode.TextDocument.languageIdonLanguage 啟用事件)中重複使用。
    • 您可以使用 aliases 欄位貢獻一個人類可讀的名稱。列表中的第一個專案將用作人類可讀的標籤。
  • 將副檔名 (extensions)、檔名 (filenames)、檔名全域性模式 (filenamePatterns)、以特定行(例如 hashbang)開頭的檔案 (firstLine) 和 mimetypes 與該 languageId 關聯。
  • 為貢獻的語言貢獻一組宣告性語言功能。在語言配置指南中瞭解有關可配置編輯功能的更多資訊。
  • 貢獻一個圖示,如果主題不包含該語言的圖示,則該圖示可在檔案圖示主題中使用

語言示例

{
  "contributes": {
    "languages": [
      {
        "id": "python",
        "extensions": [".py"],
        "aliases": ["Python", "py"],
        "filenames": [],
        "firstLine": "^#!/.*\\bpython[0-9.-]*\\b",
        "configuration": "./language-configuration.json",
        "icon": {
          "light": "./icons/python-light.png",
          "dark": "./icons/python-dark.png"
        }
      }
    ]
  }
}

contributes.menus

向編輯器或資源管理器貢獻一個命令選單項。選單項定義包含選中時應呼叫的命令以及專案應顯示的條件。後者由 when 子句定義,它使用鍵繫結when 子句上下文

command 屬性指示選擇選單項時要執行的命令。submenu 屬性指示在此位置呈現哪個子選單。

宣告 command 選單項時,還可以使用 alt 屬性定義替代命令。在開啟選單時按 Alt 鍵時,它將顯示並呼叫。在 Windows 和 Linux 上,Shift 鍵也有此作用,這在 Alt 鍵會觸發視窗選單欄的情況下很有用。

最後,group 屬性定義選單項的排序和分組。navigation 組很特殊,因為它將始終排序到選單的頂部/開頭。

請注意when 子句適用於選單,而 enablement 子句適用於命令。enablement 適用於所有選單甚至鍵繫結,而 when 僅適用於單個選單。

目前,擴充套件作者可以貢獻到

  • commandPalette - 全域性命令面板
  • comments/comment/title - 註釋標題選單欄
  • comments/comment/context - 註釋上下文選單
  • comments/commentThread/title - 註釋執行緒標題選單欄
  • comments/commentThread/context- 註釋執行緒上下文選單
  • debug/callstack/context - 除錯呼叫堆疊檢視上下文選單
  • debug/callstack/contextinline - 除錯呼叫堆疊檢視內聯操作
  • debug/toolBar - 除錯檢視工具欄
  • debug/variables/context - 除錯變數檢視上下文選單
  • editor/context - 編輯器上下文選單
  • editor/lineNumber/context - 編輯器行號上下文選單
  • editor/title - 編輯器標題選單欄
  • editor/title/context - 編輯器標題上下文選單
  • editor/title/run - 編輯器標題選單欄上的執行子選單
  • explorer/context - 資源管理器檢視上下文選單
  • extension/context - 擴充套件檢視上下文選單
  • file/newFile - 檔案選單和歡迎頁面中的新建檔案項
  • interactive/toolbar - 互動式視窗工具欄
  • interactive/cell/title - 互動式視窗單元格標題選單欄
  • notebook/toolbar - 筆記本工具欄
  • notebook/cell/title - 筆記本單元格標題選單欄
  • notebook/cell/execute - 筆記本單元格執行選單
  • scm/title - SCM 標題選單
  • scm/resourceGroup/context - SCM 資源組選單
  • scm/resourceFolder/context - SCM 資原始檔夾選單
  • scm/resourceState/context - SCM 資源選單
  • scm/change/title - SCM 更改標題選單
  • scm/sourceControl- SCM 原始碼控制選單
  • terminal/context - 終端上下文選單
  • terminal/title/context - 終端標題上下文選單
  • testing/item/context - 測試資源管理器專案上下文選單
  • testing/item/gutter - 測試專案裝訂線裝飾的選單
  • timeline/title - 時間線檢視標題選單欄
  • timeline/item/context - 時間線檢視專案上下文選單
  • touchBar - macOS Touch Bar
  • view/title - 檢視標題選單
  • view/item/context - 檢視專案上下文選單
  • webview/context - 任何webview上下文選單
  • 任何貢獻的子選單

注意 1: 當從(上下文)選單呼叫命令時,VS Code 會嘗試推斷當前選定的資源,並在呼叫命令時將其作為引數傳遞。例如,資源管理器內的選單項會傳遞選定資源的 URI,編輯器內的選單項會傳遞文件的 URI。

注意 2: 貢獻到 editor/lineNumber/context 的選單項的命令也會傳遞行號。此外,這些專案可以在其 when 子句中引用 editorLineNumber 上下文鍵,例如透過使用 innot in 運算子將其與擴充套件管理的陣列值上下文鍵進行測試。

除了標題之外,貢獻的命令還可以指定 VS Code 在呼叫選單項作為按鈕(例如在標題選單欄上)時將顯示的圖示。

這是一個命令選單項

{
  "contributes": {
    "menus": {
      "editor/title": [
        {
          "when": "resourceLangId == markdown",
          "command": "markdown.showPreview",
          "alt": "markdown.showPreviewToSide",
          "group": "navigation"
        }
      ]
    }
  }
}

menus extension point example

同樣,這是一個新增到特定檢視的命令選單項。以下示例貢獻到任意檢視,例如終端

{
  "contributes": {
    "menus": {
      "view/title": [
        {
          "command": "terminalApi.sendText",
          "when": "view == terminal",
          "group": "navigation"
        }
      ]
    }
  }
}

Adding a menu entry to view/title with view == terminal will result in an action in the panel when the terminal is open

這是一個子選單選單項

{
  "contributes": {
    "menus": {
      "scm/title": [
        {
          "submenu": "git.commit",
          "group": "2_main@1",
          "when": "scmProvider == git"
        }
      ]
    }
  }
}

menus extension point example (submenu)

命令面板選單項的上下文特定可見性

package.json 中註冊命令時,它們將自動顯示在命令面板 (⇧⌘P (Windows, Linux Ctrl+Shift+P)) 中。為了更好地控制命令的可見性,可以使用 commandPalette 選單項。它允許您定義一個 when 條件來控制命令是否應在命令面板中可見。

以下程式碼片段使“Hello World”命令僅在編輯器中選中某些內容時在命令面板中可見

{
  "commands": [
    {
      "command": "extension.sayHello",
      "title": "Hello World"
    }
  ],
  "menus": {
    "commandPalette": [
      {
        "command": "extension.sayHello",
        "when": "editorHasSelection"
      }
    ]
  }
}

組排序

選單項可以分組。它們按字典順序排序,並遵循以下預設值/規則。您可以在這些組中新增選單項,或在它們之間、下方或上方新增新的選單項組。

編輯器上下文選單具有這些預設組

  • navigation - 在所有情況下,navigation 組都排在最前面。
  • 1_modification - 此組接下來,包含修改程式碼的命令。
  • 9_cutcopypaste - 倒數第二個預設組,包含基本編輯命令。
  • z_commands - 最後一個預設組,包含開啟命令面板的入口。

Menu Group Sorting

資源管理器上下文選單具有這些預設組

  • navigation - 與 VS Code 中的導航相關的命令。此組在所有情況下都排在最前面。
  • 2_workspace - 與工作區操作相關的命令。
  • 3_compare - 與在差異編輯器中比較檔案相關的命令。
  • 4_search - 與在搜尋檢視中搜索相關的命令。
  • 5_cutcopypaste - 與檔案的剪下、複製和貼上相關的命令。
  • 6_copypath - 與複製檔案路徑相關的命令。
  • 7_modification - 與檔案修改相關的命令。

編輯器標籤上下文選單具有這些預設組

  • 1_close - 與關閉編輯器相關的命令。
  • 3_preview - 與固定編輯器相關的命令。

編輯器標題選單具有這些預設組

  • navigation - 與導航相關的命令。
  • 1_run - 與執行和除錯編輯器相關的命令。
  • 1_diff - 與使用差異編輯器相關的命令。
  • 3_open - 與開啟編輯器相關的命令。
  • 5_close - 與關閉編輯器相關的命令。

navigation1_run 顯示在主編輯器標題區域。其他組顯示在輔助區域 - ... 選單下方。

終端標籤上下文選單具有這些預設組

  • 1_create - 與建立終端相關的命令。
  • 3_run - 與在終端中執行/執行某些內容相關的命令。
  • 5_manage - 與管理終端相關的命令。
  • 7_configure - 與終端配置相關的命令。

終端上下文選單具有這些預設組

  • 1_create - 與建立終端相關的命令。
  • 3_edit - 與操作文字、選擇或剪貼簿相關的命令。
  • 5_clear - 與清除終端相關的命令。
  • 7_kill - 與關閉/終止終端相關的命令。
  • 9_config - 與終端配置相關的命令。

時間線檢視專案上下文選單具有這些預設組

  • inline - 重要或常用時間線專案命令。呈現為工具欄。
  • 1_actions - 與時間線專案操作相關的命令。
  • 5_copy - 與複製時間線專案資訊相關的命令。

擴充套件檢視上下文選單具有這些預設組

  • 1_copy - 與複製擴充套件資訊相關的命令。
  • 2_configure - 與配置擴充套件相關的命令。

組內排序

組內的順序取決於標題或 order 屬性。選單項的組內區域性順序透過在組識別符號後附加 @<number> 指定,如下所示

{
  "editor/title": [
    {
      "when": "editorHasSelection",
      "command": "extension.Command",
      "group": "myGroup@1"
    }
  ]
}

contributes.problemMatchers

貢獻問題匹配器模式。這些貢獻在輸出面板執行器和終端執行器中都有效。下面是一個示例,用於在擴充套件中貢獻用於 gcc 編譯器的錯誤匹配器

{
  "contributes": {
    "problemMatchers": [
      {
        "name": "gcc",
        "owner": "cpp",
        "fileLocation": ["relative", "${workspaceFolder}"],
        "pattern": {
          "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
          "file": 1,
          "line": 2,
          "column": 3,
          "severity": 4,
          "message": 5
        }
      }
    ]
  }
}

此問題匹配器現在可以透過名稱引用 $gcctasks.json 檔案中使用。例如:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build",
      "command": "gcc",
      "args": ["-Wall", "helloWorld.c", "-o", "helloWorld"],
      "problemMatcher": "$gcc"
    }
  ]
}

另請參閱:定義問題匹配器

contributes.problemPatterns

貢獻可在問題匹配器(見上文)中使用的命名問題模式。

contributes.productIconThemes

為 VS Code 貢獻產品圖示主題。產品圖示是 VS Code 中使用的所有圖示,除了檔案圖示和擴充套件貢獻的圖示。

您必須指定一個 id(在設定中使用)、一個標籤和圖示定義檔案的路徑。

產品圖示主題示例

{
  "contributes": {
    "productIconThemes": [
      {
        "id": "elegant",
        "label": "Elegant Icon Theme",
        "path": "./producticons/elegant-product-icon-theme.json"
      }
    ]
  }
}

product icon theme extension point example

請參閱產品圖示主題指南,瞭解如何建立產品圖示主題。

contributes.resourceLabelFormatters

貢獻資源標籤格式化程式,指定如何在工作臺中的所有位置顯示 URI。例如,擴充套件可以這樣貢獻一個用於 scheme remotehub 的 URI 格式化程式

{
  "contributes": {
    "resourceLabelFormatters": [
      {
        "scheme": "remotehub",
        "formatting": {
          "label": "${path}",
          "separator": "/",
          "workspaceSuffix": "GitHub"
        }
      }
    ]
  }
}

這意味著所有 scheme 為 remotehub 的 URI 將僅顯示 URI 的 path 部分,並且分隔符將為 /。具有 remotehub URI 的工作區將在其標籤中包含 GitHub 字尾。

contributes.semanticTokenModifiers

貢獻新的語義令牌修飾符,可以透過主題規則進行高亮顯示。

{
  "contributes": {
    "semanticTokenModifiers": [
      {
        "id": "native",
        "description": "Annotates a symbol that is implemented natively"
      }
    ]
  }
}

請參閱語義高亮指南,瞭解有關語義高亮的更多資訊。

contributes.semanticTokenScopes

貢獻語義令牌型別和修飾符與作用域之間的對映,作為回退或支援特定語言主題。

{
  "contributes": {
    "semanticTokenScopes": [
      {
        "language": "typescript",
        "scopes": {
          "property.readonly": ["variable.other.constant.property.ts"]
        }
      }
    ]
  }
}

請參閱語義高亮指南,瞭解有關語義高亮的更多資訊。

contributes.semanticTokenTypes

貢獻新的語義令牌型別,可以透過主題規則進行高亮顯示。

{
  "contributes": {
    "semanticTokenTypes": [
      {
        "id": "templateType",
        "superType": "type",
        "description": "A template type."
      }
    ]
  }
}

請參閱語義高亮指南,瞭解有關語義高亮的更多資訊。

contributes.snippets

為特定語言貢獻程式碼片段。language 屬性是語言識別符號path 是程式碼片段檔案的相對路徑,該檔案以 VS Code 程式碼片段格式定義程式碼片段。

以下示例展示了為 Go 語言新增程式碼片段。

{
  "contributes": {
    "snippets": [
      {
        "language": "go",
        "path": "./snippets/go.json"
      }
    ]
  }
}

contributes.submenus

貢獻一個子選單作為佔位符,選單項可以貢獻到其中。子選單需要一個 label 才能在父選單中顯示。

除了標題之外,命令還可以定義 VS Code 將在編輯器標題選單欄中顯示的圖示。

{
  "contributes": {
    "submenus": [
      {
        "id": "git.commit",
        "label": "Commit"
      }
    ]
  }
}

submenus extension point example

contributes.taskDefinitions

貢獻並定義一個物件字面量結構,允許唯一標識系統中貢獻的任務。任務定義至少具有一個 type 屬性,但通常定義額外的屬性。例如,表示 package.json 檔案中指令碼的任務的任務定義如下所示

{
  "taskDefinitions": [
    {
      "type": "npm",
      "required": ["script"],
      "properties": {
        "script": {
          "type": "string",
          "description": "The script to execute"
        },
        "path": {
          "type": "string",
          "description": "The path to the package.json file. If omitted the package.json in the root of the workspace folder is used."
        }
      }
    }
  ]
}

任務定義使用 JSON 模式語法定義 requiredproperties 屬性。type 屬性定義任務型別。如果上面的示例

  • "type": "npm" 將任務定義與 npm 任務關聯
  • "required": [ "script" ]script 屬性定義為強制性。path 屬性是可選的。
  • "properties" : { ... } 定義附加屬性及其型別。

當擴充套件實際建立任務時,它需要傳遞符合 package.json 檔案中貢獻的任務定義的 TaskDefinition。對於 npm 示例,在 package.json 檔案中為測試指令碼建立任務如下所示

let task = new vscode.Task({ type: 'npm', script: 'test' }, ....);

contributes.terminal

為 VS Code 貢獻終端配置檔案,允許擴充套件處理配置檔案的建立。定義後,配置檔案應在建立終端配置檔案時出現

{
  "activationEvents": ["onTerminalProfile:my-ext.terminal-profile"],
  "contributes": {
    "terminal": {
      "profiles": [
        {
          "title": "Profile from extension",
          "id": "my-ext.terminal-profile"
        }
      ]
    }
  }
}

定義後,配置檔案將顯示在終端配置檔案選擇器中。啟用後,透過返回終端選項來處理配置檔案的建立。

vscode.window.registerTerminalProfileProvider('my-ext.terminal-profile', {
  provideTerminalProfile(
    token: vscode.CancellationToken
  ): vscode.ProviderResult<vscode.TerminalOptions | vscode.ExtensionTerminalOptions> {
    return { name: 'Profile from extension', shellPath: 'bash' };
  }
});

contributes.themes

為 VS Code 貢獻顏色主題,定義工作臺顏色和編輯器中語法令牌的樣式。

您必須指定一個標籤、主題是深色主題還是淺色主題(以便 VS Code 的其餘部分隨主題而變化)以及檔案路徑 (JSON 格式)。

主題示例

{
  "contributes": {
    "themes": [
      {
        "label": "Monokai",
        "uiTheme": "vs-dark",
        "path": "./themes/monokai-color-theme.json"
      }
    ]
  }
}

color theme extension point example

請參閱顏色主題指南,瞭解如何建立顏色主題。

contributes.typescriptServerPlugins

貢獻 TypeScript 伺服器外掛,以增強 VS Code 的 JavaScript 和 TypeScript 支援

{
  "contributes": {
    "typescriptServerPlugins": [
      {
        "name": "typescript-styled-plugin"
      }
    ]
  }
}

上述示例擴充套件貢獻了 typescript-styled-plugin,它為 JavaScript 和 TypeScript 添加了 styled-component IntelliSense。此外掛將從擴充套件中載入,並且必須作為正常的 NPM dependency 安裝在擴充套件中

{
  "dependencies": {
    "typescript-styled-plugin": "*"
  }
}

當用戶使用 VS Code 版本的 TypeScript 時,TypeScript 伺服器外掛將為所有 JavaScript 和 TypeScript 檔案載入。如果使用者使用工作區版本的 TypeScript,除非外掛明確設定 "enableForWorkspaceTypeScriptVersions": true,否則它們不會被啟用。

{
  "contributes": {
    "typescriptServerPlugins": [
      {
        "name": "typescript-styled-plugin",
        "enableForWorkspaceTypeScriptVersions": true
      }
    ]
  }
}

外掛配置

擴充套件可以透過 VS Code 內建的 TypeScript 擴充套件提供的 API 向貢獻的 TypeScript 外掛傳送配置資料

// In your VS Code extension

export async function activate(context: vscode.ExtensionContext) {
  // Get the TS extension
  const tsExtension = vscode.extensions.getExtension('vscode.typescript-language-features');
  if (!tsExtension) {
    return;
  }

  await tsExtension.activate();

  // Get the API from the TS extension
  if (!tsExtension.exports || !tsExtension.exports.getAPI) {
    return;
  }

  const api = tsExtension.exports.getAPI(0);
  if (!api) {
    return;
  }

  // Configure the 'my-typescript-plugin-id' plugin
  api.configurePlugin('my-typescript-plugin-id', {
    someValue: process.env['SOME_VALUE']
  });
}

TypeScript 伺服器外掛透過 onConfigurationChanged 方法接收配置資料

// In your TypeScript plugin

import * as ts_module from 'typescript/lib/tsserverlibrary';

export = function init({ typescript }: { typescript: typeof ts_module }) {
  return {
    create(info: ts.server.PluginCreateInfo) {
      // Create new language service
    },
    onConfigurationChanged(config: any) {
      // Receive configuration changes sent from VS Code
    }
  };
};

此 API 允許 VS Code 擴充套件將 VS Code 設定與 TypeScript 伺服器外掛同步,或動態更改外掛的行為。請參閱 TypeScript TSLint 外掛lit-html 擴充套件,瞭解此 API 在實踐中如何使用。

contributes.views

為 VS Code 貢獻一個檢視。您必須為檢視指定一個識別符號和名稱。您可以貢獻到以下檢視容器中

  • explorer:活動欄中的資源管理器檢視容器
  • scm:活動欄中的原始碼控制管理 (SCM) 檢視容器
  • debug:活動欄中的執行和除錯檢視容器
  • test:活動欄中的測試檢視容器
  • 自定義檢視容器,由擴充套件貢獻。

當用戶開啟檢視時,VS Code 將發出一個啟用事件 onView:${viewId}(對於下面的示例,為 onView:nodeDependencies)。您還可以透過提供 when 上下文值來控制檢視的可見性。指定的 icon 將在標題無法顯示時使用(例如,當檢視被拖到活動欄時)。contextualTitle 在檢視移出其預設檢視容器並需要額外上下文時使用。

{
  "contributes": {
    "views": {
      "explorer": [
        {
          "id": "nodeDependencies",
          "name": "Node Dependencies",
          "when": "workspaceHasPackageJSON",
          "icon": "media/dep.svg",
          "contextualTitle": "Package Explorer"
        }
      ]
    }
  }
}

views extension point example

檢視內容可以透過兩種方式填充

contributes.viewsContainers

貢獻一個檢視容器,自定義檢視可以貢獻到其中。您必須為檢視容器指定一個識別符號、標題和圖示。目前,您可以將它們貢獻到活動欄 (activitybar) 和麵板 (panel)。以下示例展示瞭如何將 Package Explorer 檢視容器貢獻到活動欄,以及如何將檢視貢獻到其中。

{
  "contributes": {
    "viewsContainers": {
      "activitybar": [
        {
          "id": "package-explorer",
          "title": "Package Explorer",
          "icon": "resources/package-explorer.svg"
        }
      ]
    },
    "views": {
      "package-explorer": [
        {
          "id": "package-dependencies",
          "name": "Dependencies"
        },
        {
          "id": "package-outline",
          "name": "Outline"
        }
      ]
    }
  }
}

Custom views container

圖示規範

  • 大小:圖示應為 24x24 並居中。

  • 顏色:圖示應使用單一顏色。

  • 格式:建議圖示為 SVG 格式,但也接受任何影像檔案型別。

  • 狀態:所有圖示繼承以下狀態樣式

    狀態 不透明度
    預設值 60%
    Hover 100%
    活動 100%

contributes.viewsWelcome

自定義檢視貢獻歡迎內容。歡迎內容僅適用於空樹檢視。如果樹沒有子節點且沒有 TreeView.message,則檢視被視為空。按照慣例,任何單獨一行上的命令連結都顯示為按鈕。您可以使用 view 屬性指定歡迎內容應適用的檢視。歡迎內容的可見性可以透過 when 上下文值控制。要顯示的歡迎內容文字透過 contents 屬性設定。

{
  "contributes": {
    "viewsWelcome": [
      {
        "view": "scm",
        "contents": "In order to use git features, you can open a folder containing a git repository or clone from a URL.\n[Open Folder](command:vscode.openFolder)\n[Clone Repository](command:git.clone)\nTo learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
        "when": "config.git.enabled && git.state == initialized && workbenchState == empty"
      }
    ]
  }
}

Welcome content example

可以為單個檢視貢獻多個歡迎內容項。發生這種情況時,來自 VS Code 核心的內容排在前面,其次是來自內建擴充套件的內容,最後是來自所有其他擴充套件的內容。

contributes.walkthroughs

示例擴充套件

貢獻演練以顯示在“入門”頁面上。演練在您的擴充套件安裝時自動開啟,並提供了一種方便的方式向用戶介紹您的擴充套件功能。

演練包括標題、描述、ID 和一系列步驟。此外,可以設定 when 條件以根據上下文鍵隱藏或顯示演練。例如,一個解釋 Linux 平臺設定的演練可以給定 when: "isLinux" 以僅在 Linux 機器上顯示。

演練中的每個步驟都有一個標題、描述、ID 和媒體元素(影像或 Markdown 內容),以及一組可選的事件,這些事件將導致該步驟被選中(如下例所示)。步驟描述是 Markdown 內容,支援 **粗體**__下劃線__``程式碼`` 渲染,以及連結。與演練類似,步驟可以給定何時條件以根據上下文鍵隱藏或顯示它們。

建議使用 SVG 作為影像,因為它們具有縮放能力並支援 VS Code 的主題顏色。使用 Visual Studio Code Color Mapper Figma 外掛可以輕鬆地在 SVG 中引用主題顏色。

{
  "contributes": {
    "walkthroughs": [
      {
        "id": "sample",
        "title": "Sample",
        "description": "A sample walkthrough",
        "steps": [
          {
            "id": "runcommand",
            "title": "Run Command",
            "description": "This step will run a command and check off once it has been run.\n[Run Command](command:getting-started-sample.runCommand)",
            "media": { "image": "media/image.png", "altText": "Empty image" },
            "completionEvents": ["onCommand:getting-started-sample.runCommand"]
          },
          {
            "id": "changesetting",
            "title": "Change Setting",
            "description": "This step will change a setting and check off when the setting has changed\n[Change Setting](command:getting-started-sample.changeSetting)",
            "media": { "markdown": "media/markdown.md" },
            "completionEvents": ["onSettingChanged:getting-started-sample.sampleSetting"]
          }
        ]
      }
    ]
  }
}

Walkthrough example

完成事件

預設情況下,如果未提供 completionEvents 事件,則當點選步驟的任何按鈕時,或者如果步驟沒有按鈕,則在開啟步驟時,該步驟將被勾選。如果需要更精細的控制,可以提供 completionEvents 列表。

可用的完成事件包括

  • onCommand:myCommand.id:當命令已執行時勾選步驟。
  • onSettingChanged:mySetting.id:一旦給定設定被修改,勾選步驟。
  • onContext:contextKeyExpression:當上下文鍵表示式評估為 true 時勾選步驟。
  • extensionInstalled:myExt.id:如果給定擴充套件已安裝,則勾選步驟。
  • onView:myView.id:一旦給定檢視可見,勾選步驟。
  • onLink:https://...:一旦透過演練開啟給定連結,勾選步驟。

一旦步驟被勾選,它將保持勾選狀態,直到使用者明確取消勾選步驟或重置其進度(透過“入門:重置進度”命令)。