color code python or R code in moodle XML

Summary

This postmortem analyzes why syntax‑highlighted R/Python code produced by exams2html() loses all color when exported to Moodle XML via exams2moodle(). The issue stems from Moodle’s limited support for HTML/CSS in question text and the way the r‑exams package sanitizes output for LMS compatibility.

Root Cause

  • Moodle’s XML format strips or ignores CSS classes used for syntax highlighting.
  • exams2moodle() intentionally removes inline styles to avoid Moodle rejecting the question.
  • Moodle’s built‑in code formatting uses plain <pre> blocks without highlighting.
  • The r‑exams pipeline does not embed external CSS or JS, which Moodle would not load anyway.

Why This Happens in Real Systems

  • LMS platforms often sanitize HTML aggressively to prevent security issues.
  • External CSS/JS is typically blocked in question text.
  • Syntax highlighting libraries (e.g., highlight.js, prism.js) require scripts Moodle does not execute.
  • Exporters like r‑exams must target the lowest common denominator to ensure imports do not fail.

Real-World Impact

  • Students see uncolored, harder‑to‑read code in Moodle quizzes.
  • Instructors lose pedagogical clarity when teaching programming concepts.
  • Debugging or comprehension questions become more error‑prone.
  • Courses relying on code literacy experience reduced exam usability.

Example or Code (if necessary and relevant)

Below is a minimal example of what Moodle receives—note the absence of styling:

x <- 1:10
mean(x)

How Senior Engineers Fix It

Senior engineers typically apply one of these strategies:

  • Use Moodle’s built‑in syntax highlighter by wrapping code in:
    • ```{.language-r} (if the theme supports it)
  • Enable the Moodle “Syntax Highlighting” filter (requires admin rights).
  • Switch to the STACK or CodeRunner question types, which support proper highlighting.
  • Embed code as an image when formatting fidelity is critical.
  • Patch r‑exams templates to inject Moodle‑compatible <pre class="prettyprint"> blocks (works only if the Moodle theme loads Google Prettify).

Why Juniors Miss It

  • They assume HTML rendering is consistent across platforms, which is rarely true.
  • They expect LMS systems to behave like modern browsers, but Moodle sanitizes heavily.
  • They do not realize that r‑exams exporters intentionally strip styling for compatibility.
  • They overlook that syntax highlighting requires JavaScript, which Moodle question text does not execute.

Leave a Comment