Code Formatting

Topics: Developer Forum
Feb 19, 2012 at 7:21 PM

Is it possible for the editor to auto-format some code?

For example I load some xml from a database and display it on the editor but it's on one line and therefore very hard to work with.

Even though, I can use the word wrap, it is not optimal. I would like the xml code to show up with proper indentation, like on Visual Studio.

Any suggestions?

Coordinator
Feb 19, 2012 at 7:58 PM

There is nothing within ScintillaNET itself that will do code formatting for you as you've described.

ScintillaNET is able to perform syntax highligting through the user of a lexer (or sometimes called a scanner). This process identifies tokens and assigns them a color based on whether they match a predfined list.

To perform code formatting requires understanding the meaning of those tokens through the use of a parser. That's a level of complexity far exceeding just lexing and therefore usually only high-end IDE's support code formatting.

Fortunately for you, an XML parser readily exists in the form of the XmlReader/XmlWriter classes of the .NET framework. Using the XmlWriterSettings class to configure indentation needs you should very easily be able to:

  • Create a new TextReader (StringReader) from the text of the ScintillaNET control and pass it to a new XmlReader
  • Create a new XmlWriterSettings class configured to use indentation
  • Create a new TextWriter (StringWriter) and pass it to a new XmlWriter
  • Copy each node from the reader to the writer
  • Put the result back into ScintillaNET

 

Cheers

Feb 19, 2012 at 8:35 PM
Edited Feb 19, 2012 at 8:54 PM

Thanks for that.

    static public string Beautify(XmlDocument doc)
    {
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = "  ";
        settings.NewLineChars = "\r\n";
        settings.NewLineHandling = NewLineHandling.Replace;
        XmlWriter writer = XmlWriter.Create(sb, settings);
        doc.Save(writer);
        writer.Close();
        return sb.ToString();
    }

 Found here: http://stackoverflow.com/questions/203528/what-is-the-simplest-way-to-get-indented-xml-with-line-breaks-from-xmldocument/203581#203581