Creating a custom code writer

One of the strong features of Yellicode is its extensibility. It doesn't include any language- or platform specific API's, but instead makes it easy to build (and share!) your own extensions. Let's create a simple class that can write source code documentation for us, formatted in markdown.

A simple MarkdownWriter

Create a new TypeScript file and add the following code. As you can see, this is a very basic writer class.

import { CodeWriter } from '@yellicode/templating';

export class MarkdownWriter extends CodeWriter {
    
    public writeH1(text: string): void{
        this.writeLine('# '+text);
    }

    public writeH2(text: string): void{
        this.writeLine('## '+text);
    }

    public writeH3(text: string): void{
        this.writeLine('### '+text);
    }

    public writeListItem(text: string){
        this.writeLine('* '+text);
    }

    public writeEmphasisLine(text: string, strong: boolean = false) {
        if (strong) this.writeLine('**'+text+'**');
        else this.writeLine('*'+text+'*'); 
    }     
}     

Our MarkdownWriter inherits from the CodeWriter base class. The CodeWriter is a class that implements all functions of the TextWriter interface. You create an instance of any CodeWriter-derived class by providing it with the default TextWriter that Yellicode creates for you in the template:

Generator.generateFromModel( {outputFile: './markdown-output.md'}, (writer: TextWriter, model: elements.Model) => {    
    const markdown = new MarkdownWriter(writer);
});    

Generating Markdown code

To complete this how-to, let's create a simple template that generates a markdown file that documents all classes in our model:

import * as elements from '@yellicode/elements';
import { Generator, TextWriter } from '@yellicode/templating';
import { MarkdownWriter } from './markdown-writer';

Generator.generateFromModel({ outputFile: './markdown-output.md' }, (writer: TextWriter, model: elements.Model) => {
    const markdown = new MarkdownWriter(writer);
    markdown.writeH1(`${pack.name} Documentation`);
    model.getAllClasses().forEach(c => {
        // Write the class name
        markdown.writeH2(c.name);
        markdown.writeEmphasisLine(c.getFirstCommentBody());
        markdown.writeLine();
        // Write a list item for each class property
        markdown.writeH3(`${c.name} properties`);
        c.getAllAttributes().forEach(att => {
            markdown.writeListItem(`${att.name} (${att.getTypeName()}): ${att.getFirstCommentBody()}`);
        });
        markdown.writeLine();
    })
});

That's it! We've just created our first custom code writer for a relatively simple markup language. Feel free to modify it, extend it to match your needs our share your own writers with the community!