Sublime Forum

Enhance Syntax Definition for embedded code

#1

Hey,

I currently try to enhance my Syntax highlighting for Unity Shader code.

A part of the shader file is commonly a section that begins with CGPROGRAM and ends with ENDCG.

Since this part of the file has a very C like code I’d like to use the existing code highlighting.
Unfortunately a lot of shader specific types are not highlighted (float4 for example).

Currently it’s possible to switch to C highlighting correctly. But how can I matching of shader specific words to the C part. The following does not work:

%YAML 1.2
---
name: Unity Shader
file_extensions: [shader cginc]
scope: source.unity_shader
uuid: e3872ec7-60d7-4cc2-bf8f-57da56c339f2
first_line_match: (Shader \".*\")
variables:
  types: (?<=[, \s\(\)])(((float|half|fixed)[2-4]?)|SurfaceOutput|bool|sampler(CUBE|[23]D)|void|2D|Color|struct|[Ff]loat|[Rr]ange|[Vv]ector[234]?)(?=[,\s\(\)])
contexts:
  main:
  - comment: CGPROGRAM
    match: CGPROGRAM
    push: cgprogram_main
    with_prototype:
        - match: (?=ENDCG)
          pop: cgprogram_main
  - comment: Keywords
    scope: keyword.source.unity_shader
    match: (Sub)?Shader|Category|Properties|Fall[Bb]ack|Tags|LOD|Cull|Blend|AlphaTest|ColorMask|Lighting|ZWrite|BindChannels|Pass|return
  - comment: Comment
    scope: comment.source.unity_shader
    match: //.*$
  - comment: Types
    scope: storage.type.source.unity_shader
    match: '{{types}}'
  - comment: String
    scope: string.quoted.double.source.unity_shader
    match: \".*\"
  - comment: Preprocessor
    scope: meta.preprocessor.source.unity_shader
    match: ^(\#)(pragma|include|ifdef|endif|if|define).*$
    captures:
      1: keyword.control.source.unity_shader
      2: keyword.control.source.unity_shader
  - comment: number literals
    scope: constant.numeric.source.unity_shader
    match: \b([-+]?([0-9]+(\.[0-9]+)?|\.[0-9]+)[\s]*,[\s]*)*([-+]?([0-9]+(\.[0-9]+)?|\.[0-9]+)[fF]?)+\b
  cgprogram_main:
    - comment: Types
      scope: storage.type.source.unity_shader
      match: '{{types}}'
    - match: ""
      push: Packages/C++/C.sublime-syntax
      with_prototype:
        - match: ""
          pop: Packages/C++/C.sublime-syntax

Thank you very much.

0 Likes

#2

I’ve never seen anything other than pop: true before, presumably you mean to use set: instead of pop:

0 Likes

#3

Yeah that was one of my mistakes :smiley: . I use a slightly different approach now (this is just an excerpt of the whole file):

  - comment: CGPROGRAM
    match: CGPROGRAM
    push: cgprogram_main
    with_prototype:
      - match: 'float[2-4]'
        scope: storage.type.source.unity_shader
      - match: (?=ENDCG)
        pop: true
        
  cgprogram_main:
    - include: scope:source.c++

However I found another problem. I’ll make another thread for it.

0 Likes