code

A canvas environment that shows code, written as lines chunks joined into one file.

codeNode
On this page
A code canvas titled fit.py: a Python function fitting a line with NumPy, and the two lines calling it highlighted.A code canvas titled fit.py: a Python function fitting a line with NumPy, and the two lines calling it highlighted.

#Chunks and the assembled file

code holds code as lines chunks. The environment joins the chunks on show, in the order written, into one file and numbers that file's lines, so a line number counts what the reader can see at that moment. Nothing addresses a line by its number: a cue, a highlight or an error marker belongs to a chunk, and stays on that chunk's lines when another chunk arrives above it.

language is the implicit attribute, so code:python{…} highlights as Python. title is the file name in the toolbar; unwritten, the toolbar shows the language's conventional entry file, main.py or index.js.

Each chunk's body is dedented to its own margin, so a chunk can sit at any depth in the source. A chunk that continues a block states its depth with indent, its implicit attribute, in levels of four spaces. A blank line at the start of a chunk is kept and one at its end is dropped; lines{} is a chunk of one blank line.

code:python{
    lines{
        def mean(xs):
            total = sum(xs)
    }
    lines:1{
        return total / len(xs)
    }
}
A Python code canvas that loads three islands’ areas and species counts into NumPy arrays, takes their logarithms and fits a line to them.A Python code canvas that loads three islands’ areas and species counts into NumPy arrays, takes their logarithms and fits a line to them.
code{
    lines{
        import numpy as np

        # Baltra, Bartolomé and Santa Cruz: area in km² and plant species counted
        area = np.array([25.09, 1.24, 903.82])
        species = np.array([58, 31, 444])

        log_area = np.log10(area)
        log_species = np.log10(species)
        z, log_c = np.polyfit(log_area, log_species, 1)
    }
}(
    language: python
)

#Bringing chunks in

A cue wraps chunks as it wraps any other mark. A chunk cued in at step 1 joins the file there, fading in over the cue's in-duration, and every line below it moves down. hidden leaves a chunk out of the file, and is animatable.

cue.write types the chunks it wraps, character by character from in, at speed characters a second (35 unwritten), with a caret on the line being typed. The typing lasts as long as the text takes at that speed, so a longer chunk types for longer. out deletes it again, from the end.

Three frames of a Python code canvas: a polyfit line alone, then a print line beneath it half typed, then typed in full.Three frames of a Python code canvas: a polyfit line alone, then a print line beneath it half typed, then typed in full.
code:python{
    lines{
        z, log_c = np.polyfit(log_area, log_species, 1)
    }
    cue.write{
        lines{
            print(z)   # 0.41
        }
    }(
        in: 1
    )
}

#Marking lines

emphasis washes every line of its chunk for as long as the chunk is shown. Wrapped in a cue.highlight, a chunk is washed once instead, from the cue's at for its duration; cue.spotlight does the same here. Either wash covers the chunk's blank lines too.

Tip
A blank line that separates a highlighted chunk from its neighbour belongs at the start of the chunk after it, or in a lines{} of its own: the highlight then marks only the lines the reader is meant to look at.

error-lines puts the gutter's error marker on lines counted from 1 within the chunk, and error-message sets a diagnostic at the end of the first of them, or of the chunk's first line when no line is marked. added-lines and removed-lines wash lines green and red, counted the same way, to show an edit.

code:python{
    lines{
        total = 0
        for x in readings:
            total += x
        print(totl)
    }(
        error-lines: 4
        error-message: NameError: name 'totl' is not defined
    )
}
code:python{
    lines{
        mean = total / len(xs)
        mean = total / max(len(xs), 1)
    }(
        removed-lines: 1
        added-lines: 2
    )
}

#Splicing values into code

{{…}} reaches a chunk's body as it reaches prose, before the code is read, so an @let constant or a column of an @data dataset written in the source splices into the code.

Warning
A column arrives as its cells joined by commas, unquoted: a list of numbers is a Python or JavaScript list literal as it stands, and a column of words is not.
@data#survey{
    island     | area
    Baltra     | 25.09
    Bartolomé  | 1.24
    Santa Cruz | 903.82
}

scene{
    The areas come from the survey table.
}[
    code:python{
        lines{
            area = np.array([{{#survey.area}}])
        }
    }
]

A dataset read from an attachment has no rows until the internote is read, so its columns cannot be spliced into code:

@data#survey:galapagos-plants-1973.csv

scene{
    The areas come from the attached survey.
}[
    code:python{
        lines{
            area = np.array([{{#survey.area}}])
        }
    }
]

[expression]`{{#survey.area}}` resolves to the bound value `#survey.area`, which depends on `#survey.area`, which cannot be written into a literal body

#Output as authored content

Nothing in a code environment produces canvas content. Unless it is runnable nothing executes at all, and a run prints into the environment's console, never onto the canvas: no code plots, feeds a graph or generates data. An internote therefore carries no kernel, package versions or execution state, and reads years later as its author left it.

A result the reader should see is authored: a comment, or a later chunk giving what an interpreter prints. It is a claim like any number in the prose, so it is quoted from a run rather than predicted, as Checking a document's claims has it. The one way to keep a number the same in the code and in the argument is to declare it once, as an @let constant, and splice it into both.

code:python{
    lines{
        z, log_c = np.polyfit(log_area, log_species, 1)
        print(z)   # 0.41
    }
}

#Editing and running

editable lets the reader type into the code. Their first keystroke copies the file as it stands into a copy of their own, kept between visits; from then on the cues stop acting on the environment and its highlights and markers step aside, until the toolbar's Reset code discards the copy. A later environment with continue: #id starts from the reader's copy of that one.

runnable puts a Run button in the toolbar. Only a signed-in reader can run code. Run waits until the reader is on the scene's last step and its cues have finished, so it never runs half-written code; a reader's own copy can run at any time.

Warning
runnable needs an explicit language of python, javascript or c; in any other, or with auto, the Run button is not shown.

A run executes the setup chunks, in source order, followed by exactly what the editor shows. A setup chunk is never displayed and ignores cues and hidden, so what a run computes does not depend on how far the reader has got: imports and fixture values go there. The run happens in a disposable sandbox with no network access and is stopped after 30 seconds. Python has numpy, pandas, statsmodels and matplotlib beside the standard library; JavaScript runs on Node with its built-in modules; C is compiled by gcc with AddressSanitizer. Nothing else can be installed.

The console folds out of the footer and shows the text the run writes to stdout and stderr. When the run fails, the line its error names gets the error marker and the message, as an authored error-lines would, provided that line is one the editor shows.

A runnable, editable Python code canvas, its toolbar carrying the Run control.A runnable, editable Python code canvas, its toolbar carrying the Run control.
code:python{
    lines{
        import statistics
    }(
        setup
    )
    lines{
        area = [25.09, 1.24, 903.82]
        print(statistics.mean(area))
    }
}(
    title: islands.py
    editable
    runnable
)

#Attributes

languageImplicit
The language the code is highlighted as, and the mark beside the file name; Run needs python, javascript or c.
autojavascripttypescriptpythonjavacsharprubygocppphpswiftplaintexthtmlcssjsonxmlbashsqlkotlinrustscaladartluahaskellelixirclojureerlangperlrmatlabgroovyobjective cvisual-basicassemblyfortrancobolfsharpocamlpowershellshellyamlmarkdowngraphqlprotobufchalkpostgrespostgresqlsassscssotherjstspycsc#rbc++ktrsshhsexscljcljserlplmvbvbsasmf90f95f03f08f15f18cobcblfsfsifsxmlmlips1psm1ymlmdgqlprotopgpsqltxttextplainobjc
Also written: langCan be written as shorthand: code:value
Defaultauto
title
The file name in the toolbar, and the file a run's traceback names.
Also written: name, filename, file-name, file
editable
Lets the reader type into the code, keeping their own copy between visits.
Defaultfalse
runnable
A Run button in the toolbar for signed-in readers, executing the code in a sandbox with no network.
Defaultfalse
show-line-numbers
The line-number gutter, counting the lines on show.
Also written: line-numbers
Defaulttrue
wrap
Whether soft wrap is on when the environment opens.
Defaultfalse
continue
An earlier code environment whose reader state this one starts from.

#Allowed content

#Allowed in

#Examples

A Python code canvas titled greet.py, holding a two-line function that greets a name.A Python code canvas titled greet.py, holding a two-line function that greets a name.
code{
    lines{
def greet(name):
    return f"Hello, {name}!"
    }
}(
    language: python
    title: greet.py
)
Three frames of the first step: one line of Python, then a second line fading in beneath it.Three frames of the first step: one line of Python, then a second line fading in beneath it.
code{
    lines{
x = 1
    }
    cue{
        lines{
y = x + 1
        }
    }(
        in: 1
    )
}(
    language: python
)
A JavaScript code canvas titled mean.js, a function that averages an array.A JavaScript code canvas titled mean.js, a function that averages an array.
code{
    lines{
function mean(values) {
    const total = values.reduce((a, b) => a + b, 0);
    return total / values.length;
}
    }
}(
    language: javascript
    title: mean.js
)

#Writing guidance

  • Selecting canvas content — A mark belongs on the canvas when seeing it changes what the reader understands, and the detail holds as a picture on its own.
  • Checking a document's claims — Every other number worked out, every output quoted from a run, every dataset read and attached whole, every external fact checked and cited, or cut.

Last updated