Generates HTML markup for a single line of code while determining alternating line style.
@param {Integer} lineNumber  Line number.
@param {String} code Line  HTML markup.
@return {String}       Returns HTML markup.
350361
function(lineIndex, lineNumber, lineHtml)
  {
    var classes = [
      'line',
      'number' + lineNumber,
      'index' + lineIndex,
      'alt' + (lineNumber % 2 == 0 ? 1 : 2).toString()
    ];

    if (this.linesToHighlight[lineNumber])
      classes.push('highlighted');

    if (lineNumber == 0)
      classes.push('break');

    return '<div class="' + classes.join(' ') + '">' + lineHtml + '</div>';
  }
169750
function(code) {
    var lines = [];
    code.split(/\n/).forEach(line => {
      var segs = line.split(/(\s*#)/);
      var ln = {code: segs[0]};
      if (segs.length > 1)
        ln.comment = segs.reduce((c, seg, i) => i > 1 ? c + seg : seg, '');
      lines.push(ln);
    });
    return lines;
  }
194483
function toggleCodeBlock(editor) {
	var fenceCharsToInsert = editor.options.blockStyles.code;

	function fencing_line(line) {
		/* return true, if this is a ``` or ~~~ line */
		if(typeof line !== "object") {
			throw "fencing_line() takes a 'line' object (not a line number, or line text).  Got: " + typeof line + ": " + line;
		}
		return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
	}

	function token_state(token) {
		// base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
		return token.state.base.base || token.state.base;
	}

	function code_type(cm, line_num, line, firstTok, lastTok) {
		/*
		 * Return "single", "indented", "fenced" or false
		 *
		 * cm and line_num are required.  Others are optional for efficiency
		 *   To check in the middle of a line, pass in firstTok yourself.
		 */
		line = line || cm.getLineHandle(line_num);
		firstTok = firstTok || cm.getTokenAt({
			line: line_num,
			ch: 1
		});
		lastTok = lastTok || (!!line.text && cm.getTokenAt({
			line: line_num,
			ch: line.text.length - 1
		}));
		var types = firstTok.type ? firstTok.type.split(" ") : [];
		if(lastTok && token_state(lastTok).indentedCode) {
			// have to check last char, since first chars of first line aren"t marked as indented
			return "indented";
		} else if(types.indexOf("comment") === -1) {
			// has to be after "indented" check, since first chars of first indented line aren"t marked as such
			return false;
		} else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
			return "fenced";
		} else {
			return "single";
		}
	}

	function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
		var start_line_sel = cur_start.line + 1,
			end_line_sel = cur_end.line + 1,
			sel_multi = cur_start.line !== cur_end.line,
			repl_start = fenceCharsToInsert + "\n",
			repl_end = "\n" + fenceCharsToInsert;
		if(sel_multi) {
			end_line_sel++;
		}
		// handle last char including \n or not
		if(sel_multi && cur_end.ch === 0) {
			repl_end = fenceCharsToInsert + "\n";
			end_line_sel--;
		}
		_replaceSelection(cm, false, [repl_start, repl_end]);
		cm.setSelection({
			line: start_line_sel,
			ch: 0
		}, {
			line: end_line_sel,
			ch: 0
		});
	}

	var cm = editor.codemirror,
		cur_start = cm.getCursor("start"),
		cur_end = cm.getCursor("end"),
		tok = cm.getTokenAt({
			line: cur_start.line,
			ch: cur_start.ch || 1
		}), // avoid ch 0 which is a cursor pos but not token
		line = cm.getLineHandle(cur_start.line),
		is_code = code_type(cm, cur_start.line, line, tok);
	var block_start, block_end, lineCount;

	if(is_code === "single") {
		// similar to some SimpleMDE _toggleBlock logic
		var start = line.text.slice(0, cur_start.ch).replace("`", ""),
			end = line.text.slice(cur_start.ch).replace("`", "");
		cm.replaceRange(start + end, {
			line: cur_start.line,
			ch: 0
		}, {
			line: cur_start.line,
			ch: 99999999999999
		});
		cur_start.ch--;
		if(cur_start !== cur_end) {
			cur_end.ch--;
		}
		cm.setSelection(cur_start, cur_end);
		cm.focus();
	} else if(is_code === "fenced") {
		if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
			// use selection

			// find the fenced line so we know what type it is (tilde, backticks, number of them)
			for(block_start = cur_start.line; block_start >= 0; block_start--) {
				line = cm.getLineHandle(block_start);
				if(fencing_line(line)) {
					break;
				}
			}
			var fencedTok = cm.getTokenAt({
				line: block_start,
				ch: 1
			});
			var fence_chars = token_state(fencedTok).fencedChars;
			var start_text, start_line;
			var end_text, end_line;
			// check for selection going up against fenced lines, in which case we don't want to add more fencing
			if(fencing_line(cm.getLineHandle(cur_start.line))) {
				start_text = "";
				start_line = cur_start.line;
			} else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
				start_text = "";
				start_line = cur_start.line - 1;
			} else {
				start_text = fence_chars + "\n";
				start_line = cur_start.line;
			}
			if(fencing_line(cm.getLineHandle(cur_end.line))) {
				end_text = "";
				end_line = cur_end.line;
				if(cur_end.ch === 0) {
					end_line += 1;
				}
			} else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
				end_text = "";
				end_line = cur_end.line + 1;
			} else {
				end_text = fence_chars + "\n";
				end_line = cur_end.line + 1;
			}
			if(cur_end.ch === 0) {
				// full last line selected, putting cursor at beginning of next
				end_line -= 1;
			}
			cm.operation(function() {
				// end line first, so that line numbers don't change
				cm.replaceRange(end_text, {
					line: end_line,
					ch: 0
				}, {
					line: end_line + (end_text ? 0 : 1),
					ch: 0
				});
				cm.replaceRange(start_text, {
					line: start_line,
					ch: 0
				}, {
					line: start_line + (start_text ? 0 : 1),
					ch: 0
				});
			});
			cm.setSelection({
				line: start_line + (start_text ? 1 : 0),
				ch: 0
			}, {
				line: end_line + (start_text ? 1 : -1),
				ch: 0
			});
			cm.focus();
		} else {
			// no selection, search for ends of this fenced block
			var search_from = cur_start.line;
			if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
				if(code_type(cm, cur_start.line + 1) === "fenced") {
					block_start = cur_start.line;
					search_from = cur_start.line + 1; // for searching for "end"
				} else {
					block_end = cur_start.line;
					search_from = cur_start.line - 1; // for searching for "start"
				}
			}
			if(block_start === undefined) {
				for(block_start = search_from; block_start >= 0; block_start--) {
					line = cm.getLineHandle(block_start);
					if(fencing_line(line)) {
						break;
					}
				}
			}
			if(block_end === undefined) {
				lineCount = cm.lineCount();
				for(block_end = search_from; block_end < lineCount; block_end++) {
					line = cm.getLineHandle(block_end);
					if(fencing_line(line)) {
						break;
					}
				}
			}
			cm.operation(function() {
				cm.replaceRange("", {
					line: block_start,
					ch: 0
				}, {
					line: block_start + 1,
					ch: 0
				});
				cm.replaceRange("", {
					line: block_end - 1,
					ch: 0
				}, {
					line: block_end,
					ch: 0
				});
			});
			cm.focus();
		}
	} else if(is_code === "indented") {
		if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
			// use selection
			block_start = cur_start.line;
			block_end = cur_end.line;
			if(cur_end.ch === 0) {
				block_end--;
			}
		} else {
			// no selection, search for ends of this indented block
			for(block_start = cur_start.line; block_start >= 0; block_start--) {
				line = cm.getLineHandle(block_start);
				if(line.text.match(/^\s*$/)) {
					// empty or all whitespace - keep going
					continue;
				} else {
					if(code_type(cm, block_start, line) !== "indented") {
						block_start += 1;
						break;
					}
				}
			}
			lineCount = cm.lineCount();
			for(block_end = cur_start.line; block_end < lineCount; block_end++) {
				line = cm.getLineHandle(block_end);
				if(line.text.match(/^\s*$/)) {
					// empty or all whitespace - keep going
					continue;
				} else {
					if(code_type(cm, block_end, line) !== "indented") {
						block_end -= 1;
						break;
					}
				}
			}
		}
		// if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
		// insert a blank line so that the next line(s) continue to be indented code
		var next_line = cm.getLineHandle(block_end + 1),
			next_line_last_tok = next_line && cm.getTokenAt({
				line: block_end + 1,
				ch: next_line.text.length - 1
			}),
			next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
		if(next_line_indented) {
			cm.replaceRange("\n", {
				line: block_end + 1,
				ch: 0
			});
		}

		for(var i = block_start; i <= block_end; i++) {
			cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
		}
		cm.focus();
	} else {
		// insert code formatting
		var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
		var sel_multi = cur_start.line !== cur_end.line;
		if(no_sel_and_starting_of_line || sel_multi) {
			insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
		} else {
			_replaceSelection(cm, false, ["`", "`"]);
		}
	}
}
969072
function(html, lineNumbers)
        {
            html = trim(html);

            var lines = splitLines(html),
                padLength = this.getParam('pad-line-numbers'),
                firstLine = parseInt(this.getParam('first-line')),
                html = '',
                brushName = this.getParam('brush')
                ;

            for (var i = 0; i < lines.length; i++)
            {
                var line = lines[i],
                    indent = /^(&nbsp;|\s)+/.exec(line),
                    spaces = null,
                    lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i;
                ;

                if (indent != null)
                {
                    spaces = indent[0].toString();
                    line = line.substr(spaces.length);
                    spaces = spaces.replace(' ', sh.config.space);
                }

                line = trim(line);

                if (line.length == 0)
                    line = sh.config.space;

                html += this.getLineHtml(
                    i,
                    lineNumber,
                    (spaces != null ? '<code class="' + brushName + ' spaces">' + spaces + '</code>' : '') + line
                );
            }

            return html;
        }
1173125
function (element) {
		var codeStyles = getStyles(element);
		var whiteSpace = codeStyles['white-space'];

		if (whiteSpace === 'pre-wrap' || whiteSpace === 'pre-line') {
			var codeElement = element.querySelector('code');
			var lineNumbersWrapper = element.querySelector('.line-numbers-rows');
			var lineNumberSizer = element.querySelector('.line-numbers-sizer');
			var codeLines = element.textContent.split('\n');

			if (!lineNumberSizer) {
				lineNumberSizer = document.createElement('span');
				lineNumberSizer.className = 'line-numbers-sizer';

				codeElement.appendChild(lineNumberSizer);
			}

			lineNumberSizer.style.display = 'block';

			codeLines.forEach(function (line, lineNumber) {
				lineNumberSizer.textContent = line || '\n';
				var lineSize = lineNumberSizer.getBoundingClientRect().height;
				lineNumbersWrapper.children[lineNumber].style.height = lineSize + 'px';
			});

			lineNumberSizer.textContent = '';
			lineNumberSizer.style.display = 'none';
		}
	}
162970
String showScriptContextHTML( String s, int lineNo, int context )
    {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader( new StringReader(s) );

        int beginLine = Math.max( 1, lineNo-context );
        int endLine = lineNo + context;
        for( int i=1; i<=lineNo+context+1; i++ )
        {
            if ( i < beginLine )
            {
                try {
                    br.readLine();
                } catch ( IOException e ) {
                    throw new RuntimeException( e.toString() );
                }
                continue;
            }
            if ( i > endLine )
                break;

            String line;
            try {
                line = br.readLine();
            } catch ( IOException e ) {
                throw new RuntimeException( e.toString() );
            }

            if ( line == null )
                break;
            if ( i == lineNo )
                sb.append( "<font color=\"red\">"+i+": "+line +"</font><br/>" );
            else
                sb.append( i+": " +line +"<br/>" );
        }

        return sb.toString();
    }
855664
function highlight (code, lang) {
  if (!lang) {
    return code
  }

  var isDiff = DIFF_REGEXP.test(lang)

  // Remove the diff suffix. E.g. "javascript.diff".
  lang = lang.replace(DIFF_REGEXP, '')

  // Ignore unknown languages.
  if (!isDiff && !supported(lang)) {
    return code
  }

  return isDiff ? diff(code, lang) : hljs.highlight(lang, code).value
}
892600
def highlight(code, lexer='html', formatter='html', output_wrapper=None):
    """"""
    if not pygments:
        raise TypeError("pygments module required")
    if not isinstance(code, six.string_types):
        code = pprint.pformat(code)
    if isinstance(lexer, six.string_types):
        lexer = pygments.lexers.get_lexer_by_name(lexer)
    if isinstance(formatter, six.string_types):
        formatter = pygments.formatters.get_formatter_by_name(formatter)
        if formatter.name.lower() == 'html':
            formatter.full = True
            formatter.cssclass = "pygments-%s" % uuid.uuid4()
            if output_wrapper is None:
                output_wrapper = HTML
    return output_wrapper(pygments.highlight(code, lexer, formatter))
820798
function highlight(text, lang, options){

    function makeSafe(str){
      return str
        .replace(/\r\n|\n\r|\r/g, '\n')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;');
    }

    function normalize(text){
      text = text
        // cut first empty lines
        .replace(/^(?:\s*[\n]+)+?([ \t]*)/, '$1')
        .trimRight();

      // fix empty strings
      text = text.replace(/\n[ \t]+\n/g, '\n\n');

      // normalize text offset
      var minOffset = 1000;
      var lines = text.split(/\n+/);
      var startLine = Number(text.match(/^function/) != null); // fix for function.toString()

      for (var i = startLine; i < lines.length; i++)
      {
        var m = lines[i].match(/^\s*/);
        if (m[0].length < minOffset)
          minOffset = m[0].length;
        if (minOffset == 0)
          break;
      }

      if (minOffset > 0)
        text = text.replace(new RegExp('(^|\\n) {' + minOffset + '}', 'g'), '$1');

      return text;
    }

    function defaultWrapper(line, idx){
      return (
        '<div class="line ' + (idx % 2 ? 'odd' : 'even') + lineClass + '">' +
          '<span class="lineContent">' +
            (!options.noLineNumber
              ? '<input class="lineNumber" value="' + lead(idx + 1, numberWidth) + '" type="none" unselectable="on" readonly="readonly" tabindex="-1" />' +
                '<span class="over"></span>'
              : ''
            ) +
            line + '\r\n' +
          '</span>' +
        '</div>'
      );
    }

    //  MAIN PART

    if (!options)
      options = {};

    // prepare text
    var rangeStart = -1;
    var rangeEnd = -1;
    var rangeName = '';

    if (options.range)
    {
      var left = makeSafe(text.substr(0, options.range[0]));
      var range = makeSafe(text.substring(options.range[0], options.range[1]));
      var right = makeSafe(text.substr(options.range[1]));

      rangeStart = left.length;
      rangeEnd = rangeStart + range.length;
      rangeName = options.range[2] || 'range';

      text = left + range + right;
    }
    else
    {
      text = makeSafe(text);
    }

    if (!options.keepFormat)
      text = normalize(text || '');

    var parser = LANG_PARSER[lang] || LANG_PARSER.text;
    var html = parser(text, rangeStart, rangeEnd, rangeName);

    var lines = html.split('\n');
    var numberWidth = String(lines.length).length;
    var lineClass = (options.noLineNumber ? '' : ' hasLineNumber');
    var offsetRx = new RegExp('^(<span class="' + rangeName + '">)?([ \\t]+)');

    lines = lines
      .map(function(line){
        return line.replace(offsetRx, function(m, rangeSpan, spaces){
          return (rangeSpan || '') + repeat('\xA0', spaces.replace(/\t/g, '  ').length);
        });
      })
      .map(options.wrapper || defaultWrapper);

    return options.lines ? lines : lines.join('');
  }
1358224
function (code, options) {
    options = options || 0
    var defaults = this.options
    var tabWidth = options.tabWidth || defaults.tabWidth
    var space = options.space || defaults.space
    var defaultTag = options.defaultTag || defaults.defaultTag
    var cache = options.cache || ltl.cache
    if (space) {
      space = ltl.escapeBlock(space)
    }

    // Replace carriage returns for Windows compatibility.
    code = code.replace(/\r/g, '')

    // Be lenient with mixed tabs and spaces.
    var tabReplacement = Array(tabWidth + 1).join(' ')
    code = code.replace(/\t/g, tabReplacement)

    // We'll auto-detect tab width.
    var currentTabWidth = 0

    // Initialize the code, and start at level zero with no nesting.
    var lines = code.split('\n')
    var lineIndex
    var lineCount = lines.length

    var newLine = space ? '\n' : ''

    var globalSpaces = 0
    var indent = 0
    var stack = []
    var mode = 'html'
    var previousTag
    var hasHtmlOutput = false
    var hasContent = false
    var useCache = false
    var tagDepth = 0

    var output = "var output='"

    var varIndex = 0
    var escapeHtmlVar = false
    var encodeUriVar = false
    var escapeCommentVar = false
    var loopVars = []

    // If we end up in a dot block, remember the starting indent and filter, and gather lines.
    var blockIndent = 0
    var blockFilter = ''
    var blockLines = null
    var blockTag = null
    var blockName = ''
    var blockContent = ''
    var blockScope = null
    var inComment = false

    // Support adding properties like "js" to the template function.
    var properties = {}
    var blockProperty
    var blockTarget

    function appendText (textMode, text) {
      if (textMode !== mode) {
        if (mode === 'html') {
          output += "'" + (text === '}' ? '' : ';' + newLine)
        } else {
          output += "output+='"
        }
        mode = textMode
      }
      if (mode === 'html') {
        text = interpolate(text)
      }
      output += text
    }

    function startBlock (filter, content) {
      blockIndent = indent + 1
      blockFilter = filter
      blockLines = []
      if (content) {
        blockLines = blockLines || []
        blockLines.push(content)
      }
    }

    function appendBlock () {
      var text = blockLines.join('\n')

      // Reset the blockage.
      blockIndent = 0

      // Some options should be passed through.
      var blockOptions = {
        space: space,
        enableDebug: options.enableDebug
      }

      // If we're in a "call" block, call another template with compiled parts.
      if (blockFilter === 'call') {
        if (/\S/.test(text)) {
          blockScope = blockScope || []
          var blockJs = ltl.compile(text, blockOptions).toString()
          blockJs = blockJs.replace(/^.*?\)/, 'function()')
          blockScope.push('block:' + blockJs)
        }
        blockScope = blockScope ? blockScope.join(',') : ''
        appendText('html', "'+cache['" + blockName + "']({" + blockScope + "},state)+'")
        useCache = true
        blockScope = null
        return

      // If there's a filter, get its module.
      } else if (blockFilter) {
        if (blockFilter === 'coffee') {
          blockFilter = 'coffee-script'
        } else if (blockFilter === 'md') {
          blockFilter = 'marked'
        }
        var compiler = ltl.getFilter(blockFilter)

        if (compiler.renderSync) {
          text = compiler.renderSync(text, {
            data: text,
            compressed: true
          })
        } else if (compiler.render) {
          if (blockFilter === 'less') {
            compiler.render(text, function (err, result) {
              if (err) {
                throw err
              }
              text = result.css
            })
          } else {
            text = compiler.render(text)
          }
        } else if (compiler.compile) {
          var nowrap = /^[^A-Z]*NOWRAP/.test(text)
          text = compiler.compile(text)
          if (nowrap) {
            text = text.replace(/(^\(function\(\) \{\s*|\s*\}\)\.call\(this\);\s*$)/g, '')
          }
        } else if (compiler.parse) {
          text = compiler.parse(text)
        } else if (typeof compiler === 'function') {
          text = compiler(text)
        }
      } else {
        blockFilter = 'text'
      }

      text = ltl.trim(text)
      if (space) {
        if (hasHtmlOutput) {
          text = '\n' + text
        }
        text = text.replace(/\n/g, '\n' + ltl.repeat(space, tagDepth))
        if (blockTag) {
          text += '\n' + ltl.repeat(space, tagDepth - 1)
        }
      }

      if (blockProperty) {
        var value = properties[blockProperty]
        value = (value ? value + '\n' : '') + text
        properties[blockProperty] = value
      } else if (blockTarget === 'js') {
        text = text.replace(/;?$/, ';')
        appendText('script', text)
      } else {
        appendText('html', ltl.escapeBlock(text))
      }

      blockTag = null
      blockFilter = null
      blockProperty = null
      blockTarget = null
      blockScope = null
    }

    function backtrackIndent () {
      while (stack.length > indent) {
        var tags = stack.pop()
        if (tags) {
          tags = tags.split(/,/g)
          for (var i = tags.length - 1; i >= 0; i--) {
            var tag = tags[i]
            if (tag === '//') {
              inComment = false
            } else if (tag === '-') {
              appendText('html', '-->')
            } else if (ltl.controlPattern.test(tag)) {
              appendText('script', '}')
              if (tag === 'for') {
                loopVars.pop()
              }
            } else if (!ltl.selfClosePattern.test(tag)) {
              var html = '</' + tag + '>'
              tagDepth--
              if (tag === previousTag) {
                previousTag = null
              } else if (space) {
                html = '\\n' + ltl.repeat(space, tagDepth) + html
              }
              appendText('html', html)
            }
          }
        }
      }
    }

    function transformScript (script) {
      var found = false

      script = script.replace(/^for\s+([$A-Za-z_][$A-Za-z_\d]*)\s+in\s+([$A-Za-z_][$A-Za-z_\d\.]*)\s*$/,
        function (match, item, array) {
          found = true
          var i = 'ltl' + varIndex++
          var l = 'ltl' + varIndex++
          var e = 'ltl' + varIndex++
          loopVars.push([[item, e]])
          return 'for(var ' + e + ',' + i + '=0,' + l + '=scope.' + array + '.length;' +
            i + '<' + l + ';++' + i + ')' + '{' + newLine +
            e + '=scope.' + array + '[' + i + ']' + ';' + newLine
        })

      if (found) {
        stack.push('for')
        return script
      }

      script = script.replace(/^for\s+([$A-Za-z_][$A-Za-z_\d]*)\s*,\s*([$A-Za-z_][$A-Za-z_\d]*)\s+of\s+([$A-Za-z_][$A-Za-z_\d\.]*)\s*$/,
        function (match, key, value, object) {
          found = true
          var k = 'ltl' + varIndex++
          var v = 'ltl' + varIndex++
          loopVars.push([[key, k], [value, v]])
          return 'for(var ' + k + ' in scope.' + object + '){' + newLine +
            'if(!scope.' + object + '.hasOwnProperty(' + k + '))continue;' + newLine +
            v + '=scope.' + object + '[' + k + ']' + ';' + newLine
        })

      if (found) {
        stack.push('for')
        return script
      }

      script = script.replace(/^(else if|else|if)\s*(.*)\s*$/i,
        function (match, keyword, condition) {
          found = true
          return keyword + (condition ? '(' + scopify(condition) + ')' : '') + '{' + newLine
        })

      if (found) {
        stack.push('if')
        return script
      }

      /*
      script = script.replace(/^(break|continue)(\s+.*)$/i,
        function (match, keyword, condition) {
          found = true
          return keyword + (condition ? '(' + scopify(condition) + ')' : '') + '{' + newLine
        })
      */
    }

    /**
     * Give scope to a JavaScript expression by prepending the scope variable "scope".
     * TODO: Parse using acorn so that strings can't be interpreted as vars.
     */
    function scopify (code, unescapeSingleQuotes) {
      // Interpolations got escaped as HTML and must be unescaped to be JS.
      if (unescapeSingleQuotes) {
        code = code.replace(/\\'/g, "'")
      }
      var tokens = code.split(/\b/)
      var isProperty = false
      var isLoopVar = false
      var isInString = false
      for (var i = 0; i < tokens.length; i++) {
        var token = tokens[i]
        var stringTokens = token.match(/['"]/g)
        if (stringTokens) {
          isInString = ((isInString ? 1 : 0) + stringTokens.length) % 2
        } else if (!isInString) {
          if (/^[a-z_]/i.test(token)) {
            if (!ltl.jsPattern.test(token)) {
              for (var j = 0; j < loopVars.length; j++) {
                for (var k = 0; k < loopVars[j].length; k++) {
                  if (token === loopVars[j][k][0]) {
                    isLoopVar = true
                    tokens[i] = loopVars[j][k][1]
                  }
                }
              }
              if (!isProperty && !isLoopVar) {
                tokens[i] = 'scope.' + token
              }
            }
          }
          isProperty = token[token.length - 1] === '.'
          isLoopVar = false
        }
      }
      code = tokens.join('')
      return code
    }

    /**
     * Find ={...}, ${...} and &{...} interpolations.
     * Turn them into scope-aware insertions unless escaped.
     */
    function interpolate (code) {
      return code.replace(/(\\?)([$=&])\{([^\}]+)\}/g, function (match, backslash, symbol, expression) {
        if (backslash) {
          return symbol + '{' + expression + '}'
        }
        if (expression === 'block') {
          expression = 'scope.block.call(cache,scope)'
          useCache = true
        } else {
          expression = scopify(expression, true)
        }
        if (symbol === '$') {
          if (!escapeHtmlVar) {
            escapeHtmlVar = 'ltl' + varIndex++
          }
          return "'+" + escapeHtmlVar + '(' + expression + ")+'"
        } else if (symbol === '&') {
          if (!encodeUriVar) {
            encodeUriVar = 'ltl' + varIndex++
          }
          return "'+" + encodeUriVar + '(' + expression + ")+'"
        } else {
          return "'+(" + expression + ")+'"
        }
      })
    }

    // Iterate over each line.
    for (lineIndex = 0; lineIndex < lineCount; lineIndex++) {
      var line = lines[lineIndex]

      // Mitigate recursion past 100 deep.
      var maxT = 1e2

      // If the line is all whitespace, ignore it.
      if (!/\S/.test(line)) {
        if (blockIndent) {
          (blockLines = blockLines || []).push('')
        }
        continue
      }

      // Find the number of leading spaces.
      var spaces = line.search(/[^ ]/)

      // If the first line with content has leading spaces, assume they all do.
      if (!hasContent) {
        globalSpaces = spaces
        hasContent = true
      }

      var adjustedSpaces = Math.max(spaces - globalSpaces, 0)

      // If this is our first time seeing leading spaces, that's our tab width.
      if (adjustedSpaces > 0 && !currentTabWidth) {
        currentTabWidth = adjustedSpaces
      }

      // Calculate the number of levels of indentation.
      indent = adjustedSpaces ? Math.round(adjustedSpaces / currentTabWidth) : 0

      // If we're in a block, we can append or close it.
      if (blockIndent) {
        // If we've gone back to where the block started, close the block.
        if (indent < blockIndent) {
          appendBlock()

        // If we're still in the block, append to the block code.
        } else {
          line = line.substring(Math.min(spaces, currentTabWidth * blockIndent))
          blockLines = blockLines || []
          blockLines.push(line)
          continue
        }
      }

      // Strip the leading spaces.
      line = line.substring(spaces)

      // Backtrack, closing any nested tags that need to be closed.
      backtrackIndent()
      if (inComment) {
        continue
      }

      // Control patterns such as if/else/for must transform into true JavaScript.
      if (ltl.controlPattern.test(line)) {
        var script = transformScript(line)
        appendText('script', script)

      // Assignment patterns just need to be stateified.
      } else if (ltl.assignmentPattern.test(line)) {
        line = scopify(line) + ';'
        appendText('script', line)

      // Expression patterns make things append.
      } else if (line[0] === '@') {
        line.replace(/@([^\s\(\[]+)([\(\[][^\)\]]*[\)\]])?(.*)/, function (match, path, attributes, rest) {
          blockName = path
          blockContent = rest
          if (attributes) {
            blockScope = []
            attributes = attributes.substr(1, attributes.length - 2)
            attributes.replace(/([^\s]+?)(=(['"])?[^'"]*?\3)?(\s|$)/g, function (match, name, value, space) {
              blockScope.push(name + ':' + (value ? scopify(value.substr(1)) : true))
            })
          }
          startBlock('call', blockContent)
        })

      // Tags must be parsed for id/class/attributes/content.
      } else {
        var rest = line
        var t = 0

        // Process the rest of the line recursively.
        while (rest && (++t < maxT)) {
          var tag = ''
          var id = ''
          var classes = []
          var attributes = ''
          var character = ''
          var end = 0
          var content = ''

          // Process the rest of the line recursively.
          while (rest && (++t < maxT)) {
            character = rest[0]

            // If it's an ID, read up to the next thing, and save the ID.
            if (character === '#') {
              end = rest.search(/([\.\(>:\s]|$)/)
              id = id || rest.substring(1, end)
              rest = rest.substring(end)

            // If it's a class, read up to the next thing, and save the class.
            } else if (character === '.') {
              end = rest.search(/([@#\(>:\s]|$)/)
              classes.push(rest.substring(1, end).replace(/\./g, ' '))
              rest = rest.substring(end)

            // If it's the beginning of a list of attributes, iterate through them.
            } else if (character === '(' || character === '[') {
              // Move on from the parentheses.
              rest = rest.substring(1)

              // Build attributes.
              attributes = ''
              while (rest && (++t < maxT)) {
                // Find quoted attributes or the end of the list.
                end = rest.search(/[\)\]"']/)

                // If there's no end, read what's left as attributes.
                if (end < 0) {
                  attributes += rest
                  rest = ''
                  break
                }
                character = rest[end]

                // If it's the end, get any remaining attribute and get out.
                if (character === ')' || character === ']') {
                  attributes += rest.substring(0, end)
                  rest = rest.substring(end + 1)
                  break

                // If it's not the end, read a quoted param.
                } else {
                  // Allow for attributes to be comma separated or not.
                  // Also allow for valueless attributes.
                  attributes += rest.substring(0, end).replace(/[,\s]+/g, ' ')
                  rest = rest.substring(end)

                  // Find the next end quote.
                  // TODO: Deal with backslash-delimited quotes.
                  end = rest.indexOf(character, 1)

                  // Read to the end of the attribute.
                  attributes += rest.substring(0, end + 1)
                  rest = rest.substring(end + 1)
                }
              }

            // If the next character is a greater than symbol, break for inline nesting.
            } else if (character === '>') {
              rest = rest.replace(/^>\s*/, '')
              break

            // If the next character is a colon, enter a filter block.
            } else if (character === ':') {
              blockTag = tag
              rest = rest.substring(1).split(' ')
              startBlock(rest.shift(), rest.join(' '))
              rest = ''
              break

            // If the next character is a plus, store it as a property.
            } else if (character === '+') {
              rest.replace(/^\+([^:\s]+):?(\S*)\s?(.*)$/, function (match, name, filter, content) {
                var target = ltl.languages[name] || name
                blockProperty = target
                blockTag = ''
                filter = (name === target ? '' : name) || filter
                startBlock(filter, content)
              })
              rest = ''
              break

            // If the next character is a space, it's the start of content.
            } else if (character === ' ') {
              content = ltl.trim(rest)
              rest = ''

            // If the next character isn't special, it's part of a tag.
            } else {
              end = rest.search(/([#\.\(>:\s@]|$)/)
              // Prevent overwriting the tag.
              tag = tag || rest.substring(0, end)
              rest = rest.substring(end)
            }
          }

          // If it's a JS/CSS language, start an inline block.
          if (ltl.languages[tag]) {
            blockTarget = ltl.languages[tag]
            var filter = (tag === blockTarget ? '' : tag) || filter
            tag = blockTag = blockTarget === 'css' ? 'style' : '//'
            startBlock(filter, content)
          }

          // If it's a comment, set a boolean so we can ignore its contents.
          if (tag.indexOf('//') === 0) {
            tag = '//'
            inComment = true

          // If it's not a comment, we'll add some HTML.
          } else {
            var className = classes.join(' ')

            // Default to a <div> unless we're in a tagless block.
            if (!tag) {
              var useDefault = (blockTag === null) || id || className || attributes
              if (useDefault) {
                tag = blockTag = defaultTag
              }
            }

            // Convert ! or doctype into !DOCTYPE and assume html.
            if (tag === '!' || tag === 'doctype') {
              tag = '!DOCTYPE'
              attributes = attributes || 'html'
            }

            // Add attributes to the tag.
            var html = tag
            if (id) {
              html += ' id="' + id + '"'
            }
            if (className) {
              html += ' class="' + className + '"'
            }
            if (attributes) {
              html += ' ' + attributes
            }

            // Convert space tag to a space character.
            if (tag === 'space') {
              html = ' ' + content

            // Convert minus to a comment.
            } else if (tag === '-') {
              html = '<!--' + content
            } else {
              html = '<' + html + '>' + content
            }

            html = ltl.escapeSingleQuotes(html)
            if (tag === 'html') {
              // If there's an HTML tag, don't wrap with a scope.
              if (!/DOCTYPE/.test(output)) {
                html = '<!DOCTYPE html>' + (space ? '\\n' : '') + html
              }
            }

            // Prepend whitespace if requested via space.
            if (space) {
              html = ltl.repeat(space, tagDepth) + html
              // Prepend a line break if this isn't the first tag.
              if (hasHtmlOutput) {
                html = '\\n' + html
              }
            }

            // Add the HTML to the template function output.
            if (tag) {
              appendText('html', html)
              hasHtmlOutput = true
            }
          }

          if (tag) {
            // Make sure we can close this tag.
            if (stack[indent]) {
              stack[indent] += ',' + tag
            } else {
              stack[indent] = tag
            }

            // Allow same-line tag open/close in space mode.
            previousTag = tag
            if (!ltl.selfClosePattern.test(tag)) {
              tagDepth++
            }
          }

          tag = ''
          id = ''
          classes = []
          attributes = ''
          content = ''
        }
      }
    }

    // We've reached the end, so unindent all the way.
    indent = 0
    if (blockIndent) {
      appendBlock()
    }
    backtrackIndent()

    // Add the return statement (ending concatenation, where applicable).
    appendText('script', 'return output')

    // Create the function.
    if (escapeCommentVar) {
      output = (options.name
        ? 'var ' + escapeCommentVar + "=cache['-'];" + newLine
        : cache['-'].toString().replace(/\(/, escapeCommentVar + '(') + ';' + newLine) + output
      useCache = true
    }
    if (escapeHtmlVar) {
      output = (options.name
        ? 'var ' + escapeHtmlVar + '=cache.$;' + newLine
        : cache.$.toString().replace(/\(/, escapeHtmlVar + '(') + ';' + newLine) + output
      useCache = true
    }
    if (encodeUriVar) {
      output = (options.name
        ? 'var ' + encodeUriVar + "=cache['&'];" + newLine
        : cache['&'].toString().replace(/\(/, encodeUriVar + '(') + ';' + newLine) + output
      useCache = true
    }
    if (useCache) {
      output = 'var cache=this;' + newLine + output
    }

    var index = 0
    output = output.replace(/state=state\|\|scope;\s*var cache=this;\s*/g, function (match) {
      return index++ ? '' : match
    })

    if (/\bstate\b/.test(output)) {
      output = 'function(scope,state){' + newLine +
        'state=state||scope;' + newLine + output + newLine + '}'
    } else {
      output = 'function(scope){' + newLine + output + newLine + '}'
    }

    // Evaluate the template as a function.
    var name = options.name
    var template
    try {
      template = ltl.run(output, name)
    } catch (e) {
      name = (name ? '"' + name + '"' : 'template')
      e.message = '[Ltl] Failed to compile ' + name + '. ' + e.message
      throw e
    }

    // If there's a name specified, cache it and refer to it.
    if (name) {
      cache[name] = template
      template.key = name
      template.cache = cache
    }

    // Add any discovered properties to the template.
    for (name in properties) {
      template[name] = template[name] || properties[name]
    }

    return template
  }
109317
function parseForESLint(code, options) {
    const opts = options || {}
    if (!isHtmlFile(code, opts)) {
        return parseScript(code, opts)
    }
    return parseTemplate(code, opts)
}
859548
function convertCode2Script(code) {
    // clean source code comment
    return code
        .replace(/\/\/\/ <reference path="[\s\S]*?>/gm, '')
        .replace(/\r\n/gm, '\n')
        .replace(convert.mapFileCommentRegex, '')
        .trim('\n') + '\n';
}
263188
function(codePath) {
        let text =
            "\n" +
            "digraph {\n" +
            "node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" +
            "initial[label=\"\",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n";

        if (codePath.returnedSegments.length > 0) {
            text += "final[label=\"\",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n";
        }
        if (codePath.thrownSegments.length > 0) {
            text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize];\n";
        }

        const traceMap = Object.create(null);
        const arrows = this.makeDotArrows(codePath, traceMap);

        for (const id in traceMap) { // eslint-disable-line guard-for-in
            const segment = traceMap[id];

            text += `${id}[`;

            if (segment.reachable) {
                text += "label=\"";
            } else {
                text += "style=\"rounded,dashed,filled\",fillcolor=\"#FF9800\",label=\"<<unreachable>>\\n";
            }

            if (segment.internal.nodes.length > 0 || segment.internal.exitNodes.length > 0) {
                text += [].concat(
                    segment.internal.nodes.map(node => {
                        switch (node.type) {
                            case "Identifier": return `${node.type} (${node.name})`;
                            case "Literal": return `${node.type} (${node.value})`;
                            default: return node.type;
                        }
                    }),
                    segment.internal.exitNodes.map(node => {
                        switch (node.type) {
                            case "Identifier": return `${node.type}:exit (${node.name})`;
                            case "Literal": return `${node.type}:exit (${node.value})`;
                            default: return `${node.type}:exit`;
                        }
                    })
                ).join("\\n");
            } else {
                text += "????";
            }

            text += "\"];\n";
        }

        text += `${arrows}\n`;
        text += "}";
        debug("DOT", text);
    }
1154206
function getPos(lines, lineNum, code, indicator) {

	var line, min, max, dots = false, prefix = 0;
	var pos = {};

	// console.log('code', code);

	// handle special cases
	if (code === '{{{{') {
		pos.min = 0;
		pos.max = 4;
		return pos;
	} else if (code === '{{{') {
		pos.min = 0;
		pos.max = 3;
		return pos;
	} else  if (code === '{{') {
		pos.min = 0;
		pos.max = 2;
		return pos;
	} else if (code.indexOf('{{<') !== -1) {
		pos.min = lines[lineNum].indexOf('{{<');
		pos.max = pos.min + 3;
		return pos;
	} else if (code === '{{}}') {
		pos.min = 0;
		pos.max = 4;
		return pos;
	} else if (code.indexOf('{{{}}{') !== -1) {
		pos.min = lines[lineNum].indexOf('{{{}}}');
		pos.max = pos.min + 6;
		return pos;
	} else if (code.indexOf('{{#}}') !== -1) {
		pos.min = lines[lineNum].indexOf('{{#}}');
		pos.max = pos.min + 5;
		return pos;
	}

	// trim off extra prefix and suffix from code which
	// could force us to not find the pos in the line.
	code = code.substring(0, indicator.length);
	code = code.replace('...', function() {
		dots = true;
		return '';
	});

	prefix = code.indexOf('{{');
	line = lines[lineNum];
	min = line.indexOf(code);
	min = min + prefix;
	max = (!dots)
		? min + indicator.length - 1
		: min + indicator.length - 4;

	// todo: if (min === max) max = findMax(line, min); // find first ' ' or '}'
	if (min === max) max++;

	if (min === -1) {
		return {
			min: 0,
			max: 1
		};
	} else {
		return {
			min: min,
			max: max
		};
	}
}
649771
function nodeToRangeLines(node, code, engine) {
  var range = engine.nodeToRange(node);

  // we want to keep starting indentation, so search back to the previous
  // newline
  var start = range.start;
  while (start > 0 && code[start] !== "\n") {
    start--;
  }
  if (code[start] === "\n") {
    start++; // don't include the newline
  }

  // we also want to read to the end of the line for the node we found
  var end = range.end;
  while (end < code.length && code[end] !== "\n") {
    end++;
  }

  return { start: start, end: end };
}
742147
function undent(code) {
  let lines = code.split("\n");
  let minIndent = Number.MAX_VALUE;

  // find min indent
  lines.forEach(line => {
    let startingSpaceMatch = line.match(/^\s*/);
    let indentLength = startingSpaceMatch[0].length;
    if (indentLength < minIndent) {
      minIndent = indentLength;
    }
  });

  // remove the indentation from each line
  return lines
    .map(line => {
      return line.substring(minIndent);
    })
    .join("\n");
}
295137
function mdAstToHtml(ast, lines) {
    if (lines == undefined)
        lines = [];

    // Adds each element of the array as markdown 
    function addArray(ast) {
        for (let child of ast)
            mdAstToHtml(child, lines);
        return lines;
    }

    // Adds tagged content 
    function addTag(tag, ast, newLine) {
        lines.push(startTag(tag));
        if (ast instanceof Array)
            addArray(ast); 
        else
            mdAstToHtml(ast, lines);
        lines.push(endTag(tag));
        if (newLine)
            lines.push('\r\n');
        return lines;
    }

    function addLink(url, astOrText) {
        lines.push(startTag('a', { href:url }));
        if (astOrText) {
            if (astOrText.children)
                addArray(astOrText.children);
            else
               lines.push(astOrText);
        }        
        
        lines.push(endTag('a')) ;
        return lines;
    }

    function addImg(url) {
        lines.push(startTag('img', { src:url }));
        lines.push(endTag('img')) ;
        return lines;
    }

    switch (ast.name)
    {
        case "heading": 
            {
                let headingLevel = ast.children[0];
                let restOfLine = ast.children[1];
                let h = headingLevel.allText.length;
                switch (h)
                {
                    case 1: return addTag("h1", restOfLine, true); 
                    case 2: return addTag("h2", restOfLine, true); 
                    case 3: return addTag("h3", restOfLine, true); 
                    case 4: return addTag("h4", restOfLine, true); 
                    case 5: return addTag("h5", restOfLine, true); 
                    case 6: return addTag("h6", restOfLine, true); 
                    default: throw "Heading level must be from 1 to 6"
                }
            }
        case "paragraph":   
            return addTag("p", ast.children, true);
        case "unorderedList":
            return addTag("ul", ast.children, true);
        case "orderedList":
            return addTag("ol", ast.children, true);
        case "unorderedListItem":
            return addTag("li", ast.children, true);
        case "orderedListItem":
            return addTag("li", ast.children, true);
        case "inlineUrl":
            return addLink(ast.allText, ast.allText);
        case "bold":
            return addTag("b", ast.children);
        case "italic":
            return addTag("i", ast.children);
        case "code":
            return addTag("code", ast.children);
        case "codeBlock":
            return addTag("pre", ast.children);
        case "quote":
            return addTag("blockquote", ast.children, true);
        case "link":
            return addLink(ast.children[1].allText, ast.children[0]);
        case "image":
            return addImg(ast.children[0]);
        default:
            if (ast.isLeaf)
                lines.push(ast.allText);
            else 
                ast.children.forEach(function(c) { mdAstToHtml(c, lines); });
    }
    return lines;
}