Курсив зарезервированных ключевых слов JavaScript в VS Code - PullRequest
0 голосов
/ 30 июня 2018

Я пытаюсь создать собственный стиль синтаксиса с помощью Настройки темы кода Visual Studio через Грамматики языка TextMate .

В частности, я хочу выделить курсивом все зарезервированные ключевые слова JavaScript. Мне удалось пройти 98% пути с настройками ниже (комментарии для того, что осталось).

К сожалению, есть несколько правил, которые я не смог найти:

  1. storage включает жирную стрелку, которую я хочу не хочу включить. Я пытался быть более конкретным, как видно из настроек ниже, но не смог найти более конкретные настройки для constructor и const. Кроме того, "storage.type.function" был наиболее явным параметром, который я мог найти для функций (необходим для ключевого слова function, но он включает жирную стрелку).
  2. keyword включает в себя такие символы, как логические операторы и т. Д., Которые, опять же, я не хочу включить. keyword.operator необходим для текстовых операторов (например, in, instanceof), но включает символьные операторы.
  3. Мне не удалось найти правила для eval (запрещено в строгом порядке) или package (неиспользуемое ключевое слово в будущем).

Есть идеи?

const settings = {
  "editor.tokenColorCustomizations": {
    "textMateRules": [
      {
        "scope": [
          // TODO: missing keywords: package, eval

      // all comment types
      "comment",

      // true, false, null
      "constant.language",

      // import, from, export, default, return, if, for, break, continue, try, catch, finally,
      // throw, default, yield, await
      "keyword.control",

      // TODO: remove operator symbols
      // in, void, delete, instanceof
      "keyword.operator",

      // debugger
      "keyword.other",

      // new
      "keyword.operator.new",

      // enum
      "storage.type.enum",

      // super, this, arguments
      "variable.language",

      // attributes in html, jsx, etc.
      "entity.other.attribute-name",

      // TODO: remove storage.type after finding explicit for constructor, const, let, var
      "storage.type",

      // static, extends, async, private, public, implements
      "storage.modifier",

      // TODO: exclude fat arrow
      // function
      "storage.type.function",

      // class
      "storage.type.class",

      // interface
      "storage.type.interface",
    ],
    "settings": {
      "fontStyle": "italic"
    }
  },
]
  },
};

1 Ответ

0 голосов
/ 01 июля 2018

Как оказалось, в VS Code вы можете легко найти нужную область.

Откройте поиск команд с помощью ctrl / cmd + shift + p и найдите Developer: Inspect TM scopes. Затем вы можете щелкнуть слева от любого символа / слова, для которого вы хотите найти область.


Чтобы ответить на мой собственный вопрос:

  1. До сих пор не существует явной области действия для const, let, var или самого ключевого слова function (storage.type.function включает зарезервированное слово и стрелку). Однако для стрелки функции существует явная область действия: storage.type.function.arrow. Это позволяет нам включить всю область действия storage, а затем явно исключить стрелку.
  2. keyword.operator.expression - это область действия, необходимая только для операторов, представленных в словах.
  3. Определенные области действия для eval и package пока недоступны. Вы можете нацелиться на eval с помощью support.function и package с помощью variable.other.readwrite, но эти области охватывают широкий диапазон и будут включать множество других результатов.

С учетом вышесказанного правила, необходимые для выделения курсивом всех зарезервированных ключевых слов JavaScript в коде VS, перечислены ниже (также включены комментарии и jsx / html атрибуты):

"editor.tokenColorCustomizations": {
"textMateRules": [
  {
    "scope": [
      // all comment types
      "comment",

      // true, false, null
      "constant.language",

      // import, from, export, default, return, if, for, break, continue, try, catch, finally,
      // throw, default, yield, await
      "keyword.control",

      // in, void, delete, instanceof
      "keyword.operator.expression",

      // debugger
      "keyword.other",

      // new
      "keyword.operator.new",

      // super, this, arguments
      "variable.language",

      // attributes in html, jsx, etc.
      "entity.other.attribute-name",

      // static, extends, async, private, public, implements
      // constructor, const, let, var, enum, class, function, interface
      // no explicit scopes for constructor, const, let, var
      // also no explicit scope for function without the arrow
      // therefore we enable all storage and explictly exclude the arrow in another scope
      "storage",

      // // no explicit scope for the eval keyword yet
      // // can be targeted with the scope below, but scope is too broad
      // "support.function",

      // // no explicit scope for the package keyword yet
      // // can be targeted with the scope below, but scope is too broad
      // "variable.other.readwrite",
    ],
    "settings": {
      "fontStyle": "italic"
    }
  },
  {
    "scope": [
      // function keyword does not have an explicit scope without the arrow
      // therefore we explictly exclude the function arrow from being italicized
      "storage.type.function.arrow",
    ],
    "settings": {
      "fontStyle": ""
    }
  }
]
  }
...