title: How do I create an AvalonEdit syntax file (.xshd) and embed it into my assembly?
body: <p>I'm trying to define some custom highlighting rules for AvalonEdit. There doesn't seem to be any documentation for this -- there's <a href="http://www.codeproject.com/KB/edit/AvalonEdit.aspx" rel="noreferrer">some documentation on the file format</a>, but nothing on how to actually load and use the definition once you've created it.</p>
  
  <p>The "<a href="http://wiki.sharpdevelop.net/Syntax%20highlighting.ashx" rel="noreferrer">Syntax highlighting</a>" wiki page (for the old WinForms TextEditor) documents how to load highlighting definitions from a .xshd file on disk, but I'd rather embed it as a resource, the same way AvalonEdit does with its built-in definitions.</p>
  
  <p>I've looked at the code in the ICSharpCode.AvalonEdit project that loads its built-in highlighters, but the actual "load from resource" code is done in DefaultHighlightingManager.LoadHighlighting, which is private -- and which, to make things weirder, is apparently only called in release builds.</p>
  
  <p>I can keep fumbling around, copy/paste some of the code from the private methods, and try to cobble something together that might or might not work, but it seems worthwhile to ask: <strong>what is the standard way to do this?</strong> Is there a recommended way for third-party code to load a highlighting definition from a resource?</p>
  
  <hr>
  
  <p><a href="https://stackoverflow.com/questions/5057210/how-do-i-create-an-avalonedit-syntax-file-xshd-and-embed-it-into-my-assembly/5057464#5057464">Daniel's answer</a> gave me a good start, but you need to include the namespace name in the string you pass to GetManifestResourceStream -- if you don't, you'll get a NullReferenceException (because it returns a null stream).</p>
  
  <p>I wound up adding a static class called ResourceLoader to the same project folder as the .xshd file, with this method:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static IHighlightingDefinition LoadHighlightingDefinition(
      string resourceName)
  {
      var type = typeof(ResourceLoader);
      var fullName = type.Namespace + "." + resourceName;
      using (var stream = type.Assembly.GetManifestResourceStream(fullName))
      using (var reader = new XmlTextReader(stream))
          return HighlightingLoader.Load(reader, HighlightingManager.Instance);
  }
  </code></pre>
  
  <p>Then I can just call <code>ResourceLoader.LoadHighlightingDefinition("Name.xshd")</code>.</p>
  
  <p>For anyone following along at home, the .xshd file needs to have its Build Action set to Embedded Resource.</p>