/* Start - Docs Templating logic
437886
function commandListTitle(command, context) {
  const url  = (context === 'README') ? `/docs/commands/${command}.md` : `/commands/${command}`
  // const url  = (context === 'README') ? `/docs/${command}.md` : `/${command}`
  return `### [${command}](${url})${newLine}`
}
102365
function replaceWithTemplateType(start, end) {
    var templateToken = {
      type: "Template",
      value: createTemplateValue(start, end),
      start: tokens[start].start,
      end: tokens[end].end,
      loc: {
        start: tokens[start].loc.start,
        end: tokens[end].loc.end
      }
    };

    // put new token in place of old tokens
    tokens.splice(start, end - start + 1, templateToken);
  }
141204
private Node initTemplate(Node templateFunctionNode) {
    Node prepped = templateFunctionNode.cloneTree();
    prepTemplatePlaceholders(prepped);

    Node body = prepped.getLastChild();
    Node startNode;
    if (body.hasOneChild() && body.getFirstChild().isExprResult()) {
      // When matching an expression, don't require it to be a complete
      // statement.
      startNode = body.getFirstFirstChild();
    } else {
      startNode = body.getFirstChild();
    }

    for (int i = 0; i < templateLocals.size(); i++) {
      // reserve space in the locals array.
      this.localVarMatches.add(null);
    }
    for (int i = 0; i < templateParams.size(); i++) {
      // reserve space in the params array.
      this.paramNodeMatches.add(null);
    }

    return startNode;
  }
1218088
function (tpl, option) {
            var code = compiler.compile(tpl);
            option = option || {};
            // eval is not ok for eval("(function(){})") ie
            return (Function.apply(null, []
                .concat(code.params)
                .concat(code.source.join('\n') + '//@ sourceURL=' +
                    (option.name ? option.name : ('xtemplate' + (xtemplateId++))) + '.js')));
        }
513142
function XTemplate(tpl, config) {
  var tplType = (typeof tpl);
  if (tplType !== 'string' && tplType !== 'function') {
    config = tpl;
    tpl = undefined;
  }
  config = this.config = util.merge(XTemplate.globalConfig, config);
  if (tplType === 'string') {
    try {
      tpl = this.compile(tpl, config.name);
    } catch (err) {
      this.compileError = err;
    }
  }
  XTemplateRuntime.call(this, tpl, config);
}
4859
function compile(tmpl, conf) {
  const c = Object.assign(
    {},
    settings,
    conf,
  );

  const template = new LayoutTemplate({
    conf: c,
    tmpl,
  });

  return bracket.compile(
    template.compile(),
    template.conf,
  );
}
634117
function(template) {
        // no pragmas
        if(!this.includes("%", template)) {
          return template;
        }

        var that = this;
        var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" +
              this.ctag);
        return template.replace(regex, function(match, pragma, options) {
          if(!that.pragmas_implemented[pragma]) {
            throw({message:
              "This implementation of mustache doesn't understand the '" +
              pragma + "' pragma"});
          }
          that.pragmas[pragma] = {};
          if(options) {
            var opts = options.split("=");
            that.pragmas[pragma][opts[0]] = opts[1];
          }
          return "";
          // ignore unknown pragmas silently
        });
      }
1176791
function template(tmpl, data) {
  // Grab the template engine
  var engine = settings['template engine'];

  // Process the template through the template engine
  var content = engine.call(this, tmpl, data);

  // Return the content
  return content;
}
374170
public static boolean start(RootDoc rootDoc) {
        final MarkdownTaglets markdownTaglets = MarkdownTaglets.instance();
        Options options = new Options();
        String[][] forwardedOptions = options.load(rootDoc.options(), rootDoc);
        if ( forwardedOptions == null ) {
            return false;
        }
        MarkdownDoclet doclet = new MarkdownDoclet(options, rootDoc);
        markdownTaglets.setDocErrorReporter(doclet);
        doclet.process();
        if ( doclet.isError() ) {
            return false;
        }
        RootDocWrapper rootDocWrapper = new RootDocWrapper(rootDoc, forwardedOptions);
        if ( options.isHighlightEnabled() ) {
            // find the footer option
            int i = 0;
            for ( ; i < rootDocWrapper.options().length; i++ ) {
                if ( rootDocWrapper.options()[i][0].equals("-footer") ) {
                    rootDocWrapper.options()[i][1] += HIGHLIGHT_JS_HTML;
                    break;
                }
            }
            if ( i >= rootDocWrapper.options().length ) {
                rootDocWrapper.appendOption("-footer", HIGHLIGHT_JS_HTML);
            }
        }
        return Standard.start(rootDocWrapper) && doclet.postProcess();
    }
804704
function () {
      this.removeChildInstances();

      if (this.template) {
        var args = this.getTemplateArguments();

        // temporarily assign a new node to get the content in a doc fragment
        var realNode = this.node;
        var df = doc.createDocumentFragment();
        this.node = df;
        this.template.call(this, args);

        realNode.insertBefore(df, this.node2);
        this.replaceNodeBy(df , realNode); // recursively remove doc fragment reference
        // now this.node=realNode
        this.isDOMempty = false;
      }
  }
148316
function(options, cb) {

        function renderTemplate(callback) {
            options.soajs.log.debug('Rendering template ...');
            engine.render(options, function(error, output) {
                if(error) return callback({error: error.value, code: error.code});

                return callback(null, { render: output.render });
            });
        }

        function writeTemplate(result, callback) {
            options.soajs.log.debug('Writing template to temp folder ...');
            let templateFolderPath = path.join(__dirname, config.terraform.tempFolderPrefix);
            let templateFiles = [
                { name: config.terraform.templateDefaultName, content: result.renderTemplate.render }
            ];

            //if input includes a state object, add it as well
            if(options.params && options.params.templateState && Object.keys(options.params.templateState).length  > 0) {
                templateFiles.push({ name: config.terraform.stateFileName, content: JSON.stringify(options.params.templateState, null, 2) });
            }

            options.params.path = templateFolderPath;
            options.params.files = templateFiles;
            helper.writeToTempFolder(options, function(error, output) {
                if (error) return callback({error, code: 728});
                return callback(null, output);
            });
        }

        function applyTemplate(result, callback) {
            options.soajs.log.debug('Applying template ...');
            options.params.command = config.terraform.applyCommand;
            options.params.cwd = result.writeTemplate.tempFolderPath;
            helper.runChildProcess(options, function(error, output) {
                if(error) {
                    options.soajs.log.error('Applying template FAILED ...');
                    return callback(null, error); // pass error to readOutput and cleanup, then trigger rollback if applicable
                }
                return callback(null, output);
            });
        }

        function readOutput(result, callback) {
            options.soajs.log.debug('Reading output state file ...');
            let stateFilePath = path.join(result.writeTemplate.tempFolderPath, config.terraform.stateFileName);

            function readFile(counter, readFileCb) {
                fs.readFile(stateFilePath, { encoding: 'utf8' }, function(error, stateFileData) {
                    if(error) {
                        if(counter < config.terraform.stateFileReadMaxAttempts) {
                            return setTimeout(readFile.bind(null, ++counter, readFileCb), config.terraform.stateFileReadTimeout);
                        }

                        options.soajs.log.error('Unable to read template state file ...');
                        options.soajs.log.error(error);

                        if(result.applyTemplate && result.applyTemplate.error) {
                            // apply failed + no state file could be read means the template failed because of a syntax error
                            // return an empty object for the state file
                            return readFileCb(null, '{}');
                        }

                        let readFileError = { code: 730, msg: errors[730], debug: error };
                        return readFileCb({ error: readFileError });
                    }

                    return readFileCb(null, stateFileData);
                });
            }

            readFile(0, function(error, stateFileData) {
                if(error) {
                    stateFileData = error; // do not stop execution, return state file read error instead
                }
                else {
                    try {
                        stateFileData = JSON.parse(stateFileData);
                    }
                    catch(e) {
                        let parseError = { code: 730, msg: errors[730], debug: e };
                        return callback(null, { error: parseError }); // do not stop execution, return state file parse error instead
                    }
                }

                return callback(null, { stateFileData });
            });
        }

        function cleanup(result, callback) {
            options.soajs.log.debug('Cleaing up temp folder ...');
            helper.cleanup({ tempFolderPath: result.writeTemplate.tempFolderPath }, function(error) {
                if(error) options.soajs.log.error('Cleanup failed after applying terraform template!', error);
                return callback(null, true);
            });
        }

        function rollback(options, result, terraformErrors, callback) {
            if(!result.readOutput || !result.readOutput.stateFileData || (typeof(result.readOutput.stateFileData) === 'object' && Object.keys(result.readOutput.stateFileData).length === 0)) {
                options.soajs.log.debug('Terraform state file not found, rollback is not possible ...');
                return callback({
                    source: 'driver',
                    value: terraformErrors.applyError,
                    code: 729,
                    msg: terraformErrors.applyError
                });
            }

            options.soajs.log.debug('Terraform deployment failed, rolling back ...');
            // options.params.layerName and options.params.exclude are already set
            options.params.template = result.renderTemplate.render;
            options.params.templateState = result.readOutput.stateFileData;
            return engine.destroy(options, function(destroyError, destroyResult) {
                if(destroyError) {
                    options.soajs.log.debug('Terraform rollback failed ...');
                    terraformErrors.destroyError = destroyError;
                }

                return callback({
                    source: 'driver',
                    value: terraformErrors.applyError,
                    code: 729,
                    msg: terraformErrors.applyError
                });
            });
        }

        async.auto({
            // render template + input using handlebars
            renderTemplate,
            // create temp folder and write template to folder
            writeTemplate: ['renderTemplate', writeTemplate],
            // terraform init and terraform apply
            applyTemplate: ['writeTemplate', applyTemplate],
            // read terraform.tfstate file
            readOutput: ['writeTemplate', 'applyTemplate', readOutput],
            // delete temp folder
            cleanup: ['writeTemplate', 'readOutput', cleanup]
        }, function(error, result) {
            utils.checkError(error && error.error, error && error.code, cb, () => {
                let backupData = { render: result.renderTemplate.render, templateOutput: result.applyTemplate };
                helper.backup((options.params.templateState) ? 'modify' : 'create', options, backupData, function() {
                    if(result.applyTemplate && result.applyTemplate.error) {
                        let terraformErrors = {};
                        terraformErrors.applyError = helper.parseErrorOutput({ output: result.applyTemplate.error });
                        // not options.params.templateState -> this is a create operation
                        // result.readOutput.stateFileData -> not a terraform syntax error, deployment started but failed
                        if(!options.params.templateState && result.readOutput && result.readOutput.stateFileData) {
                            return rollback(options, result, terraformErrors, cb);
                        }
                        else {
                            // this is a modify operation, do not destroy | return error
                            return utils.checkError(error && error.error, error && error.code, cb, cb);
                        }
                    }

                    return cb(null, {
                        applied: true,
                        stateFileData: result.readOutput.stateFileData,
                        output: result.applyTemplate.output,
                        render: result.renderTemplate.render
                    });
                });
            });
        });
    }
443137
@Override
    public void startDocument() throws SAXException {
        try {
            switch (doctype) {
                case NO_DOCTYPE:
                    return;
                case DOCTYPE_HTML5:
                    writer.write("<!DOCTYPE html>\n");
                    return;
                case DOCTYPE_HTML401_STRICT:
                    writer.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n");
                    return;
                case DOCTYPE_HTML401_TRANSITIONAL:
                    writer.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
                    return;
            }
        } catch (IOException ioe) {
            throw (SAXException)new SAXException(ioe).initCause(ioe);
        }
    }
1074795
function()
		{
			var startContainer = this.startContainer,
				startOffset = this.startOffset;

			// If the starting node is a text node, and non-empty before the offset,
			// then we're surely not at the start of block.
			if ( startOffset && startContainer.type == CKEDITOR.NODE_TEXT )
			{
				var textBefore = CKEDITOR.tools.ltrim( startContainer.substring( 0, startOffset ) );
				if ( textBefore.length )
					return false;
			}

			// Antecipate the trim() call here, so the walker will not make
			// changes to the DOM, which would not get reflected into this
			// range otherwise.
			this.trim();

			// We need to grab the block element holding the start boundary, so
			// let's use an element path for it.
			var path = new CKEDITOR.dom.elementPath( this.startContainer );

			// Creates a range starting at the block start until the range start.
			var walkerRange = this.clone();
			walkerRange.collapse( true );
			walkerRange.setStartAt( path.block || path.blockLimit, CKEDITOR.POSITION_AFTER_START );

			var walker = new CKEDITOR.dom.walker( walkerRange );
			walker.evaluator = getCheckStartEndBlockEvalFunction( true );

			return walker.checkBackward();
		}
660186
private function parseTemplatingSettings(\DOMNode $templating) {

		if(is_null($this->templating)) {
			$this->templating = new \stdClass;
			$this->templating->filters = [];
		}

		$xpath = new \DOMXPath($templating->ownerDocument);

		foreach($xpath->query("filters/filter", $templating) as $filter) {

			$id = $filter->getAttribute('id');
			$class = $filter->getAttribute('class');

			if(!$id) {
				throw new ConfigException('Templating filter without id found.');
			}

			if(!$class)	{
				throw new ConfigException(sprintf("No class for templating filter '%s' configured.", $id));
			}

			if(isset($this->templating->filters[$id])) {
				throw new ConfigException(sprintf("Templating filter '%s' has already been defined.", $id));
			}

			// clean path delimiters, prepend leading backslash, and replace slashes with backslashes

			$class = '\\' . ltrim(str_replace('/', '\\', $class), '/\\');

			// store parsed information

			$this->templating->filters[$id] = [
				'class' => $class,
				'parameters' => $filter->getAttribute('parameters')
			];

		}

	}
306627
function Doc(runner) {
  Base.call(this, runner);

  var self = this
    , stats = this.stats
    , total = runner.total
    , indents = 2;

  function indent() {
    return Array(indents).join('  ');
  }

  runner.on('suite', function(suite){
    if (suite.root) return;
    ++indents;
    console.log('%s<section class="suite">', indent());
    ++indents;
    console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
    console.log('%s<dl>', indent());
  });

  runner.on('suite end', function(suite){
    if (suite.root) return;
    console.log('%s</dl>', indent());
    --indents;
    console.log('%s</section>', indent());
    --indents;
  });

  runner.on('pass', function(test){
    console.log('%s  <dt>%s</dt>', indent(), utils.escape(test.title));
    var code = utils.escape(utils.clean(test.fn.toString()));
    console.log('%s  <dd><pre><code>%s</code></pre></dd>', indent(), code);
  });
}
1132673
function fromPres( preHtmls, newBlock )
	{
		var docFrag;
		if ( preHtmls.length > 1 )
			docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );

		for ( var i = 0 ; i < preHtmls.length ; i++ )
		{
			var blockHtml = preHtmls[ i ];

			// 1. Trim the first and last line-breaks immediately after and before <pre>,
			// they're not visible.
			 blockHtml =  blockHtml.replace( /(\r\n|\r)/g, '\n' ) ;
			 blockHtml = replace(  blockHtml, /^[ \t]*\n/, '' ) ;
			 blockHtml = replace(  blockHtml, /\n$/, '' ) ;
			// 2. Convert spaces or tabs at the beginning or at the end to &nbsp;
			 blockHtml = replace(  blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset, s )
					{
						if ( match.length == 1 )	// one space, preserve it
							return '&nbsp;' ;
						else if ( !offset )		// beginning of block
							return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ';
						else				// end of block
							return ' ' + CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 );
					} ) ;

			// 3. Convert \n to <BR>.
			// 4. Convert contiguous (i.e. non-singular) spaces or tabs to &nbsp;
			 blockHtml =  blockHtml.replace( /\n/g, '<br>' ) ;
			 blockHtml =  blockHtml.replace( /[ \t]{2,}/g,
					function ( match )
					{
						return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ' ;
					} ) ;

			if ( docFrag )
			{
				var newBlockClone = newBlock.clone();
				newBlockClone.setHtml(  blockHtml );
				docFrag.append( newBlockClone );
			}
			else
				newBlock.setHtml( blockHtml );
		}

		return docFrag || newBlock;
	}
117346
function doctypeInInitialMode(p, token) {
    p._setDocumentType(token);

    const mode = token.forceQuirks ? HTML.DOCUMENT_MODE.QUIRKS : doctype.getDocumentMode(token);

    if (!doctype.isConforming(token)) {
        p._err(ERR.nonConformingDoctype);
    }

    p.treeAdapter.setDocumentMode(p.document, mode);

    p.insertionMode = BEFORE_HTML_MODE;
}