Wrap text into lines
Break text into lines that fit a width with greedy word wrapping, measure how tall the result is, and handle single words too long for any line.
Knowing how wide text is lets us answer the question layout really needs: given a box this wide, how many lines will this paragraph take, and how tall will it be? That's .
Greedy wrapping
- Start with an empty line.
- For each word, try it on the end of the line (with a space). If
measureTextsays the result still fits, keep it. - If it doesn't fit, the current line is finished. Start the next line with this word.
- After the last word, the unfinished line is the last line.
It's called greedy because it packs each line as full as possible before moving on. PowerPoint wraps the same way, which is exactly why it works: our lines match its lines.
How tall is it?
PowerPoint's single line spacing for Arial is about 1.2 × the font size. So textHeight(lines, fontSize) is lines × fontSize × 1.2. Three lines of 18pt text are 64.8 points tall.
Under the hood — Is greedy wrapping the best possible?
Not always. Typesetting systems like TeX consider the whole paragraph at once to make line lengths more even. But PowerPoint uses greedy wrapping, and our goal is to predict PowerPoint, not to beat it. Matching the renderer matters more than elegance here.
Key takeaways
- Greedy wrapping adds words to a line until the next one wouldn't fit, then starts a new line.
- Text height is the number of lines × font size × 1.2.
- A word wider than the box is broken into pieces so nothing sticks out.
Sign in to run the exercise
Reading is free. Writing code here needs an account so we have somewhere to keep your Gemini key and the +30 XP you are about to earn.