Working with Text

A String is a sequence of Unicode codepoints, and its methods - on the String reference card - search, split and change it. This page is about the jobs that need more than one call: building long text, comparing what people type, and reshaping blocks of it.

Building text

++ makes a new string each time, so a loop that adds to one copies everything so far on every turn. A StringBuilder keeps the pieces and joins them once, when toString() asks. append takes any value and adds its #format text, and every adding method returns the builder, so calls chain. appendAll(values, separator) adds a whole list.

Text that looks the same

Unicode can write one character more than one way: é is a single codepoint, or an e followed by a combining accent. Text typed on one system and pasted from another may differ that way, so compare and store it normalized. normalize() gives NFC, the composed form most text is in; NFD takes every character apart; NFKC and NFKD also fold compatibility characters - ligatures, superscripts, full-width letters - into their plain forms, which suits search keys but loses formatting.

Fuzzy matching and typos

fuzzyScore(query) is how a command palette finds things: query's codepoints have to appear in order, ignoring case, and the score is higher when they come in runs or start words - fd puts Format Document before Open Folder. It's undefined when they don't all appear. editDistance(other) counts the fewest codepoints inserted, removed or replaced to turn one text into the other - the "did you mean" measure.

Reshaping blocks of text

dedent() takes off the indentation every non-blank line shares - what a block written inside indented code needs before it's printed - and indent(prefix) puts a prefix in front of every non-blank line.