kmail.at
contact

elsewhere

EnglishEN
← learning

gradio · difficulty ◆◆

gradio Code — a syntax-highlighted pane that reads or accepts source

language= picks the grammar, interactive= picks the direction — and Gradio strips your string before it reaches the pane.

Gradio's code pane highlights 28 languages, 13 of them SQL dialects — and every one of those SQL snippets still downloads as file.txt.

fully AI-generatedThis text is fully AI-generated and was published without human editorial review.

2026-10-26 · 5 min read

$ gr.Code()
3.21.0
Introduced

14 Mar 2023, PR #3421

28
Languages

13 are SQL dialects; None means no grammar

22
Constructor params

gr.Code() signature in 6.30.0

4
Event listeners

change, input, focus, blur

What it does

gr.Code is a CodeMirror 6 editor wrapped in a Gradio component. Give it a value and a language from gr.Code.languages and it renders highlighted source with a line-number gutter and Copy/Download icons in the corner. Set interactive=True and it becomes an input, handing your listener the whole document as a plain str. It is not a Textbox with nicer fonts: it has its own gutter, fold gutter, wrapping, a max_lines cap and an update payload that can switch languages live. And it ships zero language detection — language=None draws bare, unhighlighted text.

Why it matters

Every LLM or codegen demo ends in source. Markdown fenced blocks are fine in a README and wrong in a demo: no line numbers, no copy button, no editing, no way to stream a half-written file. gr.Code gives you the pane a developer already expects, in one line, with the same str type on both sides of the event — so generate → review → fix loops need no adapter code. It is the difference between showing code and shipping a tool that works on code.

Example

$ import gradio as gr

def write_validator(field: str) -> str:
    return f'''def validate_{field}(value: str) -> bool:
    """Reject empty or whitespace-only input."""
    return bool(value and value.strip())
'''

with gr.Blocks(title="Validator generator") as demo:
    gr.Markdown("## Generate a validator\nType a field name, get a tested stub.")
    with gr.Row():
        field = gr.Textbox(label="field name", value="email")
        run = gr.Button("Generate", variant="primary")
    out = gr.Code(label="generated validator", language="python", lines=12)

    run.click(write_validator, inputs=field, outputs=out)

demo.launch(prevent_thread_lock=True)
* Running on local URL:  http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.

Rendered UI: an H2, then one Row holding a Textbox labelled "field name" (prefilled "email") and a primary Button "Generate", then a Code pane labelled "generated validator". Component tree from /config on 6.30.0: ['markdown', 'row', 'textbox', 'button', 'form', 'code'] — the Row is wrapped in a form because it only contains inputs. After the click the pane shows, with line numbers 1–3 in the gutter and Copy + Download icons top-right:

def validate_email(value: str) -> bool:
    """Reject empty or whitespace-only input."""
    return bool(value and value.strip())

Verified end to end: gradio_client calling /write_validator('email') returned exactly that string, and the served page showed the same three lines.

Measured, not assumed: with value=None the pane renders its label but no editor at all — 0 elements with .cm-editor in the DOM until the first value arrives. If the layout looks collapsed on first load, that is why. Also note the triple-quoted return string: the leading newline is what makes the snippet start flush left, because postprocess would strip it otherwise.

$ import ast
import gradio as gr

with gr.Blocks() as demo:
    src = gr.Code(
        value="import os\nimport json\n\n\ndef load(path):\n    return json.loads(open(path).read())\n",
        language="python", label="review this file", lines=10, interactive=True)
    verdict = gr.Markdown("waiting for edits…")

    def review(code: str) -> str:
        try:
            tree = ast.parse(code)
        except SyntaxError as e:
            return f"**SyntaxError** line {e.lineno}: {e.msg}"
        imports = [a.name for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names]
        return f"parsed OK · {len(imports)} import(s): {', '.join(imports)} · {len(code.splitlines())} lines"

    src.change(review, inputs=src, outputs=verdict)

demo.launch(prevent_thread_lock=True)
* Running on local URL:  http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.

Rendered UI: an editable code editor labelled "review this file" (its .cm-content carries contenteditable="true"; the read-only variant serves contenteditable="false" plus aria-readonly="true") above a Markdown block. On the untouched file it reads: "parsed OK · 2 import(s): os, json · 6 lines". Delete the indented return line and the Markdown flips to "**SyntaxError** line 5: expected an indented block after function definition on line 4" — verified by calling the same review() function on the broken source.

Event behaviour measured in headless Chromium: six characters typed at 350 ms intervals produced six .input events but only five .change events, with the last .change landing when focus left the editor. Handlers receive the entire document as str (len=42 for the edited sample), never a diff.

.change on Code coalesces rapid edits and also fires on blur; .input mirrors every keystroke. Use .change for parsing and .input for character counters. The interactive=True is what makes it an editor at all — an output-only Code is read-only.

$ import time
import gradio as gr

with gr.Blocks() as demo:
    fmt = gr.Radio(["yaml", "json"], value="yaml", label="format")
    go = gr.Button("Generate config", variant="primary")
    out = gr.Code(label="config", lines=6)

    def generate(fmt: str):
        if fmt == "yaml":
            parts = ["service:\n", "  name: api\n", "  replicas: 3\n"]
            lang = "yaml"
        else:
            parts = ['{"service": ', '{"name": "api", ', '"replicas": 3}}']
            lang = "json"
        acc = ""
        for chunk in parts:
            acc += chunk
            time.sleep(0.3)
            yield gr.Code(value=acc, language=lang)

    go.click(generate, inputs=fmt, outputs=out)

demo.launch(prevent_thread_lock=True)
* Running on local URL:  http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.

Rendered UI: a Radio labelled "format" (yaml selected), a primary Button "Generate config", and a Code pane labelled "config". Streaming the yaml branch leaves the pane on:

service:
  name: api
  replicas: 3

with data-language="yaml" on .cm-content. Switch the radio to json, click again, and the same pane ends on {"service": {"name": "api", "replicas": 3}} with data-language="json" — the returned gr.Code(language=...) re-highlights in place, so the language is updatable at runtime.

The accumulator is the whole trick. Written the naive way — `yield chunk` three times — the pane showed only the last chunk (`replicas: 3`), because each update replaces the document instead of appending to it. Verified in the browser against 6.30.0.

$ import gradio as gr

def tidy(code: str) -> str:
    return "\n".join(line.rstrip() for line in code.splitlines() if line.strip())

with gr.Blocks() as demo:
    tidy_btn = gr.Button("Tidy")
    code = gr.Code(value="x=1   \n\n\nprint( x )", language="python",
                   label="messy snippet", lines=6, buttons=["copy", tidy_btn])
    tidy_btn.click(tidy, inputs=code, outputs=code)

demo.launch(prevent_thread_lock=True)
* Running on local URL:  http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.

Rendered UI: a single code pane labelled "messy snippet" showing x=1 / (blank) / (blank) / print( x ), with a Copy icon in the pane's top-right corner and a "Tidy" button beside it. No Download icon — passing buttons=["copy", Button] replaces the default ['copy','download'] list. Clicking Tidy rewrote the pane to:

x=1
print( x )

Verified in headless Chromium: the corner showed ['Copy'] plus the named "Tidy" button, and the click cleared the trailing spaces and blank lines.

buttons takes strings ('copy', 'download') and/or real gr.Button objects; each Button keeps its normal .click wiring, so a formatter, a linter or a "send to model" action can live on the pane itself instead of in a separate Row.

Common flags

language
One of gr.Code.languages — 28 entries at 6.30.0, 13 of them SQL dialects. None means no grammar at all (plain text, no guessing). Anything else raises ValueError: "Language rust not supported." at construction.
interactive
True makes the pane an input (contenteditable="true"); False/None leaves it read-only with aria-readonly="true". Left unset, Gradio infers read-only for an output-only pane.
lines / max_lines
lines is the floor (default 5 renders an 84 px scroller), max_lines the ceiling; beyond it the pane scrolls internally instead of stretching the page.
show_line_numbers
Default True. False empties the gutter rather than removing it — the .cm-gutters element still exists in the DOM, which matters if your CSS targets it.
wrap_lines
False scrolls horizontally. True switches .cm-content to white-space: break-spaces so long lines fold inside the pane.
buttons
Defaults to ['copy','download'] in the served config even though the signature says None. Pass ['copy'] to drop the download icon, or a gr.Button to add your own action.
value
A str, or a callable that is evaluated once at page load. Tuples (filename, code) raise ValueError since 5.0 — read the file yourself and return its text.

History

A code pane lands in 3.21.0

gr.Code shipped on 14 March 2023 in Gradio 3.21.0 (PR #3421, written by pngwn), the same release that gave Chatbot audio/video/image support and brought shareable themes. Before it, the standard trick was a gr.Textbox or a fenced block inside gr.Markdown: no line numbers, no copy button, nothing editable.

Three years of small cuts, not a rewrite

The component has been patched rather than redesigned: SQL grammars in 4.18.0, the tuple-value deprecation in 5.0.0-beta.0, max_lines in 5.0.0-beta.2, show_line_numbers in 5.18.0, Jedi-backed Python autocomplete in 5.23.0, LaTeX in 5.25.0. The wrapper's CSS class, .codemirror-wrapper, is unchanged from 3.21.0 to 6.30.0 — I diffed the frontend bundles of both wheels to check.

Under the hood

What renders, and what your string goes through

Code.postprocess() is four lines: None passes through, tuples raise, everything else is value.strip(). The frontend then mounts CodeMirror 6 (@codemirror/state + view) into a .codemirror-wrapper — the same class name since 3.21.0 — derives contenteditable and aria-readonly from the interactive flag, and writes the grammar to a data-language attribute on .cm-content; token spans are produced client-side, which is why language=None has literally no spans. The Copy and Download icons are rendered outside the editor, in the component's corner container, which is also where custom buttons in buttons=[...] land and why they keep normal Gradio .click wiring. Both input and change post the full document as a str to the queue, so every event on a 5,000-line file is a 5,000-line JSON payload — use a button or your own client-side debounce for large files.

Fun facts

Pros & cons

pros

  • + One component covers both directions: viewer and editor, str in, str out, no adapters
  • + Real editing UX in one line: gutter, line numbers, copy/download, folding, optional Jedi autocomplete
  • + Language is updatable at runtime — return gr.Code(language="json") and the pane re-highlights in place

cons

  • − No language auto-detection: leave language unset and you get unhighlighted text, even for obvious Python
  • − postprocess strips the string, so a deliberate leading blank line or an indented first line quietly disappears
  • − No append mode for streaming, and every update ships the whole document

Takeaways

  1. 1Always set language= explicitly — None is plain text, not auto-detect
  2. 2interactive=True for an editor, leave it unset for a read-only output pane with Copy/Download
  3. 3Accumulate first, then yield the full document — Code replaces rather than appends
  4. 4Do not rely on postprocess for formatting; it strips your string
  5. 5Put actions on the pane with buttons=[gr.Button('Tidy')] instead of building a Row underneath

Related commands

archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →

← all learning