Format the line to re-write previous lines, if necessary

@param string $line
@param integer $key
@param integer $last_frame_count

@return string
354032
protected function getLineFormatted($line, $key, $last_frame_count)
    {
        // If this is the first thing we're writing, just return the line
        if ($last_frame_count == 0) {
            return $line;
        }

        $content = '';

        // If this is the first line of the frame,
        // move the cursor up the total number of previous lines from the previous frame
        if ($key == 0) {
            $content .= $this->util->cursor->up($last_frame_count);
        }

        $content .= $this->util->cursor->startOfCurrentLine();
        $content .= $this->util->cursor->deleteCurrentLine();
        $content .= $line;

        return $content;
    }
1250590
public function rc4($key, $text)
	{
		if ($this->lastRc4Key != $key) {
			$k = str_repeat($key, 256 / strlen($key) + 1);
			$rc4 = range(0, 255);
			$j = 0;
			for ($i = 0; $i < 256; $i++) {
				$t = $rc4[$i];
				$j = ($j + $t + ord($k[$i])) % 256;
				$rc4[$i] = $rc4[$j];
				$rc4[$j] = $t;
			}
			$this->lastRc4Key = $key;
			$this->lastRc4KeyC = $rc4;
		} else {
			$rc4 = $this->lastRc4KeyC;
		}

		$len = strlen($text);
		$a = 0;
		$b = 0;
		$out = '';
		for ($i = 0; $i < $len; $i++) {
			$a = ($a + 1) % 256;
			$t = $rc4[$a];
			$b = ($b + $t) % 256;
			$rc4[$a] = $rc4[$b];
			$rc4[$b] = $t;
			$k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
			$out .= chr(ord($text[$i]) ^ $k);
		}

		return $out;
	}
1052600
private function formatGetFunctionDeclaration( $lines )
    {

        // do we need a switch statement
        $switch = '';
        if( count( $lines ) ) {
            $lines = new Format($lines);
            $switch = <<<PHP
    switch( \$key ) {

{$lines->indent(8)}
    }\n
PHP;
        }

        $fn = new Sformatf(
            <<<'PHP'
/**
 * Get entity property
 * {@inheritDoc}
 */
public function get( $key, $inputValidate = null, $source = null, \Bond\RecordManager\Task $task = null )
{
%s    return parent::get( $key, $inputValidate, $source, $task );
}
PHP
            , $switch
        );

        $this->class->classComponents[] = new FunctionDeclaration( "get", $fn );

    }
53304
private function getFirstElementFromQueue($key) :? string
    {
        $result = $this->getClient()->getRedis()->zrevrange($key, 0, 0);
        if (empty($result)) {
            return null;
        }

        return $result[0];
    }
1022651
def line( loc, strg ):
    
    lastCR = strg.rfind("\n", 0, loc)
    nextCR = strg.find("\n", loc)
    if nextCR >= 0:
        return strg[lastCR+1:nextCR]
    else:
        return strg[lastCR+1:]
263223
protected function getLastTokenOfLine(array $tokens, int $index): int
    {
        $line = $tokens[$index]['line'];

        $currentIndex = $index;
        while ($tokens[$currentIndex + 1]['line'] === $line) {
            $currentIndex++;
        }

        return $currentIndex;
    }
271563
def last_line(text):
    
    last_line_of_text = ""
    while last_line_of_text == "" and len(text) > 0:
        last_line_start = text.rfind("\n")
        # Handle one-line strings (without \n)
        last_line_start = max(0, last_line_start)
        last_line_of_text = text[last_line_start:].strip("\r\n ")
        text = text[:last_line_start]
    return last_line_of_text
1047368
private function checkLinesAfterLastContent($closePointer, $lastPointer)
    {
        $lines = TokenHelper::getContent($this->phpcsFile, $lastPointer + 1, $closePointer);
        $linesCount = $this->countLines($lines);

        if ($linesCount === 0) {
            return;
        }

        $this->phpcsFile->addError(
            \sprintf('No lines allowed after last content, found %d.', $linesCount),
            $lastPointer,
            'LinesAfterLastContent'
        );
    }
428516
private function getEndOfPreviousKeyPosition($key): int
    {
        preg_match($this->getKeyRegex($key), $this->contents, $matches, PREG_OFFSET_CAPTURE, $this->currentPosition);

        if (empty($matches)) {
            // for integers, the key may not be explicitly printed
            if (\is_int($key)) {
                return $this->currentPosition;
            }

            throw new YamlManipulationFailedException(sprintf('Cannot find the key "%s"', $key));
        }

        $startOfKey = $matches[0][1];

        // if we're at the start of the file, we're done!
        if (0 === $startOfKey) {
            return 0;
        }

        /*
         * Now, walk backwards: so that the position is before any
         * whitespace, commas or line breaks. Basically, we want to go
         * back to the first character *after* the previous key started.
         */
        // walk back any spaces
        while (' ' === substr($this->contents, $startOfKey - 1, 1)) {
            --$startOfKey;
        }

        // find either a line break or a , that is the end of the previous key
        while (\in_array(($char = substr($this->contents, $startOfKey - 1, 1)), [',', "\n"])) {
            --$startOfKey;
        }

        // look for \r\n
        if ("\r" === substr($this->contents, $startOfKey - 1, 1)) {
            --$startOfKey;
        }

        // if we're at the start of a line, if the prev line is a comment, move before it
        if ($this->isCharLineBreak(substr($this->contents, $startOfKey, 1))) {
            // move one (or two) forward so the code below finds the *previous* line
            ++$startOfKey;

            if ($this->isCharLineBreak(substr($this->contents, $startOfKey, 1))) {
                ++$startOfKey;
            }

            /*
             * In a multi-line array, the previous line(s) could be 100% comments.
             * In that situation, we want to rewind to *before* the comments, so
             * that those comments are attached to the current key and move with it.
             */
            while ($this->isPreviousLineComment($startOfKey)) {
                --$startOfKey;
                // if this is a \n\r, we need to go back an extra char
                if ("\r" === substr($this->contents, $startOfKey - 1, 1)) {
                    --$startOfKey;
                }

                while (!$this->isCharLineBreak(substr($this->contents, $startOfKey - 1, 1))) {
                    --$startOfKey;

                    // we've reached the start of the file!
                    if (0 === $startOfKey) {
                        break;
                    }
                }
            }

            if (0 !== $startOfKey) {
                // move backwards one onto the previous line
                --$startOfKey;
            }

            // look for \n\r situation
            if ("\r" === substr($this->contents, $startOfKey - 1, 1)) {
                --$startOfKey;
            }
        }

        return $startOfKey;
    }
581797
private static function formatParamsKey($key): string
    {
        if (\is_string($key) && \strpos($key, ':') === false) {
            return ':' . $key;
        }

        return $key;
    }
24358
protected function writeLines($lines, $newline = false) {
		$docblock = '';
		if ($newline) {
			$docblock .= " *\n";
		}

		foreach ($lines as $line) {
			if (strpos($line, "\n")) {
				$sublines = explode("\n", $line);
				$line = array_shift($sublines);
				$docblock .= ' * ' . $line . "\n";
				$docblock .= $this->writeLines($sublines);
			} else {
				$docblock .= ' * ' . $line . "\n";
			}
		}
		
		return $docblock;
	}
655032
public function formatList($list)
    {
        /**
         * The query to be returned.
         *
         * @var string
         */
        $ret = '';

        /**
         * The indentation level.
         *
         * @var int
         */
        $indent = 0;

        /**
         * Whether the line ended.
         *
         * @var bool
         */
        $lineEnded = false;

        /**
         * Whether current group is short (no linebreaks).
         *
         * @var bool
         */
        $shortGroup = false;

        /**
         * The name of the last clause.
         *
         * @var string
         */
        $lastClause = '';

        /**
         * A stack that keeps track of the indentation level every time a new
         * block is found.
         *
         * @var array
         */
        $blocksIndentation = [];

        /**
         * A stack that keeps track of the line endings every time a new block
         * is found.
         *
         * @var array
         */
        $blocksLineEndings = [];

        /**
         * Whether clause's options were formatted.
         *
         * @var bool
         */
        $formattedOptions = false;

        /**
         * Previously parsed token.
         *
         * @var Token|null
         */
        $prev = null;

        // In order to be able to format the queries correctly, the next token
        // must be taken into consideration. The loop below uses two pointers,
        // `$prev` and `$curr` which store two consecutive tokens.
        // Actually, at every iteration the previous token is being used.
        for ($list->idx = 0; $list->idx < $list->count; ++$list->idx) {
            /**
             * Token parsed at this moment.
             *
             * @var Token
             */
            $curr = $list->tokens[$list->idx];
            if ($list->idx + 1 < $list->count) {
                $next = $list->tokens[$list->idx + 1];
            } else {
                $next = null;
            }

            if ($curr->type === Token::TYPE_WHITESPACE) {
                // Keep linebreaks before and after comments
                if (strpos($curr->token, "\n") !== false && (
                        ($prev !== null && $prev->type === Token::TYPE_COMMENT) ||
                        ($next !== null && $next->type === Token::TYPE_COMMENT)
                    )
                ) {
                    $lineEnded = true;
                }
                // Whitespaces are skipped because the formatter adds its own.
                continue;
            }

            if ($curr->type === Token::TYPE_COMMENT && $this->options['remove_comments']) {
                // Skip Comments if option `remove_comments` is enabled
                continue;
            }

            // Checking if pointers were initialized.
            if ($prev !== null) {
                // Checking if a new clause started.
                if (static::isClause($prev) !== false) {
                    $lastClause = $prev->value;
                    $formattedOptions = false;
                }

                // The options of a clause should stay on the same line and everything that follows.
                if ($this->options['parts_newline']
                    && ! $formattedOptions
                    && empty(self::$INLINE_CLAUSES[$lastClause])
                    && (
                        $curr->type !== Token::TYPE_KEYWORD
                        || (
                            $curr->type === Token::TYPE_KEYWORD
                            && $curr->flags & Token::FLAG_KEYWORD_FUNCTION
                        )
                    )
                ) {
                    $formattedOptions = true;
                    $lineEnded = true;
                    ++$indent;
                }

                // Checking if this clause ended.
                if ($isClause = static::isClause($curr)) {
                    if (($isClause === 2 || $this->options['clause_newline']) && empty(self::$SHORT_CLAUSES[$lastClause])) {
                        $lineEnded = true;
                        if ($this->options['parts_newline'] && $indent > 0) {
                            --$indent;
                        }
                    }
                }

                // Inline JOINs
                if (($prev->type === Token::TYPE_KEYWORD && isset(JoinKeyword::$JOINS[$prev->value]))
                    || (in_array($curr->value, ['ON', 'USING'], true) && isset(JoinKeyword::$JOINS[$list->tokens[$list->idx - 2]->value]))
                    || isset($list->tokens[$list->idx - 4], JoinKeyword::$JOINS[$list->tokens[$list->idx - 4]->value])
                    || isset($list->tokens[$list->idx - 6], JoinKeyword::$JOINS[$list->tokens[$list->idx - 6]->value])
                ) {
                    $lineEnded = false;
                }

                // Indenting BEGIN ... END blocks.
                if ($prev->type === Token::TYPE_KEYWORD && $prev->keyword === 'BEGIN') {
                    $lineEnded = true;
                    $blocksIndentation[] = $indent;
                    ++$indent;
                } elseif ($curr->type === Token::TYPE_KEYWORD && $curr->keyword === 'END') {
                    $lineEnded = true;
                    $indent = array_pop($blocksIndentation);
                }

                // Formatting fragments delimited by comma.
                if ($prev->type === Token::TYPE_OPERATOR && $prev->value === ',') {
                    // Fragments delimited by a comma are broken into multiple
                    // pieces only if the clause is not inlined or this fragment
                    // is between brackets that are on new line.
                    if (end($blocksLineEndings) === true
                        || (
                            empty(self::$INLINE_CLAUSES[$lastClause])
                            && ! $shortGroup
                            && $this->options['parts_newline']
                        )
                    ) {
                        $lineEnded = true;
                    }
                }

                // Handling brackets.
                // Brackets are indented only if the length of the fragment between
                // them is longer than 30 characters.
                if ($prev->type === Token::TYPE_OPERATOR && $prev->value === '(') {
                    $blocksIndentation[] = $indent;
                    $shortGroup = true;
                    if (static::getGroupLength($list) > 30) {
                        ++$indent;
                        $lineEnded = true;
                        $shortGroup = false;
                    }
                    $blocksLineEndings[] = $lineEnded;
                } elseif ($curr->type === Token::TYPE_OPERATOR && $curr->value === ')') {
                    $indent = array_pop($blocksIndentation);
                    $lineEnded |= array_pop($blocksLineEndings);
                    $shortGroup = false;
                }

                // Adding the token.
                $ret .= $this->toString($prev);

                // Finishing the line.
                if ($lineEnded) {
                    $ret .= $this->options['line_ending']
                        . str_repeat($this->options['indentation'], $indent);

                    $lineEnded = false;
                } else {
                    // If the line ended there is no point in adding whitespaces.
                    // Also, some tokens do not have spaces before or after them.
                    if (// A space after delimiters that are longer than 2 characters.
                        $prev->keyword === 'DELIMITER'
                        || ! (
                            ($prev->type === Token::TYPE_OPERATOR && ($prev->value === '.' || $prev->value === '('))
                            // No space after . (
                            || ($curr->type === Token::TYPE_OPERATOR && ($curr->value === '.' || $curr->value === ',' || $curr->value === '(' || $curr->value === ')'))
                            // No space before . , ( )
                            || $curr->type === Token::TYPE_DELIMITER && mb_strlen((string) $curr->value, 'UTF-8') < 2
                        )
                    ) {
                        $ret .= ' ';
                    }
                }
            }

            // Iteration finished, consider current token as previous.
            $prev = $curr;
        }

        if ($this->options['type'] === 'cli') {
            return $ret . "\x1b[0m";
        }

        return $ret;
    }
490084
public function remove($key)
    {
        $linesBefore = $this->lineCount();

        $this->lines->removeDefinition($key);

        return $linesBefore - $this->lineCount();
    }
756116
public function withKey($key)
    {
        $this->lastKey = $key;
        $this->keys[$key] = null;

        return $this;
    }
158966
def previous_multiline(key)
      begin
        # scan multilines until no further multiline is hit
        # /#\|\p{Blank}"/ needs to catch the double quote to ensure it hits a previous
        # multiline and not another line type.
        if @scanner.scan(/#\|\p{Blank}*"/)
          @scanner.pos = @scanner.pos - 1 # go one character back, so we can reuse the "message line" method
          add_result(key, message_line)
          previous_multiline(key) # go on until we no longer hit a multiline line
        end
      rescue PoSyntaxError => pe
        raise PoSyntaxError, "Syntax error in previous_multiline\n" + pe.message, pe.backtrace
      end
    end
1298435
private function getFirstSegmentOfKey(Line $line)
    {
        // Remove first part since that part equals the page
        $key = substr($line->key, strpos($line->key, '.')+1);

        $length = strpos($key, '.')?: strlen($key);
        $key = substr($key, 0, $length);

        return $key;
    }
653420
protected function printBlock(array $lines, $style, $firstBlock = false)
    {
        /** @var FormatterHelper $formatter */
        $formatter = $this->getHelper('formatter');

        // just to satisfy my obsessive needs.
        if ($firstBlock) {
            // prints an empty line at the begging of output.
            $this->line('');
        }

        // merge argument lines with an empty line before and after.
        $spacedLines = array_merge([''], array_merge($lines, ['']));
        // generate a text block.
        $block = $formatter->formatBlock($spacedLines, $style);

        // print it.
        $this->line($block);

        // empty ending line.
        $this->line('');
    }