Skip to content
Writing
Hook

Hooks

What cc-stretch runs automatically, and when. A hook is a command Claude Code fires at a fixed moment, without you asking for it.

From plugin
cc-stretch
4381 command1 hook

Claude Code

> /plugin marketplace add pro-vi/cc-stretch
> /plugin install cc-stretch@cc-stretch

What fires, and when

modules

Read hooks/hooks.json

Where it lives

  • hooks/contrast.tsGitHub
    Read the script
    // Colour arithmetic shared by the reply and the hooks module: the text colour that reads on a highlight,
    // and the mix and hex spelling the stretch palette is built from.
    
    /** A colour's red, green and blue, 0 to 255 each. */
    export type Rgb = readonly [number, number, number]
    /** A colour written `#rgb` or `#rrggbb`. */
    export type Hex = `#${string}`
    
    const DARK: Rgb = [0x1c, 0x1c, 0x1c]
    const LIGHT: Rgb = [0xf2, 0xf2, 0xf2]
    /**
     * How far dim moves text toward its background: as of Claude Code 2.1.302 Claude Code's dim grey sits
     * 40% of the way from text to background on both themes (153 between 255 and 0, 102 between 0 and 255).
     */
    const DIM_SHARE = 0.4
    
    /** A colour written as `#rrggbb`. */
    export const hex = (rgb: Rgb): Hex => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`
    
    /** `rgb` moved `share` of the way toward `toward`, channel by channel. */
    export function mix(rgb: Rgb, toward: Rgb, share: number): Rgb {
      const channel = (at: 0 | 1 | 2) => Math.round(rgb[at] + (toward[at] - rgb[at]) * share)
      return [channel(0), channel(1), channel(2)]
    }
    
    /** The red, green and blue of a `#rgb` or `#rrggbb` colour; undefined for anything else. */
    function rgbOf(colour: string): Rgb | undefined {
      const short = /^#([0-9a-f]{3})$/i.exec(colour)?.[1]
      const digits = short === undefined ? /^#([0-9a-f]{6})$/i.exec(colour)?.[1] : [...short].map(c => c + c).join('')
      if (digits === undefined) return undefined
      const channel = (at: number) => parseInt(digits.slice(at, at + 2), 16)
      return [channel(0), channel(2), channel(4)]
    }
    
    /** Whether a colour is written `#rgb` or `#rrggbb`. */
    export const isHex = (colour: string): colour is Hex => rgbOf(colour) !== undefined
    
    /** The relative luminance of a colour, as WCAG defines it. */
    function luminance(rgb: Rgb): number {
      const linear = (value: number) => {
        const c = value / 255
        return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
      }
      return 0.2126 * linear(rgb[0]) + 0.7152 * linear(rgb[1]) + 0.0722 * linear(rgb[2])
    }
    
    const ratio = (a: number, b: number) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
    
    /**
     * Text that reads on a highlight: near black or near white, whichever contrasts more, and under dim
     * moved toward the highlight as dim moves text toward its background. Nothing for a colour that is
     * not hex, whose luminance is unknown here.
     */
    export function contrastOn(background: string, isDim = false): { color?: Hex } {
      const backgroundRgb = rgbOf(background)
      if (backgroundRgb === undefined) return {}
      const bg = luminance(backgroundRgb)
      const text = ratio(bg, luminance(DARK)) >= ratio(bg, luminance(LIGHT)) ? DARK : LIGHT
      return { color: hex(isDim ? mix(text, backgroundRgb, DIM_SHARE) : text) }
    }
    
  • hooks/grow.tsGitHub
    Read the script
    import { asArriving, breakables } from './layout'
    import type { Segment, Stretch } from './parse'
    
    // A long form grows around its short form. A word here is a piece a row may
    // break between (breakables in layout.ts), so Chinese grows a character at a
    // time, with the punctuation that sticks to it. The words both forms share, in
    // order, stand throughout; the words the long form adds arrive from them
    // outward, so the sentence widens at every seam at once, to the left of a
    // shared word as much as to its right. Words arrive whole: a terminal has no
    // room to fade one in, and half a word reads as a typo. A markdown link arrives
    // whole too, since part of one is drawn as its markup. Around each shared word,
    // the short form's own text stands until the first word the long form adds
    // there arrives, so a growth starts as the closed short form is drawn and ends
    // as the open long form is, and nothing moves when it turns into either.
    
    /**
     * A word, a run of spaces, a markdown link or a nested stretch. A word `glued` to the one before it
     * was cut from the same word, as the comma is from `fails,`, and arrives with it.
     */
    type Token = { kind: 'word'; text: string; glued?: true } | { kind: 'space'; text: string } | { kind: 'link'; text: string; label: string } | { kind: 'nested'; stretch: Stretch }
    
    /** A markdown link or image as hooks/layout.ts reads one: a label, then a target with no space in it. */
    const LINK = /!?\[([^\]\n]+)\]\([^)\s]+\)/g
    
    /** Where a run of new words sits relative to the shared words around it. */
    type Side = 'before' | 'between' | 'after'
    
    // Punctuation a word carries on either side, cut off it so that `fails` in a short form meets
    // `fails,` in its long form and the comma arrives as the long form's own. Only marks that mean
    // nothing to markdown are cut.
    const LOOSE = '.,;:!?…"\'“”‘’,。、;:?!'
    
    // A mark that pairs with another in markdown, or changes the character after it. The short form's
    // text between two shared words stands among the long form's words while it grows, so where that
    // text holds one, the two forms share no word and the short form leaves whole: half of its markup
    // could otherwise meet half of the long form's.
    const PAIRING = /[`*_~[\]\\<]/
    
    /**
     * Between two shared words, or before the first or after the last: the short form's text there, and
     * the long form's tokens there, from `from` up to the shared one at `to`.
     */
    type Gap = { left: string; from: number; to: number }
    
    /**
     * The long form at `progress`: 0 shows the short form as written, 1 the long form as written.
     * `draw` writes a nested stretch, which is never shown in part; `paint` marks each word the long
     * form adds, with any punctuation cut off it, so the reader can tell it from the words they already
     * read. A frame that shows some of the words the long form adds and not all of them is marked as
     * arriving (`asArriving`), so an opening mark whose closing one has not arrived is not drawn; one
     * that shows none or all is not, so it draws as the short form does closed or the long form open.
     */
    export function grow(
      short: string,
      long: Segment[],
      progress: number,
      draw: (nested: Stretch) => string,
      paint: (word: string) => string = word => word,
    ): string {
      const tokens = cut(tokenize(long))
      const { shared, gaps } = sharedOf(short, tokens)
      const arrival = arrivalsOf(tokens, shared)
      const at = Math.min(1, Math.max(0, progress))
      const added = tokens.flatMap((token, i) => (token.kind === 'space' || shared.has(i) ? [] : [arrival.get(i) ?? 0]))
      const isPart = added.some(time => time <= at) && added.some(time => time > at)
    
      let out = ''
      for (const { left, from, to } of gaps) {
        const gap = tokens.slice(from, to)
        const times = gap.map((token, k) => (token.kind === 'space' ? undefined : arrival.get(from + k)))
        // The earliest point among the words before each token of the gap, and among those after it.
        const before: number[] = []
        const after: number[] = []
        let least = Infinity
        for (const time of times) {
          before.push(least)
          least = Math.min(least, time ?? Infinity)
        }
        // A gap the long form adds nothing to, its short form's text there dropped, closes halfway.
        const opens = Number.isFinite(least) ? least : 0.5
        least = Infinity
        for (let k = times.length - 1; k >= 0; k--) {
          after[k] = least
          least = Math.min(least, times[k] ?? Infinity)
        }
        // Where both forms have only a space, the long form's stands throughout.
        const isSpaced = left !== '' && left.trim() === '' && gap.length > 0 && gap.every(token => token.kind === 'space')
        if (isSpaced) out += gap.map(token => (token.kind === 'space' ? token.text : '')).join('')
        else if (at < opens) out += left
        else {
          // A space between two words added here shows once a word on each side of it has and one right
          // beside it has, so none trails a word with nothing yet after it, and none stands between two
          // words the long form writes together; one beside a shared word shows with the first word
          // added. Spaces that words still to come leave side by side are drawn as one, the one that
          // breaks the most lines, as the long form will.
          let space: string | undefined
          // A word and the punctuation cut off it arrive together and are painted as one.
          let word = ''
          const endWord = () => {
            if (word !== '') out += paint(word)
            word = ''
          }
          gap.forEach((token, k) => {
            if (token.kind === 'space') {
              endWord()
              const wordBefore = before[k] ?? Infinity
              const wordAfter = after[k] ?? Infinity
              const beside = Math.min(times[k - 1] ?? Infinity, times[k + 1] ?? Infinity)
              const point = Number.isFinite(wordBefore) && Number.isFinite(wordAfter) ? Math.max(wordBefore, wordAfter, beside) : opens
              if (point <= at && (space === undefined || breaks(token.text) > breaks(space))) space = token.text
              retur
  • hooks/guide.tsGitHub
    Read the script
    // The section cc-stretch adds to Claude's system prompt, and the rule that picks which sessions
    // carry a guide on trial in its place. The benchmark rewrites replies under this same text and the
    // trial's live check uses the rule, so the file lives on its own.
    export const GUIDE = `# Stretchtext replies
    
    The reader's screen draws each stretch \`{{short|long}}\` in your reply as its short form, a link. A click puts the long form in its place and the text reads on; nothing moves to a separate section. So write every reply to read complete at its shortest, with depth where each stretch stands:
    
    - At its shortest, the reply is one to three short sentences that answer on their own. Anything the reader must decide or do stays outside every stretch.
    - Stretch list items, not whole lists.
    - A short form says what its long form says, in fewer words, however many that takes. When the long form is a plan or a series, its short form is that series with each part named in a few words. A count of the parts ("three fixes"), a word for what remains ("the rest", "a few follow-ups") and a sentence that only announces them are not short forms: name each part. Example: "{{Next: key the cache on the lockfile; drop the retry; ship on Friday.|Next: key the CI cache on the lockfile as well as \`package.json\`; drop the retry, which only hides the stale read; and ship on Friday, once CI has passed twice.}}"
    - The long form keeps every word of the short form, in the same order, and grows around them: words added before, between and after the ones the reader already saw. On screen those words stay where they are while the new ones open up around them, so the reader never loses their place. Example: "{{The build fails on a stale cache.|The CI build fails, about one run in five, on a stale dependency cache keyed only by \`package.json\`.}}"
    - To write a long form, copy its short form and add words to the copy; do not write the detail as a new sentence. If the detail needs different words, change the short form until the long form holds every word of it.
    - The long form must read correctly in the short form's place: a phrase stretches into a clause, a sentence into a paragraph, a paragraph into several.
    - Stretches nest: a long form may hold further stretches, each a further level of depth.
    - The short form is plain inline text on one line. Never put a stretch inside a code span, a code block, a table or a heading.
    - If other instructions require a closing block, such as a status block, make it the reply's last stretch, its short form a one-line gist of the block.
    - A reply that is already short needs no stretches.
    
    With each of the reader's messages you are told which stretches they opened. Do not assume they read a long form they did not open; if it matters to what they asked, say it again.`
    
    /**
     * Whether the session `id` is one of the half that carry a guide on trial in place of GUIDE, under
     * the `trialGuide` setting. The id alone decides (one bit of a hash of its characters), so a
     * session keeps one guide from its first request to its last, and the choice can be worked out again
     * from a transcript.
     */
    export function takesTrialGuide(id: string): boolean {
      let hash = 0x811c9dc5
      for (let i = 0; i < id.length; i++) hash = Math.imul(hash ^ id.charCodeAt(i), 0x01000193)
      // Mixed once more (MurmurHash3's last step), so that ids differing only in their last character still fall on both sides.
      hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b)
      hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35)
      return ((hash ^ (hash >>> 16)) & 1) === 1
    }
    
  • hooks/layout.tsGitHub
    Read the script
    // Lays out a paragraph that holds stretches, for a Client to draw: its markdown as rows of styled
    // runs, wrapped to the region's width, so a press can be matched to the phrase under it. Claude
    // Code draws every paragraph without a stretch with its own markdown.
    
    import { closesFence, codeSpan, drawnAs, isLinkable, isRule, openingFence, stretches } from './parse'
    import type { Segment, Stretch } from './parse'
    
    /** What a press on a pressable phrase does to its stretch. */
    export type Action = 'open' | 'close'
    
    export type Run = {
      text: string
      bold?: true
      italic?: true
      code?: true
      underline?: true
      dim?: true
      /** The colour of the words a stretch added. */
      tint?: string
      /**
       * The stretch a press acts on, and how. `isLeadIn` marks lead-in words: the words written just before
       * a link with no words of its own, and the punctuation glued after an empty short form, which a press
       * opens too. They stay a run apart from the link, so rows break where they would without it.
       */
      link?: { action: Action; key: string; isLeadIn?: true }
      /** Where a markdown link or a bare URL goes, drawn as a hyperlink. */
      href?: string
    }
    
    export type Row = Run[]
    
    /** How a row a line wrapped onto joins the row before it: what the break took out, and the lead's cells. */
    export type Continuation = { join: string; lead: number }
    
    // The rows a line wrapped onto, so a copy of several rows gives back the line as written.
    const continuations = new WeakMap<Row, Continuation>()
    
    /** How `row` continues the row before it, if a line wrapped onto it. */
    export function continuationOf(row: Row): Continuation | undefined {
      return continuations.get(row)
    }
    
    // Noncharacters frame a pressable phrase, a tinted word or an arriving word in composed text: Unicode
    // keeps them for a program's own use, where the Private Use Area holds icons such as Nerd Font's. A
    // start mark with no separator after it is read as a character, so a stray one still lets its line
    // be laid out.
    const START = '\ufdd0'
    const SEP = '\ufdd1'
    const END = '\ufdd2'
    const PHRASE_MARK = /[\ufdd0-\ufdd2]/
    /** What a pressable phrase adds around its label, none of it drawn: its start with the action and key it carries, and its end. For `replace`. */
    const PHRASE_FRAME = new RegExp(`${START}[^${SEP}]*${SEP}[^${SEP}]*${SEP}|${END}`, 'g')
    const TINT = '\ufdd3'
    const TINT_END = '\ufdd4'
    const ARRIVING = '\ufdd5'
    const ARRIVING_END = '\ufdd6'
    
    // A mark drawn on the letter before it, or a character no terminal draws, takes no cell.
    const ZERO_WIDTH = /[\p{Mn}\p{Me}\p{Default_Ignorable_Code_Point}]/u
    
    // A character drawn as a picture by default, such as 🚀, takes two cells; the first is U+231A, so
    // widthOf tests nothing below it. A flag is two regional indicators that take two cells together,
    // so each one keeps its single cell.
    const EMOJI = /(?!\p{Regional_Indicator})\p{Emoji_Presentation}/u
    
    // Where a row may break in text without spaces. Chinese and Japanese break between any two
    // characters. Korean spaces its words, so it breaks at spaces as Latin text does. Thai, Lao, Khmer
    // and Burmese write words without spaces, and a row breaks between words where Intl.Segmenter
    // finds them. Closing punctuation, a Japanese small kana, the long-vowel mark and a mark drawn on
    // the letter before it never start a row; opening punctuation never ends one.
    const UNSPACED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Bopomofo}\u3000-\u303f\uff00-\uffef]/u
    const SEGMENTED = /[\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u
    const NO_START = /[\p{Pe}\p{Pf},.:;!?,。、;:?!…·ぁぃぅぇぉっゃゅょゎゕゖァィゥェォッャュョヮヵヶーゝゞヽヾ々]/u
    const NO_END = /[\p{Ps}\p{Pi}]/u
    const SEGMENTER = new Intl.Segmenter(undefined, { granularity: 'word' })
    
    // The marks that start a markdown block on a line. The benchmark reads lines with the same ones.
    export const TABLE_ROW = /^\s*\|/
    export const HEADING = /^#{1,6}\s+(.*)$/
    export const QUOTE = /^>\s?(.*)$/
    export const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/
    
    /** A line's text without its tint and arriving marks, with each remaining character's tint and whether it is arriving. */
    type Line = { text: string; tints: (string | undefined)[]; arriving: boolean[] }
    
    /** `word` drawn in `colour`. */
    export function tint(colour: string, word: string): string {
      return `${TINT}${colour}${SEP}${word}${TINT_END}`
    }
    
    /**
     * `text` as what a growing or shrinking long form shows at one frame, marked as arriving line by line.
     * A `*` or `_` in it that opens italics and meets no closing mark is then not drawn, and the rest of
     * the arriving text on its line is italic: its closing mark may be in a word not shown at this frame.
     * A rule or a fence line stays bare, since `closeAfter` reads a long form's last line for one.
     */
    export function asArriving(text: string): string {
      const isBare = (line: string) => isRule(line) || openingFence(line) !== undefined
      return text.split('\n').map(line => (isBare(line) ? line : `${ARRIVING}${line}${ARRIVING_END}`)).join('\n')
    }
    
    /** Whether a word is markdown syntax rather than text: a bullet, a list number, a rule, a fence, a pipe, a heading mark. */
    export function isMarkup(word: string): boolean {
      return !HAS_WORDS.test(word) || /^\d+[.)]$/.test(word) || openingFence(word) !== undefined
    }
    
    /**
     * A pressable phrase for composed text: drawn as `label`, a press does `action` to stretch `key`;
     * `leadIn` marks lead-in words, which open it.
     */
    export function link(action: Action | 'leadIn', key: string, label: string): string {
      return `${START}${action}${SEP}${key}${SEP}${label}${END}`
    }
    
    /** Punctuation that ends a sentence at the end of a word, before any closing quote or bracket. */
    const SENTENCE_END = /[.!?]["'”’)\]]*$/
    /** Sentence-ending punctuation of scripts that write no space after it, so it can stand inside a word. */
    const UNSPACED_SENTENCE_END = /[。!?](?=[^。!?]*$)/u
    /** Markup a pressed phrase would cut in two: emphasis, a markdown link, HTML, a
  • hooks/look.tsGitHub
    Read the script
    // How a phrase the reader can press is marked: text marks that turn on or off one by one, and a
    // highlight. Shared by the hooks module, which also draws the toolbar, and the reply.
    
    import { contrastOn, isHex } from './contrast'
    import type { Hex } from './contrast'
    
    /** Every text mark a phrase can carry, in the order the toolbar shows them. */
    export const MARK_NAMES = ['bold', 'italic', 'underline', 'strikethrough', 'dim'] as const
    export type Mark = (typeof MARK_NAMES)[number]
    
    /** The highlight that puts each closed stretch on the colour its words take once open, blended 75% into the background. */
    export const TINTED = 'tinted'
    
    /** A highlight: one hex colour for every stretch, TINTED, or '' for none. */
    export type Highlight = Hex | typeof TINTED | ''
    
    /** The marks a pressable phrase carries and its highlight. */
    export type Look = { marks: Mark[]; highlight: Highlight }
    
    /** A look as a reply draws it: the hooks module has already replaced TINTED with '', and gives each stretch's own colour in ReplyProps.highlights. */
    export type DrawnLook = { marks: Mark[]; highlight: Hex | '' }
    
    /** The default: underlined, in the text's own colour. */
    export const DEFAULT_LOOK: DrawnLook = { marks: ['underline'], highlight: '' }
    
    export const textOf = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
    
    /**
     * A highlight as one spelling: TINTED, or a hex colour in lower case, so `#264F78` and `#264f78` are
     * one colour; anything else is none, as its luminance is unknown here and no text colour can be chosen
     * to read on it.
     */
    const highlightOf = (value: unknown): Highlight => {
      const text = textOf(value).toLowerCase()
      return text === TINTED ? TINTED : isHex(text) ? text : ''
    }
    
    /** Whether a highlight is one colour, for every stretch alike. */
    export const isColour = (highlight: Highlight): highlight is Hex => highlight !== '' && highlight !== TINTED
    
    /** The marks named in a list (commas or spaces, any case), in toolbar order, unknown names dropped. */
    export function marksOf(value: unknown): Mark[] {
      const names = textOf(value).toLowerCase().split(/[\s,;]+/)
      return MARK_NAMES.filter(mark => names.includes(mark))
    }
    
    /**
     * The look the options set. `marks` left empty keeps the default underline, so a highlight alone
     * adds to it; `none` takes every mark away. A value that names no mark (a typo) keeps the default
     * too, so stretches never lose their mark by accident. A hex highlight and `tinted` are read in
     * any case, and any other highlight is none.
     */
    export function lookOf(options: Record<string, unknown>): Look {
      const named = textOf(options.marks)
      const parsed = marksOf(named)
      const marks = named.toLowerCase() === 'none' ? [] : parsed.length > 0 ? parsed : DEFAULT_LOOK.marks
      return { marks, highlight: highlightOf(options.highlight) }
    }
    
    /** The `marks` setting that reads back as `marks`: `none` for none, as an empty one means the default. */
    export function marksSetting(marks: readonly Mark[]): string {
      return marks.length === 0 ? 'none' : marks.join(',')
    }
    
    /** A look held in state, checked: what the toolbar stored, or null when there is none. */
    export function storedLook(value: unknown): Look | null {
      if (typeof value !== 'object' || value === null || !('marks' in value) || !Array.isArray(value.marks)) return null
      if (!('highlight' in value) || typeof value.highlight !== 'string') return null
      return { marks: marksOf(value.marks.join(',')), highlight: highlightOf(value.highlight) }
    }
    
    /** Whether two looks draw a phrase the same. */
    export function isSameLook(a: Look, b: Look): boolean {
      return a.highlight === b.highlight && a.marks.length === b.marks.length && a.marks.every(mark => b.marks.includes(mark))
    }
    
    /** Whether a look draws its highlight on a run: only on plain text, leaving a coloured closer, code and a hyperlink alone. */
    export const drawsHighlight = (look: DrawnLook, isPlainText: boolean) => look.highlight !== '' && isPlainText
    
    /**
     * The text props a look gives a pressable phrase, whose run may be dim of its own (a link target).
     * The look's dim and highlight leave a coloured closer, code and a hyperlink inside the phrase alone.
     * On a highlight the text turns dark or light so it reads, and dim moves that colour toward the
     * highlight.
     */
    export function lookProps(look: DrawnLook, isPlainText: boolean, isDim = false) {
      const has = (mark: Mark) => look.marks.includes(mark)
      const isHighlighted = drawsHighlight(look, isPlainText)
      const isDimmed = isDim || (has('dim') && isPlainText)
      return {
        ...(has('bold') && { bold: true }),
        ...(has('italic') && { italic: true }),
        ...(has('underline') && { underline: true }),
        ...(has('strikethrough') && { strikethrough: true }),
        ...(isHighlighted && { backgroundColor: look.highlight, ...contrastOn(look.highlight, isDimmed) }),
        // As of Claude Code 2.1.302 dimColor draws the theme's grey whatever the colour, so on a highlight
        // contrastOn dims the colour chosen to read on it instead.
        ...(isDimmed && !isHighlighted && { dimColor: true }),
      }
    }
    
  • hooks/parse.tsGitHub
    Read the script
    // A reply is markdown in which `{{short|long}}` marks a stretch: the reader
    // sees `short`, and opening it puts `long` in its place. `long` may hold
    // further stretches. Code spans and fences are copied as written, so braces in
    // code never open a stretch; inside a long form, a fence's closing line may
    // carry the `}}` that closes the stretches around the block.
    
    export type Segment = string | Stretch
    
    export type Stretch = {
      /**
       * Names the stretch by its trimmed short form, each line break in it written ↵, and
       * its parents' (`cache › key`), so a stretch added elsewhere in the reply leaves
       * every other key as it was. A short form repeated among siblings takes `~2`, `~3`.
       */
      key: string
      short: string
      /** Undefined when no `|` was written: then there is nothing to open, and `short` is plain text. */
      long: Segment[] | undefined
      /** False while the reply streams and the closing braces have not arrived. */
      isClosed: boolean
    }
    
    type Frame = { stretch: Stretch; siblings: Map<string, number> }
    
    export const KEY_SEPARATOR = ' › '
    
    export function isOpenable(stretch: Stretch): boolean {
      return stretch.isClosed && stretch.long !== undefined
    }
    
    /** Whether a stretch is drawn as a link: openable, with its short form on one line, as a link cannot span lines. */
    export function isLinkable(stretch: Stretch): boolean {
      return isOpenable(stretch) && !stretch.short.includes('\n')
    }
    
    /**
     * How the terminal draws a stretch: as plain text when there is nothing to open, already open when
     * its short form spans lines, otherwise as a link.
     */
    export function drawnAs(stretch: Stretch): 'text' | 'open' | 'link' {
      if (!isOpenable(stretch)) return 'text'
      return isLinkable(stretch) ? 'link' : 'open'
    }
    
    /**
     * An open stretch's long form followed by its `closer`, after a space, or after `gap` when the long
     * form ends in a line text after it would change: a rule, which then reads as plain dashes, or a code
     * fence, which then no longer closes.
     */
    export function closeAfter(long: string, closer: string, gap: string): string {
      const trimmed = long.trimEnd()
      const last = trimmed.slice(trimmed.lastIndexOf('\n') + 1)
      const fence = openingFence(last)
      const endsInBlock = isRule(last) || (fence !== undefined && closesFence(last, fence))
    
      return endsInBlock ? `${trimmed}${gap}${closer}` : `${long} ${closer}`
    }
    
    /** Whether `line` is a rule: three or more of one of `-`, `*` and `_`, spaces between allowed. */
    export function isRule(line: string): boolean {
      return /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/.test(line)
    }
    
    /** The key of the stretch holding the one keyed `key`, or '' when no stretch holds it. */
    export function parentOf(key: string): string {
      return key.split(KEY_SEPARATOR).slice(0, -1).join(KEY_SEPARATOR)
    }
    
    /**
     * The code span at `i`: where it stops, past the next run of as many backticks or at the text's end,
     * and its backticks when it is still open there. `open` carries the backticks of a span opened on an
     * earlier line, whose close is then looked for from `i` on.
     */
    export function codeSpan(text: string, i: number, open?: string): { stop: number; open: string | undefined } {
      const run = open ?? /^`+/.exec(text.slice(i))?.[0] ?? '`'
      const end = text.indexOf(run, open === undefined ? i + run.length : i)
      return end === -1 ? { stop: text.length, open: run } : { stop: end + run.length, open: undefined }
    }
    
    export function parse(text: string): Segment[] {
      const root: Segment[] = []
      const stack: Frame[] = []
      const rootSiblings = new Map<string, number>()
    
      const write = (chunk: string) => {
        const frame = stack.at(-1)
        if (frame && frame.stretch.long === undefined) {
          frame.stretch.short += chunk
          return
        }
        const segments = frame?.stretch.long ?? root
        const last = segments.at(-1)
        if (typeof last === 'string') segments[segments.length - 1] = last + chunk
        else segments.push(chunk)
      }
    
      let i = 0
      while (i < text.length) {
        const frame = stack.at(-1)
        const isInShort = frame !== undefined && frame.stretch.long === undefined
        const isInLong = frame !== undefined && !isInShort
    
        const fenceStop = i === 0 || text[i - 1] === '\n' ? fenceEnd(text, i, isInLong) : undefined
        if (fenceStop !== undefined) {
          write(text.slice(i, fenceStop))
          i = fenceStop
          continue
        }
    
        if (text[i] === '`') {
          const { stop } = codeSpan(text, i)
          write(text.slice(i, stop))
          i = stop
          continue
        }
    
        if (text.startsWith('{{', i) && !isInShort) {
          const stretch: Stretch = {
            key: '',
            short: '',
            long: undefined,
            isClosed: false,
          }
          ;(frame?.stretch.long ?? root).push(stretch)
          stack.push({ stretch, siblings: new Map() })
          i += 2
          continue
        }
    
        if (isInShort && text[i] === '|') {
          frame.stretch.key = keyOf(frame.stretch.short, stack.at(-2), rootSiblings)
          frame.stretch.long = []
          i += 1
          continue
        }
    
        if (frame && text.startsWith('}}', i)) {
          frame.stretch.isClosed = true
          stack.pop()
          i += 2
          continue
        }
    
        write(text[i] ?? '')
        i += 1
      }
    
      return root
    }
    
    function keyOf(short: string, parent: Frame | undefined, rootSiblings: Map<string, number>): string {
      // A line break in a key would split the link's markup across rows in `layout`; ↵ keeps the key apart
      // from the same words on one line, which a space would not.
      const name = short.trim().replaceAll('\n', '↵')
      const siblings = parent?.siblings ?? rootSiblings
      const seen = (siblings.get(name) ?? 0) + 1
      siblings.set(name, seen)
      const own = seen === 1 ? name : `${name}~${seen}`
    
      return parent ? `${parent.stretch.key}${KEY_SEPARATOR}${own}` : own
    }
    
    /**
     * Where a fenced code block opening at `start` ends (past its closing line, or where the braces after
     * its closing fence begin, inside a long form), or undefined when no fence opens there.
     */
    function fenceEnd(text: string, start: number, 

Read the script before you install anything that runs on your machine. This is the one part of a plugin that acts without being asked.

@pro-vi
Ships withcc-stretch

Claude writes a lot. Now you can read a little. Replies arrive short. Click a linked phrase and it grows right where it stands. Click « and it shrinks back. Claude is told which parts you opened, so it doesn't assume you read the rest.

Stars on GitHub

Momentum

stars in total
438
Star history of pro-vi/cc-stretch on GitHub, a chart by star-history.com

More plugins that ship hooks.

sloptrim

sloptrim

Detects AI-writing patterns in prose files your agent saves, and includes a skill that helps humanize text and remove AI-sounding phrasing. Runs locally using only the Python standard library, with no network access or model.

1 skill7 hooks436
@seyedehsanhadi@seyedehsanhadi
Install Plugin
genshijin

genshijin

Makes Claude's replies terse to cut token use, with skills for short commit messages, one-line PR review comments, compressing memory files like CLAUDE.md, and delegating to small subagents. Japanese and English supported.

7 skills+3336
@interfacex-co-jp@interfacex-co-jp
Install Plugin
pordee

pordee

A Claude Code plugin that makes the agent reply in short, simple Thai, dropping polite particles and hedging words, to cut output tokens while keeping technical accuracy. Includes a command that shows real session token usage.

2 skills4 hooks332
@kerlos@kerlos
Install Plugin
awesome-claude-output-styles

awesome-claude-output-…

Make Claude talk like a human: 17 installable output styles for Claude Code, built on credited methodologies.

1 skill+2152
@smixs@smixs
Install Plugin
notion-doc

notion-doc

Make your AI agent write documents like Notion, not like an AI. Ask an AI agent to create a document and you'll often get the same kind of output: a purple gradient hero, emoji-heavy headings, cards with drop shadows.

1 skill1 hook106
@heyman333@heyman333
Install Plugin

Questions about the hooks in cc-stretch.

Which coding agents can use the hooks in cc-stretch?
The hooks in cc-stretch install in Claude Code and Cursor: each runs Claude Code hooks from .claude/settings.json, so copy the hooks there.