/*
Show context number lines of string before and after target line.
Add HTML formatting to bold the target line.
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();
    }
1131905
def text_after(self, start, match_on):
        """"""
        text = ""
        index = start - 1
        while index > 0:
            text = self.code[index:start]
            if text.startswith(match_on):
                return text.lstrip(match_on)
            index -= 1

        return text.lstrip(match_on)
1043691
def _context_string(context):
    """"""
    msg = 'Code block context:\n            '
    lines = ['Selective arithmetic coding bypass:  {0}',
             'Reset context probabilities on coding pass boundaries:  {1}',
             'Termination on each coding pass:  {2}',
             'Vertically stripe causal context:  {3}',
             'Predictable termination:  {4}',
             'Segmentation symbols:  {5}']
    msg += '\n            '.join(lines)
    msg = msg.format(((context & 0x01) > 0),
                     ((context & 0x02) > 0),
                     ((context & 0x04) > 0),
                     ((context & 0x08) > 0),
                     ((context & 0x10) > 0),
                     ((context & 0x20) > 0))
    return msg
592273
def preformatted_text(source: str) -> str:
    """"""
    environ.abort_thread()

    if not source:
        return ''

    source = render_utils.html_escape(source)

    return '<pre class="preformatted-textbox">{text}</pre>'.format(
        text=str(textwrap.dedent(source))
    )
684458
function lineTop (){
    var l = line(chars.top
               , chars['top-left'] || chars.top
               , chars['top-right'] ||  chars.top
               , chars['top-mid']);
    if (l)
      ret += l + "\n";
  }
1287812
function(context, font, stroke) {
        context.font = font.font;
        context.fillStyle = font.fillStyle.toRGBA();
        if (stroke === true) {
            context.strokeStyle = font.strokeStyle.toRGBA();
            context.lineWidth = font.lineWidth;
        }
        context.textAlign = font.textAlign;
        context.textBaseline = font.textBaseline;
    }
384375
def highlightBlock(self, text):
        
        text = nativestring(text)
        for pattern, format in self.patterns():
            for result in re.finditer(pattern, text):
                grps = result.groups()
                if grps:
                    for i in range(len(grps)):
                        start, end = result.span(i+1)
                        self.setFormat(start, end - start, format)
                else:
                    self.setFormat(result.start(),
                                   result.end() - result.start(),
                                   format)
        
        self.setCurrentBlockState(0)
        if self.previousBlockState() == 1:
            return
        
        for form, open, close in self._multiline:
            open = QtCore.QRegExp(open)
            close = QtCore.QRegExp(close)
            
            start = open.indexIn(text)
            processed = False
            
            while start >= 0:
                processed = True
                end = close.indexIn(text, start)

                if end == -1:
                    self.setCurrentBlockState(1)
                    length = len(text) - start
                else:
                    length = end - start + close.matchedLength()

                self.setFormat(start, length, form)
                start = open.indexIn(text, start + length)
            
            if processed:
                break
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;
        }
555417
function highlight() {
    $('pre code').each(function (i, block) {
      hljs.highlightBlock(block);
    });
    $('pre code[highlight-lines]').each(function (i, block) {
      if (block.innerHTML === "") return;
      var lines = block.innerHTML.split('\n');

      queryString = block.getAttribute('highlight-lines');
      if (!queryString) return;

      var ranges = queryString.split(',');
      for (var j = 0, range; range = ranges[j++];) {
        var found = range.match(/^(\d+)\-(\d+)?$/);
        if (found) {
          // consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional
          var start = +found[1];
          var end = +found[2];
          if (isNaN(end) || end > lines.length) {
            end = lines.length;
          }
        } else {
          // consider region as a sigine line number
          if (isNaN(range)) continue;
          var start = +range;
          var end = start;
        }
        if (start <= 0 || end <= 0 || start > end || start > lines.length) {
          // skip current region if invalid
          continue;
        }
        lines[start - 1] = '<span class="line-highlight">' + lines[start - 1];
        lines[end - 1] = lines[end - 1] + '</span>';
      }

      block.innerHTML = lines.join('\n');
    });
  }
345130
function renderLine(n, line) {
    // Convert tabs to spaces, so errors in code lines with tabs as indention symbol
    // could be correctly rendered, plus it will provide less verbose output
    line = line.replace(/\t/g, ' ');

    // "n + 1" to print lines in human way (counted from 1)
    var lineNumber = prependSpaces((n + 1).toString(), 5) + ' |';
    return ' ' + lineNumber + line;
}
957535
function(value /* String */)
	{
		this.currentLineNb = -1;
		this.currentLine = '';
		this.lines = this.cleanup(value).split("\n");
		
		var data = null;
      var context = null;
      		
		while ( this.moveToNextLine() )
		{
			if ( this.isCurrentLineEmpty() )
			{
				continue;
			}
			
			// tab?
			if ( this.currentLine.charAt(0) == '\t' )
			{
				throw new YamlParseException('A YAML file cannot contain tabs as indentation.', this.getRealCurrentLineNb() + 1, this.currentLine);
			}
			
			var isRef = false;
			var isInPlace = false;
			var isProcessed = false;
			var values = null;
			var matches = null;
			var c = null;
			var parser = null;
			var block = null;
			var key = null;
			var parsed = null;
			var len = null;
			var reverse = null;
			
			if ( values = /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine) )
			{

				if (context && 'mapping' == context) {
					throw new YamlParseException('You cannot define a sequence item when in a mapping', this.getRealCurrentLineNb() + 1, this.currentLine);
				}
				context = 'sequence';

				if ( !this.isDefined(data) ) data = [];
				//if ( !(data instanceof Array) ) throw new YamlParseException("Non array entry", this.getRealCurrentLineNb() + 1, this.currentLine);
				
				values = {leadspaces: values[2], value: values[3]};
				
				if ( this.isDefined(values.value) && ( matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
				{
					matches = {ref: matches[1], value: matches[2]};
					isRef = matches.ref;
					values.value = matches.value;
				}
				
				// array
				if ( !this.isDefined(values.value) || '' == this.trim(values.value) || values.value.replace(/^ +/,'').charAt(0) == '#' )
				{
					c = this.getRealCurrentLineNb() + 1;
					parser = new YamlParser(c);
					parser.refs = this.refs;
					data.push(parser.parse(this.getNextEmbedBlock()));
					this.refs = parser.refs;
				}
				else
				{
					if ( this.isDefined(values.leadspaces) && 
						' ' == values.leadspaces && 
						( matches = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\{\[].*?) *\:(\\s+(.+?))?\\s*$').exec(values.value) ) 
					) {
						matches = {key: matches[1], value: matches[3]};
						// this is a compact notation element, add to next block and parse
						c = this.getRealCurrentLineNb();
						parser = new YamlParser(c);
						parser.refs = this.refs;
						block = values.value;
						
						if ( !this.isNextLineIndented() )
						{
							block += "\n"+this.getNextEmbedBlock(this.getCurrentLineIndentation() + 2);
						}

						data.push(parser.parse(block));
						this.refs = parser.refs;
					}
					else
					{
						data.push(this.parseValue(values.value));
					}
				}
			}
			else if ( values = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\[\{].*?) *\:(\\s+(.+?))?\\s*$').exec(this.currentLine) )
			{
				if ( !this.isDefined(data) ) data = {};
				if (context && 'sequence' == context) {
					throw new YamlParseException('You cannot define a mapping item when in a sequence', this.getRealCurrentLineNb() + 1, this.currentLine);
				}
				context = 'mapping';				
				//if ( data instanceof Array ) throw new YamlParseException("Non mapped entry", this.getRealCurrentLineNb() + 1, this.currentLine);
				
				values = {key: values[1], value: values[3]};
				
				try {
					key = new YamlInline().parseScalar(values.key);
				} catch (e) {
					if ( e instanceof YamlParseException ) {
						e.setParsedLine(this.getRealCurrentLineNb() + 1);
						e.setSnippet(this.currentLine);
					}
					throw e;
				}				
				
				
				if ( '<<' == key )
				{
					if ( this.isDefined(values.value) && '*' == (values.value+'').charAt(0) )
					{
						isInPlace = values.value.substr(1);
						if ( this.refs[isInPlace] == undefined )
						{
							throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
						}
					}
					else
					{
						if ( this.isDefined(values.value) && values.value != '' )
						{
							value = values.value;
						}
						else
						{
							value = this.getNextEmbedBlock();
						}
						
						c = this.getRealCurrentLineNb() + 1;
						parser = new YamlParser(c);
						parser.refs = this.refs;
						parsed = parser.parse(value);
						this.refs = parser.refs;
				
						var merged = [];
						if ( !this.isObject(parsed) )
						{
							throw new YamlParseException("YAML merge keys used with a scalar value instead of an array", this.getRealCurrentLineNb() + 1, this.currentLine);
						}
						else if ( this.isDefined(parsed[0]) )
						{
							// Numeric array, merge individual elements
							reverse = this.reverseArray(parsed);
							len = reverse.length;
							for ( var i = 0; i < len; i++ )
							{
								var parsedItem = reverse[i];
								if ( !this.isObject(reverse[i]) )
								{
									throw new YamlParseException("Merge items must be arrays", this.getRealCurrentLineNb() + 1, this.currentLine);
								}
								merged = this.mergeObject(reverse[i], merged);
							}
						}
						else
						{
							// Associative array, merge
							merged = this.mergeObject(merged, parsed);
						}
				
						isProcessed = merged;
					}
				}
				else if ( this.isDefined(values.value) && (matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
				{
					matches = {ref: matches[1], value: matches[2]};
					isRef = matches.ref;
					values.value = matches.value;
				}
				
				if ( isProcessed )
				{
					// Merge keys
					data = isProcessed;
				}
				// hash
				else if ( !this.isDefined(values.value) || '' == this.trim(values.value) || this.trim(values.value).charAt(0) == '#' )
				{
					// if next line is less indented or equal, then it means that the current value is null
					if ( this.isNextLineIndented() && !this.isNextLineUnIndentedCollection() )
					{
						data[key] = null;
					}
					else
					{
						c = this.getRealCurrentLineNb() + 1;
						parser = new YamlParser(c);
						parser.refs = this.refs;
						data[key] = parser.parse(this.getNextEmbedBlock());
						this.refs = parser.refs;
					}
				}
				else
				{
					if ( isInPlace )
					{
						data = this.refs[isInPlace];
					}
					else
					{
						data[key] = this.parseValue(values.value);
					}
				}
			}
			else
			{
				// 1-liner followed by newline
				if ( 2 == this.lines.length && this.isEmpty(this.lines[1]) )
				{
					try {
						value = new YamlInline().parse(this.lines[0]);
					} catch (e) {
						if ( e instanceof YamlParseException ) {
							e.setParsedLine(this.getRealCurrentLineNb() + 1);
							e.setSnippet(this.currentLine);
						}
						throw e;
					}
					
					if ( this.isObject(value) )
					{
						var first = value[0];
						if ( typeof(value) == 'string' && '*' == first.charAt(0) )
						{
							data = [];
							len = value.length;
							for ( var i = 0; i < len; i++ )
							{
								data.push(this.refs[value[i].substr(1)]);
							}
							value = data;
						}
					}
				
					return value;
				}
				
				throw new YamlParseException('Unable to parse.', this.getRealCurrentLineNb() + 1, this.currentLine);
			}
		
			if ( isRef )
			{
				if ( data instanceof Array )
					this.refs[isRef] = data[data.length-1];
				else
				{
					var lastKey = null;
					for ( var k in data )
					{
						if ( data.hasOwnProperty(k) ) lastKey = k;
					}
					this.refs[isRef] = data[k];
				}
			}
		}
		
		return this.isEmpty(data) ? null : data;
	}
882557
function(html, lineNumbers)
  {
    // html = utils.trim(html);

    var _this = this,
        opts = _this.opts,
        lines = getLines(html),
        padLength = opts.padLineNumbers,
        firstLine = parseInt(opts.firstLine || 1),
        brushName = opts.brush,
        html = ''
        ;

    for (var i = 0, l = lines.length; i < l; 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(' ', opts.space);
      }

      // line = utils.trim(line);

      if (line.length == 0)
        line = opts.space;

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

    return html;
  }
647305
def get_context(self, line=1, column=0):
        ''

        line -= 1  # The line is one-based

        # If there is no data in the file, there can be no context.
        datalen = len(self.data)
        if datalen <= line:
            return None

        build = [self.data[line]]

        # Add surrounding lines if they're available. There must always be
        # three elements in the context.
        if line > 0:
            build.insert(0, self.data[line - 1])
        else:
            build.insert(0, None)

        if line < datalen - 1:
            build.append(self.data[line + 1])
        else:
            build.append(None)

        leading_counts = []

        # Count whitespace to determine how much needs to be stripped.
        lstrip_count = INFINITY
        for line in build:
            # Don't count empty/whitespace-only lines.
            if line is None or not line.strip():
                leading_counts.append(lstrip_count)
                continue

            # Isolate the leading whitespace.
            ws_count = len(line) - len(line.lstrip())
            leading_counts.append(ws_count)
            if ws_count < lstrip_count:
                lstrip_count = ws_count

        # If all of the lines were skipped over, it means everything was
        # whitespace.
        if lstrip_count == INFINITY:
            return ('', '', '')

        for lnum in range(3):
            # Skip edge lines.
            if not build[lnum]:
                continue

            line = build[lnum].strip()

            # Empty lines stay empty.
            if not line:
                build[lnum] = ''
                continue

            line = self._format_line(line, column=column, rel_line=lnum)
            line = '%s%s' % (' ' * (leading_counts[lnum] - lstrip_count), line)

            build[lnum] = line

        # Return the final output as a tuple.
        return tuple(build)
1200744
function getExpectedIndent(line) {
            const offset = offsets.get(line)
            if (!offset) {
                const index = sourceCode.getIndexFromLoc({ line, column: 0 })
                const templateTag = microTemplateService.getTemplateTagByRangeIndex(
                    index
                )
                return getTopLevelIndentByTemplateTag(templateTag)
            }
            if (offset.expectedIndent !== undefined) {
                return offset.expectedIndent
            }

            const baseLineTemplate = microTemplateService
                .getMicroTemplateTokens()
                .find(t => t.loc.start.line === offset.baseline)

            let baseIndent = undefined
            if (baseLineTemplate) {
                baseIndent = getTopLevelIndentByTemplateTag(baseLineTemplate)
            } else {
                baseIndent = getExpectedIndent(offset.baseline)
            }

            const expectedNumberOfIndent =
                baseIndent.indent + offset.offset * options.indentSize

            const expectedIndent = new ExpectedIndent(
                baseIndent.baseIndentText,
                expectedNumberOfIndent
            )
            offset.expectedIndent = expectedIndent
            return expectedIndent
        }
204837
function format(text) {
    const lintResult = linter.executeOnText(text)
    return lintResult.results[0].output || text
}
696530
def get_context(template, line, num_lines=5, marker=None):
    '''
    
    '''
    template_lines = template.splitlines()
    num_template_lines = len(template_lines)

    # In test mode, a single line template would return a crazy line number like,
    # 357. Do this sanity check and if the given line is obviously wrong, just
    # return the entire template
    if line > num_template_lines:
        return template

    context_start = max(0, line - num_lines - 1)  # subt 1 for 0-based indexing
    context_end = min(num_template_lines, line + num_lines)
    error_line_in_context = line - context_start - 1  # subtr 1 for 0-based idx

    buf = []
    if context_start > 0:
        buf.append('[...]')
        error_line_in_context += 1

    buf.extend(template_lines[context_start:context_end])

    if context_end < num_template_lines:
        buf.append('[...]')

    if marker:
        buf[error_line_in_context] += marker

    return '---\n{0}\n---'.format('\n'.join(buf))
1269956
function insertLineContent(line, builder, styles) {
    var spans = line.markedSpans;
    if (!spans) {
      for (var i = 1; i < styles.length; i+=2)
        builder.addToken(builder, styles[i], styleToClass(styles[i+1]));
      return;
    }

    var allText = line.text, len = allText.length;
    var pos = 0, i = 1, text = "", style;
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
    for (;;) {
      if (nextChange == pos) { // Update current marker set
        spanStyle = spanEndStyle = spanStartStyle = "";
        collapsed = null; nextChange = Infinity;
        var foundBookmark = null;
        for (var j = 0; j < spans.length; ++j) {
          var sp = spans[j], m = sp.marker;
          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
            if (m.className) spanStyle += " " + m.className;
            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
            if (m.collapsed && (!collapsed || collapsed.marker.width < m.width))
              collapsed = sp;
          } else if (sp.from > pos && nextChange > sp.from) {
            nextChange = sp.from;
          }
          if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
            foundBookmark = m.replacedWith;
        }
        if (collapsed && (collapsed.from || 0) == pos) {
          buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
                             collapsed.from != null && collapsed.marker.replacedWith);
          if (collapsed.to == null) return collapsed.marker.find();
        }
        if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
      }
      if (pos >= len) break;

      var upto = Math.min(len, nextChange);
      while (true) {
        if (text) {
          var end = pos + text.length;
          if (!collapsed) {
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
          }
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
          pos = end;
          spanStartStyle = "";
        }
        text = styles[i++]; style = styleToClass(styles[i++]);
      }
    }
  }