6

Is there an xshd ruleset for the AvalonEdit control to highlight the JSON syntax? I tried the definition for JavaScript, but it doesn't work well, i.e.:

{
   "name" : "value"
}

both name and value have the same color using the JavaScript definition.

Is there a ruleset for JSON, and if not, how can I modify the xshd so that I get different colors for the name and value in JSON?

2 Answers 2

11

If somebody needs something like that, I worked it out in following way:

<?xml version="1.0" encoding="utf-8" ?>
<SyntaxDefinition name="Json" extensions=".js" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
  <Color name="Digits" foreground="#8700FF" exampleText="3.14" />
  <Color name="Value" foreground="#000CFF" exampleText="var text = &quot;Hello, World!&quot;;" />
  <Color name="ParamName" foreground="#057500"  exampleText="var text = &quot;Hello, World!&quot;;" />
  <RuleSet ignoreCase="false">
    <Keywords color="Digits" >
      <Word>true</Word>
      <Word>false</Word>
    </Keywords>
    <Span color="ParamName">
      <Begin>"</Begin>
      <End>(?=:)</End>
    </Span>
    <Span color="Value" multiline="true">
      <Begin>
        (?&lt;=:)\040"[^"]*
      </Begin>
      <End>"</End>
    </Span>
    <Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
  </RuleSet>
</SyntaxDefinition>

Not perfect, but for me enough.

2
  • Thank you so much for this! I bound this to my view model and works beautifully. I'll no doubt extend it in future, but this is a great starting point! It would be great to get pull request into the AvalonEdit GitHub repository.
    – wonea
    Jul 25, 2017 at 9:13
  • 2
    Just a heads up for anyone looking at this now: There is an official one here: github.com/icsharpcode/AvalonEdit/blob/master/… It hilites numbers, string, bools, etc all in different colors.
    – Andy
    Apr 13, 2020 at 13:21
-1

Just use AvalonEdit's JavaScript highlighter.

Sample code:

using (var stream = Assembly.GetAssembly(typeof(ICSharpCode.AvalonEdit.TextEditor)).GetManifestResourceStream("ICSharpCode.AvalonEdit.Highlighting.Resources.JavaScript-Mode.xshd"))
{
    using (var reader = new XmlTextReader(stream))
    {
        avalonEdit.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
        SearchPanel.Install(avalonEdit);
    }
}
1
  • 1
    From OP's question: "I tried the definition for JavaScript, but it doesn't work well." Your answer does not solve the issue. Also it's much easier to set the JavaScript xshd by calling ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.GetDefinition("JavaScript"); Sep 12, 2016 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.