Sublime Forum

Add keyword to sublime C++ Syntax

#1

Hi, I’m new in sublime text and I’m having some troubles with this editor.

I develop in C++ and in C++ sublime Syntax there aren’t some definitions that I frequently use, for example FILE, string.
When I try to add this basic types in the C++.sublime-syntax, the compiler doesn’t show any errors but my source code still has this words white.

When I add that words, for example in control_keywords, my source code change and this words are colored according to my color scheme (1337).

What I have to do?
Thanks
Bye!!

0 Likes

#2

The C++ Syntax file is mostly RegEx and using the default method of tracking - ie for strings looking for the start, and when found looking for valid data before ending, etc…

For functions there are no keywords from what I saw…

I’d suggest creating a custom folder in %AppData%\Sublime Text 3\Packages\ and copying the file there - it’ll appear under view > Syntax > FolderName > C++

You could easily add your own scope to the file itself - I did it for my GMod Lua additions and it makes it easier for maintenance…

<!-- AcecoolDev_Framework Pre-Determined Local Variables -->
		<dict>
			<key>match</key>
			<string>\b(_p|_w|_ent|_v|_convar|_color|_col|_npc|_mat|_restore|_pos|_save|_cmd|_sound|_ed|_md|_texture|_file|_damageinfo|_matrix|_ang|_phys|_locomotion|_nextbox|_pathfollower|_rf|_nav|_panel|_emitter|_particle|_audio|_load|_tab|_b|_func|_num|_string|_trace|_effect|_path|_realm|_namespace|_name|_dmginfo|_bullet|_meta|_trace.HitPos|_trace.HitNormal|_trace.Entity|_trace|_dmginfo|_bullet)\b</string>
			<key>name</key>
			<string>constant.language.lua</string>
		</dict>
		<!-- AcecoolDev_Framework colors| StartsWith -->
		<dict>
			<key>match</key>
			<string>\b(color_white|color_black|colors.alice_blue|colors.amber|colors.antique_white|colors.army|colors.aqua|colors.aquamarine|colors.azure|colors.beige|colors.bisque|colors.blanched_almond|colors.black|colors.blue|colors.blue_violet|colors.brown|colors.burley_wood|colors.cadet_blue|colors.chartreuse|colors.chocolate|colors.coral|colors.cornflower_blue|colors.cornsilk|colors.crimson|colors.cyan|colors.darkergray|colors.darkgray|colors.darkgrey|colors.dark_blue|colors.dark_cyan|colors.dark_golden_rod|colors.dark_gray|colors.dark_grey|colors.dark_green|colors.dark_khaki|colors.dark_magenta|colors.dark_olive_green|colors.dark_orange|colors.dark_orchid|colors.dark_red|colors.dark_salmon|colors.dark_sea_green|colors.dark_slate_blue|colors.dark_slate_gray|colors.dark_turqoise|colors.dark_violet|colors.deep_pink|colors.deep_sky_blue|colors.dim_gray|colors.dim_grey|colors.dodger_blue|colors.fire_brick|colors.floral_white|colors.forest_green|colors.fuchsia|colors.gainsboro|colors.ghost_white|colors.gold|colors.golden_rod|colors.gray|colors.grey|colors.green|colors.green_yellow|colors.honey_dew|colors.hot_pink|colors.indian_red|colors.indigo|colors.ivory|colors.khaki|colors.lavender|colors.lavender_blush|colors.lawn_green|colors.lemon_chiffon|colors.lightgray|colors.light_blue|colors.light_coral|colors.light_cyan|colors.light_goldenrod_yellow|colors.light_gray|colors.light_green|colors.light_pink|colors.light_salmon|colors.light_sea_green|colors.light_sky_blue|colors.light_slate_gray|colors.light_steel_blue|colors.light_yellow|colors.lilac|colors.lime|colors.lime_green|colors.linen|colors.magenta|colors.maroon|colors.medium_aqua_marine|colors.medium_blue|colors.mediumgray|colors.medium_orchid|colors.medium_purple|colors.medium_sea_green|colors.medium_slate_blue|colors.medium_sprint_green|colors.medium_turqoise|colors.medium_violet_red|colors.midnight_blue|colors.mint_cream|colors.misty_rose|colors.moccasin|colors.navajo_white|colors.navy|colors.old_lace|colors.olive|colors.olive_drab|colors._orange|colors.orange|colors.orange_red|colors.orchid|colors.pale_golden_rod|colors.pale_green|colors.pale_violet_red|colors.papaya_whip|colors.peach_puff|colors.peru|colors._pink|colors.pink|colors.plum|colors.powder_blue|colors.purple|colors.red|colors.rosy_brown|colors.royal_blue|colors.saddle_brown|colors.salmon|colors.sandy_brown|colors.sea_green|colors.sea_shell|colors.sienna|colors.silver|colors.sky_blue|colors.slate_blue|colors.slate_gray|colors.snow|colors.snowy|colors.spring_green|colors.steel_blue|colors.tan|colors.teal|colors.thistle|colors.tomato|colors.turquoise|colors.violet|colors.wheat|colors.white|colors.white_smoke|colors.yellow|colors.yellow_green)\b</string>
			<key>name</key>
			<string>constant.language.lua</string>
		</dict>
		<!-- AcecoolDev_Framework other table data -->
		<dict>
			<key>match</key>
			<string>\b(vector_origin|angle_zero)\b</string>
			<key>name</key>
			<string>constant.language.lua</string>
		</dict>
		<!-- AcecoolDev_Framework META Tables -->
		<dict>
			<key>match</key>
			<string>\b(META_DATABASE|META_PLAYER|META_WEAPON|META_ENTITY|META_VEHICLE|META_CONVAR|META_COLOR|META_NPC|META_IMATERIAL|META_IRESTORE|META_VECTOR|META_ISAVE|META_CUSERCMD|META_CSOUNDPATCH|META_CEFFECTDATA|META_CMOVEDATA|META_ITEXTURE|META_FILE|META_CTAKEDAMAGEINFO|META_VMATRIX|META_ANGLE|META_PHYSOBJ|META_CLUALOCOMOTION|META_NEXTBOT|META_DATABASE|META_PATHFOLLOWER|META_CRECIPIENTFILTER|META_CNAVAREA|META_PANEL|META_EMITTER|META_PARTICLE|META_GMODAUDIOCHANNEL|META_LOADLIB|META_PRELOAD|META_LOADED|META_TABLE|META_BOOLEAN|META_FUNCTION|META_NUMBER|META_STRING)\b</string>
			<key>name</key>
			<string>constant.language.lua</string>
		</dict>
<!-- AcecoolDev_Framework Libraries -->
		<dict>
			<key>match</key>
			<string>\b(accessors|audio|autoloader|binds|cards|card|character|colors|config|container|controller|credits|database|data|deck|dialogue|doors|effects|elevators|errors|event|fileio|gamedata|game|gatekeeper|gm|inventory|io|item|language|logic|logs|managed_list|map|notify|npcs|objectives|objective|object|physics|plants|player|poly|prop_interface|poly|quests|readonly|round|seeds|settings|shop_npcs|sounds|steam_api|stencil|team|timer|time|tutorial|uniqueid|vehicles|version|wiki|xml|permission)\b</string>
			<key>name</key>
			<string>constant.language.lua</string>
		</dict>
		<!-- AcecoolDev_Framework Extensions -->
		<dict>
			<key>match</key>
			<string>\b(file\.(ReadRunction|ReadLines|ReadJSON|WriteJSON))\b</string>
			<key>name</key>
			<string>support.function.library.lua</string>
		</dict>

Notice how the scope is the same across multiple entries - this works and will show ALL of the additions as though they were all in the same category - also making things easier to maintain…

the Lua file I edited is .tmLanguage but the same should still work for sublime-syntax but a slightly different way of typing it. I converted Lua to .tmLanguage from sublime-syntax ( Short story: I thought CodeMap required .tmLanguage but it can use either - whoops )…

Here are both files for comparison:

Lua.sublime-syntax

%YAML 1.2
---
# http://www.sublimetext.com/docs/3/syntax.html
name: Lua
comment: "Lua Syntax: version 0.8"
file_extensions:
  - lua
scope: source.lua
contexts:
  main:
    - match: '\b(function|func|ƒ|F|f)\s+([a-zA-Z_.:]+[.:])?([a-zA-Z_]\w*)\s*(\()([^)]*)(\))'
      scope: meta.function.lua
      captures:
        1: keyword.control.lua
        2: entity.name.function.scope.lua
        3: entity.name.function.lua
        4: punctuation.definition.parameters.begin.lua
        5: variable.parameter.function.lua
        6: punctuation.definition.parameters.end.lua
    - match: '(?<![\d.])\b0[xX][a-fA-F\d\.]+([pP][\-\+]?\d+)?|\b\d+(\.\d+)?([eE]-?\d+)?|\.\d+([eE]-?\d+)?'
      scope: constant.numeric.lua
    - match: "'"
      captures:
        0: punctuation.definition.string.begin.lua
      push:
        - meta_scope: string.quoted.single.lua
        - match: "'"
          captures:
            0: punctuation.definition.string.end.lua
          pop: true
        - match: '\\([abfnrtv\\"'']|\r?\n|\n\r?|\d\d?\d?)'
          scope: constant.character.escape.lua
        - match: '\\[xX][0-9a-fA-F][0-9a-fA-F]'
          scope: constant.character.escape.lua
        - match: '\\u\{[0-9a-fA-F]{,7}\}'
          scope: constant.character.escape.lua
    - match: '"'
      captures:
        0: punctuation.definition.string.begin.lua
      push:
        - meta_scope: string.quoted.double.lua
        - match: '"'
          captures:
            0: punctuation.definition.string.end.lua
          pop: true
        - match: '\\([abfnrtv\\"'']|\r?\n|\n\r?|\d\d?\d?)'
          scope: constant.character.escape.lua
        - match: '\\[xX][0-9a-fA-F][0-9a-fA-F]'
          scope: constant.character.escape.lua
        - match: '\\u\{[0-9a-fA-F]{,7}\}'
          scope: constant.character.escape.lua
    - match: '(?<!--)\[(=*)\['
      captures:
        0: punctuation.definition.string.begin.lua
      push:
        - meta_scope: string.quoted.other.multiline.lua
        - match: '\]\1\]'
          captures:
            0: punctuation.definition.string.end.lua
          pop: true
    - match: '--\[(=*)\['
      captures:
        0: punctuation.definition.comment.lua
      push:
        - meta_scope: comment.block.lua
        - match: '\]\1\]'
          captures:
            0: punctuation.definition.comment.lua
          pop: true
    - match: '(--)(?!\[\[).*$\n?'
      scope: comment.line.double-dash.lua
      captures:
        1: punctuation.definition.comment.lua
    - match: \b(break|do|else|for|if|elseif|return|then|repeat|while|until|end|function|func|ƒ|F|f|local|in)\b
      scope: keyword.control.lua
    - match: '(?<![^.]\.|:)\b(false|nil|true|_G|_VERSION|math\.(pi|huge))\b|(?<![.])\.{3}(?!\.)'
      scope: constant.language.lua
    - match: '(?<![^.]\.|:)\b(self)\b'
      scope: variable.language.self.lua
    - match: '(?<![^.]\.|:)\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\b(?=[( {"''\[])'
      scope: support.function.lua
    - match: '(?<![^.]\.|:)\b(coroutine\.(create|resume|running|status|wrap|yield)|string\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\.(concat|insert|maxn|remove|sort)|math\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\.(cpath|loaded|loadlib|path|preload|seeall)|debug\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\b(?=[( {"''\[])'
      scope: support.function.library.lua
    - match: \b(and|or|not)\b
      scope: keyword.operator.lua
    - match: '\+|-|%|#|\*|\/|\^|==?|~=|<=?|>=?|(?<!\.)\.{2}(?!\.)'
      scope: keyword.operator.lua

So, everything works the same way… so in main simply add a - match: line, scope, and captures list to define something… You don’t need the extra push, pop, etc…

So as a test, I added (function|func|ƒ|F|f) to c++ ( as keywords and they now highlight… ) Here’s the c++ file if you’d like to use it to compare default from edited…

default c++:
EXCLUDED BECAUSE OF LENGTH

I added custom_keywords under variables and modified modifiers under variables to include it…


scope: source.c++
variables:
  custom_keywords: 'function|func|ƒ|F|f'

  ...

  modifiers: '{{storage_classes}}|{{type_qualifier}}|{{compiler_directive}}|{{custom_keywords}}'

  ...
  

Then it lights right up…

If I tried adding the keywords to most of the other locations, it didn’t seem to do anything… The C++ syntax file is quite complex - the method above is an easy way for these keywords to become highlighted…

Hopefully this helps.

Note: I’ve removed most of the default code, etc… In most languages it’s easy to add keywords but because of how complex the C++ file is, it’s a little trickier but you can use the above method for a quick and easy way in… You may need to relaunch sublime text editor for the changes to show though… ( Which reminds me that I need to add a monitor for it to be reloaded if edited )

0 Likes

#3

Thanks for your answer Acecool!

I have done it, but char, int etc… and my keywords have not the same color!!

I have edited the C++.sublime-syntax as you suggested…and now what should I do?

Thanks for helping me!
I am very grateful

Dany

0 Likes

#4

Hold ALT then press M 2 times - that should open the mapper - for untitled files there may be issues detecting the type of file ( I’m working on a stand-alone system so I’ll add a way to detect what unnamed files are by seeing the syntax set )…

Sorry - wrong response was for an addon…

Did you create the new keywords var above the modifiers var?

Each keyword between so blah|bleh|int|void|main
and nothing else…

Here’s mine: look for custom_keywords: https://www.dropbox.com/s/csdel9f259y5deu/C%2B%2B.sublime-syntax?dl=0

I just tried it with your file contents and I added a few keywords and it does change color… Note: Make sure View > Syntax > C++ is selected ( or if you have the modified one in a different folder that you use that folder in the Syntax menu so > _Acecool > C++ would appear if Sublime Text 3\Packages_Acecool\ was used…

C++ syntax file is very complex - the modifiers var may not be targeting the specific scope you’re trying to find… My next version of my code mapping system includes default symbols mapper for all languages and it has the ability to grab the scope so from your file:

Mapping: test.cpp containing: 11 lines and 16 entries!

☼ function: Core = 'For function declarations..';
    int main(   )                                                                                                            :3

☼ SublimeText: Symbols = 'This is what Sublime Text reports as important information to the Command Palette and allows for quick ju';
    int main( ) - Scope: source.c++ meta.function.c++ entity.name.function.c++   

The scope allows you to see where in the syntax file the data is targeted ie where you can add keywords to highlight it…

Additionally, if your theme doesn’t have the scope set up then you won’t see the colors highlighted so try switching themes to see if the colors are still hidden - there is a quick theme switcher on Package Control which is quite nice and a theme editor too… ( for colors, etc… all done live )

0 Likes

#5

Amazing!!!
I have done it!

I edited my color scheme opening it with PackageResourceViewer and next with ColorSchemeEditor.
I selected “int”, I copied the color definition of it (Storage type) and pasted into color definition of “FILE” (Storage)…

Thank you for helping me Acecool…

Now Just Keep in Code :wink:

Bye,

Dany

1 Like