Ace-inline filter demo
This page demonstrates the capabilities of the new and experimental Ace inline Moodle filter. This filter operates on the rendered HTML of a page, so its use requires that teachers be able to edit content in HTML. See the filter documentation for details.
The original HTML of (most of) this page can be inspected by importing the description 'question' demoaceinline.xml into the question bank on your own Moodle server and opening it for edit in HTML mode. Or you can simply open that link directly in your browser, if you're able to read the XML itself and identify the relevant embedded HTML within it (essentially, all the blue text).
To revert any edited code to its original version just reload the page.
Note: the Ace inline filter requires a new version of CodeRunner that provides a sandbox web service (version 4.2.1 or later).
Highlighting code
The simplest use of the filter is to let the Ace editor do syntax colouring of code. This is achieved by putting the code into a HTML <pre> element with the class ace-highlight-code. The default language is python; if you want another language you should add to the pre element an attribute like data-lang="java". Here are two examples, the first in Python, the second in Java.
A python example
print("Some squares") for i in range(10): print(i, i ** 2)
A Java example
public class hello { public static void main(String[] args) { System.out.println("Hello world!"); } }
Note: for strict HTML5 compliance, all non-standard element attributes must be prefixed with 'data-', which is why the language attribute is called 'data-lang' rather than just 'lang'. However, if you don't care about such compliance, you can drop the prefix; the code will still work but will not pass HTML5 validator checks. All code in this test/demo question use the full 'data-' form for attributes.
Options for highlighting
Line numbers are not shown by default, but an attribute data-start-line-number can be added to set the line number to use on the first line. Its default value is none, resulting in no line numbers being displayed. If non-none, the usual value is '1', but other values can be used in special cases, for example if code is broken into two separate highlighted segments.
There is also an optional attribute data-font-size to set the font size within the Ace editor.
The following example shows the Java hello world program with line numbers starting at 5 and a font-size of 16 pts.
public class hello { public static void main(String[] args) { System.out.println("Hello world!"); } }
Making code interactive
Note: to run the examples that follow you need to be logged into this site as a user. Also, because this site is open to the world and has been subject to abuse, there is an additional tight constraint limiting you to at most 20 submissions per hour. The normal rate limit, which can be set to any value by the system administrator, is 200 submissions per hour.
If the class of the HTML <pre> element containing the code is instead set to ace-interactive-code, a Try it! button is added below the Ace editor panel. When clicked, the code is sent to the CodeRunner sandbox (usually a Jobe server) for execution and the result is displayed below the button. The code can be edited and re-run an arbitrary number of times.
Here are firstly the same two examples from above, but with class ace-interactive-code, and then C and C++ hello world programs. An extra blank line is being displayed in these cases by moving the terminating '</pre>' onto a new line rather than putting it hard up against the last non-whitespace character in the code. This makes it clear that all the editable code is being displayed, but you might prefer not to do this - your call.
A python example
print("Hello squares") for i in range(10): print(i, i ** 2)
A Java example
public class hello { public static void main(String[] args) { System.out.println("Hello world!"); } }
Hello world in C
#include <stdio.h> int main() { puts("Hello world!"); }
Hello world in C++
#include <iostream> using namespace std; int main() { cout << "Hello world" << endl; }
Providing standard input
Users cannot provide standard input to ace-interactive-code samples, as the facility is intended for demonstrating code rather than for writing useful programs. In the unlikely case that the code does try to read standard input, however, the question author can provide a standard input string using the attribute data-stdin. Since HTML5 allows multiline literal strings, the stdin stream can be multiline too.
The following example shows a Python program that reads standard input until EOF. The stdin attribute here is
Chaos reigns within. Reflect, repent, and reboot. Order shall return.
while 1: try: print(input()) except EOFError: break
Providing files
As with reading stdin, it is not usual to use 'ace-interactive-code' examples to read files. However, it is possible to define an attribute data-files which is a JSON object that provides a map from filename to file contents. Since JSON strings cannot contain newline characters, they must be represented within the JSON as '\n'.
Here's a trivial example, with a 2-line file 'blah.txt':
print(open("blah.txt").read())
Other ace-interactive-code options
Other attributes that can be used with ace-interactive-code elements are:
Attribute | Meaning |
---|---|
data-button-name |
Sets the label to use for the button instead of 'Try it!' |
data-ace-lang |
If the Jobe language used to run the code differs from the language being displayed (e.g. if an R program is wrapped by python) this attribute can be used to explicitly set the Ace editor's language mode. |
data-start-line-number |
Can be set to 'none' to suppress line numbers or to an integer to start numbering with the given value |
data-readonly |
If set (to any value) the supplied code cannot be edited by the user |
data-code-mapper |
The name of a global JavaScript function (i.e. an attribute of the window object) that takes as a parameter the code from the Ace editor and returns a modified version. This can be used to perform arbitrary transformations of the code the student is writing into some other program. If prefix or suffix code is supplied (see below) it is added after the code-mapper has been used. |
data-prefix |
Defines code that will be inserted before the code from the Ace editor (so the student doesn't see it). An extra newline is not inserted between the prefix and the visible code - you must insert it explicitly if you want one. |
data-suffix |
Defines code that will be inserted after the code from the Ace editor (so the student doesn't see it). An extra newline is not inserted between the visible code and the suffix - you must insert it explicitly if you want one. |
data-html-output |
If set (to any value) the output from the program is interpreted as raw html to insert into the DOM, rather than being escaped and displayed in a <p> element. |
data-params |
A JSON-encoded object defining sandbox params, such as cputime, memorylimit. Rarely useful. |
data-max-output-length |
The limit to the displayed length of stdout and stderr strings. Strings longer than this are truncated prior to display. Default: 10,000. |
A simple data-html-output example
The following example shows how the data-html-output option works. It's only rarely useful in isolation but in conjunction with data-code-mapper and/or data-prefix and data-suffix it can be used by question authors to provide arbitrary output. The following example also changes the button name.
print("<h2>I'm a heading</h2>") print("<ol><li>Bullet 1</li><li>Bullet 2</li></ol>")
A simple use of code-mapper
In this case we define (using a <script> element) a function called doubler that returns its parameter concatenated onto itself. The <pre> element that wraps the following code has the attribute data-code-mapper set to 'doubler'.
print("Hello world!")
A simple use of data-prefix
In the above example showing the use of stdin, the input() function was called and the result printed. But if students are using input() interactively, they expect to see what they enter from the keyboard echoed to the screen. To achieve such an effect in Python, prefix code could be added that simulates this echoing. For example, here's a program that asks the student for their name and age and prints a message telling them their age next year.The data-stdin attribute of the <pre> element has been set to contain the two lines 'jeremy' and '11'.
name = input("What's your name? ") age = int(input("How old are you? ")) print(f"Hi {name}, next year you'll be {age + 1}")
Displaying matplotlib images
By using the data-code-mapper option (and/or data-prefix and data-suffix) in conjunction with html-output it is possible, with some difficulty, to define an ace-interactive-code block that will let students run matplotlib code and display both the textual output from the question and any output images. Here is an example (inspect the HTML at your peril):
import matplotlib.pyplot as plt import numpy as np # Generate some text output print("I am a line of output") print("And so am I") # Now the graph plotting axes = plt.axes() xs = np.linspace(0, 720, 200) ys = np.sin(2 * np.pi * xs / 360) axes.plot(xs, ys) axes.set_title("y = sin(x)") axes.set_xlabel('x (degrees)') axes.set_ylabel('y') axes.grid() plt.show()