Like QString::simpified(), except that it preserves non-breaking spaces (which Evernote uses for identation, etc.)
7747
function simplifyString(s) {
	let output = '';
	let previousWhite = false;
	for (let i = 0; i < s.length; i++) {
		let c = s[i];
		let isWhite = isWhiteSpace(c);
		if (previousWhite && isWhite) {
			// skip
		} else {
			output += c;
		}
		previousWhite = isWhite;
	}

	while (output.length && isWhiteSpace(output[0])) output = output.substr(1);
	while (output.length && isWhiteSpace(output[output.length - 1])) output = output.substr(0, output.length - 1);

	return output;
}
120057
function( text ){
			if(text && text.length){
				var i = text.length,
					x = 0;

				// turn all whitespace chars at end into spaces
				while (i--) {
					if(this.isOnlyWhiteSpace(text[i])){
						text = this.replaceCharAt( text, i, ' ' );
					}else{
						break;
					}
				}

				// turn all whitespace chars at start into spaces
				i = text.length;
				while (x < i) {
					if(this.isOnlyWhiteSpace(text[x])){
						text = this.replaceCharAt( text, i, ' ' );
					}else{
						break;
					}
					x++;
				}
			}
			return this.trim(text);
		}
1018257
def fix_indentation_depth(query):
    """"""
    lines = query.split('\n')
    final_lines = []

    for line in lines:
        consecutive_spaces = 0
        for char in line:
            if char == ' ':
                consecutive_spaces += 1
            else:
                break

        if consecutive_spaces % 2 != 0:
            raise AssertionError(u'Indentation was not a multiple of two: '
                                 u'{}'.format(consecutive_spaces))

        final_lines.append(('  ' * consecutive_spaces) + line[consecutive_spaces:])

    return '\n'.join(final_lines)
311365
def beautify_string(self, data, path=''):
        """"""
        tab = 0
        case_level = 0
        prev_line_had_continue = False
        continue_line = False
        started_multiline_quoted_string = False
        ended_multiline_quoted_string = False
        open_brackets = 0
        in_here_doc = False
        defer_ext_quote = False
        in_ext_quote = False
        ext_quote_string = ''
        here_string = ''
        output = []
        line = 1
        formatter = True
        for record in re.split('\n', data):
            record = record.rstrip()
            stripped_record = record.strip()

            # preserve blank lines
            if not stripped_record:
                output.append(stripped_record)
                continue

            # ensure space before ;; terminators in case statements
            if case_level:
                stripped_record = re.sub(r'(\S);;', r'\1 ;;', stripped_record)

            test_record = self.get_test_record(stripped_record)

            # detect whether this line ends with line continuation character:
            prev_line_had_continue = continue_line
            continue_line = True if (re.search(r'\\$', stripped_record)!=None) else False
            inside_multiline_quoted_string = prev_line_had_continue and continue_line and started_multiline_quoted_string

            if not continue_line and prev_line_had_continue and started_multiline_quoted_string:
                # remove contents of strings initiated on previous lines and that are ending on this line:
                [test_record, num_subs] = re.subn(r'^[^"]*"', '', test_record)
                ended_multiline_quoted_string = True if num_subs>0 else False
            else:
                ended_multiline_quoted_string = False

            if(in_here_doc) or (inside_multiline_quoted_string) or (ended_multiline_quoted_string):  # pass on with no changes
                output.append(record)
                # now test for here-doc termination string
                if(re.search(here_string, test_record) and not
                   re.search(r'<<', test_record)):
                    in_here_doc = False
            else:  # not in here doc or inside multiline-quoted

                if continue_line:
                    if prev_line_had_continue:
                        # this line is not STARTING a multiline-quoted string... we may be in the middle
                        # of such a multiline string though
                        started_multiline_quoted_string = False
                    else:
                        # remove contents of strings initiated on current line but that continue on next line
                        # (in particular we need to ignore brackets they may contain!)
                        [test_record, num_subs] = re.subn(r'"[^"]*?\\$', '', test_record)
                        started_multiline_quoted_string = True if num_subs>0 else False
                else:
                    # this line is not STARTING a multiline-quoted string
                    started_multiline_quoted_string = False

                if(re.search(r'<<-?', test_record)) and not (re.search(r'.*<<<', test_record)):
                    here_string = re.sub(
                        r'.*<<-?\s*[\'|"]?([_|\w]+)[\'|"]?.*', r'\1',
                        stripped_record, 1)
                    in_here_doc = (len(here_string) > 0)

                if(in_ext_quote):
                    if(re.search(ext_quote_string, test_record)):
                        # provide line after quotes
                        test_record = re.sub(
                            r'.*%s(.*)' % ext_quote_string, r'\1',
                            test_record, 1)
                        in_ext_quote = False
                else:  # not in ext quote
                    if(re.search(r'(\A|\s)(\'|")', test_record)):
                        # apply only after this line has been processed
                        defer_ext_quote = True
                        ext_quote_string = re.sub(
                            r'.*([\'"]).*', r'\1', test_record, 1)
                        # provide line before quote
                        test_record = re.sub(
                            r'(.*)%s.*' % ext_quote_string, r'\1',
                            test_record, 1)
                if(in_ext_quote or not formatter):
                    # pass on unchanged
                    output.append(record)
                    if(re.search(r'#\s*@formatter:on', stripped_record)):
                        formatter = True
                        continue
                else:  # not in ext quote
                    if(re.search(r'#\s*@formatter:off', stripped_record)):
                        formatter = False
                        output.append(record)
                        continue

                    # multi-line conditions are often meticulously formatted
                    if open_brackets:
                        output.append(record)
                    else:
                        inc = len(re.findall(
                            r'(\s|\A|;)(case|then|do)(;|\Z|\s)', test_record))
                        inc += len(re.findall(r'(\{|\(|\[)', test_record))
                        outc = len(re.findall(
                            r'(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)',
                            test_record))
                        outc += len(re.findall(r'(\}|\)|\])', test_record))
                        if(re.search(r'\besac\b', test_record)):
                            if(case_level == 0):
                                sys.stderr.write(
                                    'File %s: error: "esac" before "case" in '
                                    'line %d.\n' % (path, line))
                            else:
                                outc += 1
                                case_level -= 1

                        # special handling for bad syntax within case ... esac
                        if re.search(r'\bcase\b', test_record):
                            inc += 1
                            case_level += 1

                        choice_case = 0
                        if case_level:
                            if(re.search(r'\A[^(]*\)', test_record)):
                                inc += 1
                                choice_case = -1

                        # detect functions
                        func_decl_style = self.detect_function_style(test_record)
                        if func_decl_style != None:
                             stripped_record = self.change_function_style(stripped_record, func_decl_style)

                        # an ad-hoc solution for the "else" or "elif" keyword
                        else_case = (0, -1)[re.search(r'^(else|elif)',
                                            test_record) is not None]
                        net = inc - outc
                        tab += min(net, 0)

                        # while 'tab' is preserved across multiple lines, 'extab' is not and is used for
                        # some adjustments:
                        extab = tab + else_case + choice_case
                        if prev_line_had_continue and not open_brackets and not ended_multiline_quoted_string:
                            extab+=1
                        extab = max(0, extab)
                        output.append((self.tab_str * self.tab_size * extab) +
                                      stripped_record)
                        tab += max(net, 0)
                if(defer_ext_quote):
                    in_ext_quote = True
                    defer_ext_quote = False

                # count open brackets for line continuation
                open_brackets += len(re.findall(r'\[', test_record))
                open_brackets -= len(re.findall(r'\]', test_record))
            line += 1
        error = (tab != 0)
        if(error):
            sys.stderr.write(
                'File %s: error: indent/outdent mismatch: %d.\n' % (path, tab))
        return '\n'.join(output), error
44225
function uglifyWithCopyrights() {
    const preserveComments = (f) => {
        return (_node, comment) => {
            const text = comment.value;
            const type = comment.type;
            if (/@minifier_do_not_preserve/.test(text)) {
                return false;
            }
            const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
            if (isOurCopyright) {
                if (f.__hasOurCopyright) {
                    return false;
                }
                f.__hasOurCopyright = true;
                return true;
            }
            if ('comment2' === type) {
                // check for /*!. Note that text doesn't contain leading /*
                return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
            }
            else if ('comment1' === type) {
                return /license|copyright/i.test(text);
            }
            return false;
        };
    };
    const minify = composer(uglifyes);
    const input = es.through();
    const output = input
        .pipe(flatmap((stream, f) => {
        return stream.pipe(minify({
            output: {
                comments: preserveComments(f),
                max_line_len: 1024
            }
        }));
    }));
    return es.duplex(input, output);
}
1014720
public static String prettyToString(final Object object, final int indentation) {
        final String string = object.toString();

        // position of new lines and number of intending spaces
        final Map<Integer, Integer> newLines = new TreeMap<>();

        int currentLevel = 0;
        boolean inStringLiteral = false;
        for (int i = 0; i < string.length(); i++) {
            final char currentChar = string.charAt(i);
            if (currentChar == ',' && !inStringLiteral)
                newLines.put(i, currentLevel);
            if (currentChar == '{' && !inStringLiteral)
                currentLevel++;
            if (currentChar == '}' && !inStringLiteral)
                currentLevel--;

            // known flaw -> will fail for string containing a ' character
            if (currentChar == '\'')
                inStringLiteral = !inStringLiteral;
        }

        final StringBuilder builder = new StringBuilder(string);

        int modifiedLength = 0;
        for (final Map.Entry<Integer, Integer> entry : newLines.entrySet()) {
            final String intend = IntStream.range(0, entry.getValue() * indentation).mapToObj(c -> INDENTATION_CHARACTER)
                    .collect(() -> new StringBuilder("\n"), StringBuilder::append, StringBuilder::append).toString();

            builder.insert(modifiedLength + entry.getKey() + 1, intend);
            modifiedLength += intend.length();
        }

        return builder.toString();
    }
1167018
def collapse_indents(indentation):
    """"""
    change_in_level = ind_change(indentation)
    if change_in_level == 0:
        indents = ""
    elif change_in_level < 0:
        indents = closeindent * (-change_in_level)
    else:
        indents = openindent * change_in_level
    return indentation.replace(openindent, "").replace(closeindent, "") + indents
463155
function(str) {
    return trim(str).replace(/([\r\n\s　])+/g, function(match, whitespace) {
      return whitespace === '　' ? whitespace : ' ';
    });
  }
994866
def json_minify(string, strip_space=True): # pragma: no cover
    
    in_string = False
    in_multi = False
    in_single = False

    new_str = []
    index = 0

    for match in re.finditer(TOKENIZER, string):

        if not (in_multi or in_single):
            tmp = string[index:match.start()]
            if not in_string and strip_space:
                # replace white space as defined in standard
                tmp = re.sub('[ \t\n\r]+', '', tmp)
            new_str.append(tmp)

        index = match.end()
        val = match.group()

        if val == '"' and not (in_multi or in_single):
            escaped = END_SLASHES_RE.search(string, 0, match.start())

            # start of string or unescaped quote character to end string
            if not in_string or (escaped is None or len(escaped.group()) % 2 == 0):
                in_string = not in_string
            index -= 1 # include " character in next catch
        elif not (in_string or in_multi or in_single):
            if val == '/*':
                in_multi = True
            elif val == '//':
                in_single = True
        elif val == '*/' and in_multi and not (in_string or in_single):
            in_multi = False
        elif val in '\r\n' and not (in_multi or in_string) and in_single:
            in_single = False
        elif not ((in_multi or in_single) or (val in ' \r\n\t' and strip_space)):
            new_str.append(val)

    new_str.append(string[index:])
    return ''.join(new_str)
1051847
def remove_trailing_white_spaces(self):
        

        cursor = self.textCursor()

        block = self.document().findBlockByLineNumber(0)
        while block.isValid():
            cursor.setPosition(block.position())
            if re.search(r"\s+$", block.text()):
                cursor.movePosition(QTextCursor.EndOfBlock)
                cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.KeepAnchor)
                cursor.insertText(foundations.strings.to_string(block.text()).rstrip())
            block = block.next()
        cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
        if not cursor.block().text().isEmpty():
            cursor.insertText("\n")
        return True
498541
def clean_docstring(docstring):
    """"""
    docstring = docstring.strip()
    if '\n' in docstring:
        # multiline docstring
        if docstring[0].isspace():
            # whole docstring is indented
            return textwrap.dedent(docstring)
        else:
            # first line not indented, rest maybe
            first, _, rest = docstring.partition('\n')
            return first + '\n' + textwrap.dedent(rest)
    return docstring
492033
def pretty_str(self, indent=0):
        
        return '\n\n'.join(
                codeobj.pretty_str(indent=indent)
                for codeobj in self.children
        )
731190
def _make_pretty_note(note):
    

    if note != "":
        note = "\n".join(map(lambda n: n[4:], note.split("\n")))
        return "**Note:**\n%s\n" % note
1204648
def format_no_tty(table):
    """"""

    for i, row in enumerate(table.rows):
        for j, item in enumerate(row):
            table.rows[i][j] = format_output(item, fmt='raw')
    ptable = table.prettytable()

    for col in table.columns:
        ptable.align[col] = 'l'

    ptable.hrules = prettytable.NONE
    ptable.border = False
    ptable.header = False
    ptable.left_padding_width = 0
    ptable.right_padding_width = 2
    return ptable
284938
def pretty_format(obj, indent=None):
        
        if indent is None:
            if isinstance(obj, TLObject):
                obj = obj.to_dict()

            if isinstance(obj, dict):
                return '{}({})'.format(obj.get('_', 'dict'), ', '.join(
                    '{}={}'.format(k, TLObject.pretty_format(v))
                    for k, v in obj.items() if k != '_'
                ))
            elif isinstance(obj, str) or isinstance(obj, bytes):
                return repr(obj)
            elif hasattr(obj, '__iter__'):
                return '[{}]'.format(
                    ', '.join(TLObject.pretty_format(x) for x in obj)
                )
            else:
                return repr(obj)
        else:
            result = []
            if isinstance(obj, TLObject):
                obj = obj.to_dict()

            if isinstance(obj, dict):
                result.append(obj.get('_', 'dict'))
                result.append('(')
                if obj:
                    result.append('\n')
                    indent += 1
                    for k, v in obj.items():
                        if k == '_':
                            continue
                        result.append('\t' * indent)
                        result.append(k)
                        result.append('=')
                        result.append(TLObject.pretty_format(v, indent))
                        result.append(',\n')
                    result.pop()  # last ',\n'
                    indent -= 1
                    result.append('\n')
                    result.append('\t' * indent)
                result.append(')')

            elif isinstance(obj, str) or isinstance(obj, bytes):
                result.append(repr(obj))

            elif hasattr(obj, '__iter__'):
                result.append('[\n')
                indent += 1
                for x in obj:
                    result.append('\t' * indent)
                    result.append(TLObject.pretty_format(x, indent))
                    result.append(',\n')
                indent -= 1
                result.append('\t' * indent)
                result.append(']')

            else:
                result.append(repr(obj))

            return ''.join(result)
806750
function indentation(value, maximum) {
  var values = value.split(lineFeed)
  var position = values.length + 1
  var minIndent = Infinity
  var matrix = []
  var index
  var indentation
  var stops
  var padding

  values.unshift(repeat(space, maximum) + exclamationMark)

  while (position--) {
    indentation = getIndent(values[position])

    matrix[position] = indentation.stops

    if (trim(values[position]).length === 0) {
      continue
    }

    if (indentation.indent) {
      if (indentation.indent > 0 && indentation.indent < minIndent) {
        minIndent = indentation.indent
      }
    } else {
      minIndent = Infinity

      break
    }
  }

  if (minIndent !== Infinity) {
    position = values.length

    while (position--) {
      stops = matrix[position]
      index = minIndent

      while (index && !(index in stops)) {
        index--
      }

      if (
        trim(values[position]).length !== 0 &&
        minIndent &&
        index !== minIndent
      ) {
        padding = tab
      } else {
        padding = ''
      }

      values[position] =
        padding + values[position].slice(index in stops ? stops[index] + 1 : 0)
    }
  }

  values.shift()

  return values.join(lineFeed)
}
953176
def _pad(self):
    
    if self._indent:
      self.whitespace(self._indent * len(self._open_elements))