Klipper macros: parameters, variables and five macros you can copy

By Sina Esfahani, OmniTechs · Published 27 November 2026

A Klipper macro is a [gcode_macro NAME] section in your printer configuration. Its gcode: lines become a new command you can call from the console, the slicer or a screen. Before running them, Klipper treats the lines as a Jinja2 template: { } inserts a value and {% %} adds conditions and loops.

You read what was passed in through params, keep state in variable_ options and read the printer's state through printer. One rule causes most confusion: Klipper evaluates the whole macro first and only then runs its commands, so a macro never sees the result of its own commands (Klipper).

Write and test a macro in this order:

  1. Add a [gcode_macro NAME] section to printer.cfg or an included file; any digits go at the end of the name.

  2. Start gcode: at the left edge and give every line after it, up to the next line in square brackets, two leading spaces.

  3. Read arguments as params.NAME|default(value)|float: names arrive in upper case and always as text.

  4. Keep state in a variable_name option (lower case) and change it with SET_GCODE_VARIABLE.

  5. Read printer state from printer plus a section name, such as printer.extruder.temperature, using the fields in Klipper's Status Reference.

  6. Move a step into a second macro whenever it must see the result of an earlier command.

  7. Save, send RESTART, run the macro from the console and read the error line there or in klippy.log.

What a macro error message means

Macro errors and their fixes

Message texts from Klipper's source code (gcode.py, gcode_macro.py, extruder.py) and its Command Templates and Config Reference pages, read on 27 November 2026.
What you seeWhat it meansWhat to do
Unknown command:"HEAT_SOAK"Klipper did not load the macro: a typo, a file that is not included, or a digit in the middle of the nameFix the name or the [include] line, then RESTART
Error loading template ... line 4A syntax error in the template, such as an {% if %} without {% endif %}Correct that line and RESTART
Error evaluating 'gcode_macro HEAT_SOAK:gcode': ...The template failed when you ran it, often text used as a number or a misspelt printer fieldConvert parameters with int or float; check the field in the Status Reference
Unknown gcode_macro variable 'target'SET_GCODE_VARIABLE names a variable the macro does not declareAdd variable_target to the macro, in lower case
Unable to parse 'textured' as a literalVALUE= expects a Python literal; plain text needs quotesSend VALUE='"textured"'
Macro HEAT_SOAK called recursivelyThe macro called itselfRepeat work with a delayed_gcode instead
Existing command 'PAUSE' not found in gcode_macro renamerename_existing points at a command that is not loadedAdd the section that provides it, here [pause_resume]
Extrude below minimum tempThe nozzle is below min_extrude_temp, 170 °C by defaultHeat first, or guard the macro (see the filament macro below)
Extrude only move too long (100.000mm vs 50.000mm)A pure extrude or retract is longer than max_extrude_only_distance, 50 mm by defaultSplit the move or raise that option in [extruder]

Klipper reads macros only at start-up, so every edit needs RESTART before it takes effect (Klipper's configuration checks say the same for every config change).

How a macro is built

Indentation matters. Each list item in this guide is one line of printer.cfg. Section lines in square brackets, gcode: itself and options such as description:, variable_ and rename_existing: start at the left edge. Every line after gcode:, up to the next line in square brackets, gets two leading spaces; without them Klipper no longer reads the line as part of the macro and reports a configuration error. This macro, built on Klipper's documented example with a description added, lifts the nozzle 10 mm:

  • [gcode_macro MOVE_UP]

  • description: Lift the nozzle 10 mm

  • gcode:

  • SAVE_GCODE_STATE NAME=my_move_up_state

  • G91

  • G1 Z10 F300

  • RESTORE_GCODE_STATE NAME=my_move_up_state

The description appears with HELP and in autocomplete. The SAVE_GCODE_STATE and RESTORE_GCODE_STATE pair matters more than it looks. G1 depends on whatever G90, G91, M82 and M83 last set, so Klipper advises saving the state, switching to relative mode for the move and restoring it afterwards, with an explicit F speed on the first G1. Without the restore, the slicer's next absolute move would be read as relative.

Names are not case sensitive, so MOVE_UP and move_up are the same command. A name with digits must have them all at the end: TEST_MACRO25 works, MACRO25_TEST3 does not.

Teaching Tech's Klipper guide starts with simple macros and then adds variables; the link starts at that chapter.

Klipper guide: Input shaping, pressure advance and macros (manual + accelerometer) (Teaching Tech)

Parameters: a heat soak you can tune per print

Anything after the macro name arrives in params. Klipper hands every value over as text with an upper-case name, so convert it before you calculate. The usual pattern sets a default and converts in one line, as Klipper's sample START_PRINT does for its default bed temperature of 60 °C:

  • [gcode_macro HEAT_SOAK]

  • description: Heat the bed and hold it before printing

  • gcode:

  • {% set bed = params.BED|default(60)|float %}

  • {% set minutes = params.MINUTES|default(10)|int %}

  • M190 S{bed}

  • G4 P{minutes * 60000}

Worked example. HEAT_SOAK BED=100 MINUTES=15 waits until the bed reaches 100 °C, then dwells for 15 × 60,000 = 900,000 ms, because Klipper's G4 takes milliseconds. Bambu Lab's first-layer guide for the H2D suggests holding the bed at temperature for 10 to 15 minutes when first-layer problems persist, which is where a soak earns its time.

This version blocks the console until it finishes. A heat-soak thread on the Klipper forum explains why that annoyed its author: M190 and G4 cannot be interrupted without an emergency stop. Its interruptible version checks the time every few seconds with a delayed_gcode, the same technique as the LED macro below.

Variables: a Z offset for each build plate

A variable_ option declares a value the macro keeps between calls. Inside its own macro you use it by name; other macros read it as printer["gcode_macro NAME"].name. SET_GCODE_VARIABLE changes it at run time, and Klipper parses the new value as a Python literal, so text needs quotes. Variable names must be lower case.

Ordinary variables reset at every restart. To keep a value, add a [save_variables] section: SAVE_VARIABLE writes to a file, and the stored values return in printer.save_variables.variables after each start. That suits a Z offset per build plate. Print a first layer, adjust Z live until it is right, then store the result under the plate's name:

  • [save_variables]

  • filename: ~/variables.cfg

  • [gcode_macro SAVE_PLATE_OFFSET]

  • description: Store the current Z offset for one build plate

  • gcode:

  • {% set plate = params.PLATE|default('default')|lower|replace(' ', '_') %}

  • SAVE_VARIABLE VARIABLE=z_{plate} VALUE={printer.gcode_move.homing_origin.z}

  • [gcode_macro LOAD_PLATE_OFFSET]

  • description: Apply the stored Z offset for one build plate

  • gcode:

  • {% set plate = params.PLATE|default('default')|lower|replace(' ', '_') %}

  • {% set svv = printer.save_variables.variables %}

  • SET_GCODE_OFFSET Z={svv['z_' ~ plate]|default(0.0)}

homing_origin.z holds the offset that SET_GCODE_OFFSET and live Z adjustments have built up. Call LOAD_PLATE_OFFSET PLATE=textured in your slicer's start code after START_PRINT; Klipper's sample START_PRINT resets the offset to zero, so the order matters. OrcaSlicer can fill in the plate itself with PLATE="{curr_bed_type}", a setting that holds names such as Textured PEI Plate. The lower and replace filters turn that into textured_pei_plate, a valid variable name. A Creality forum user sets per-plate and per-filament offsets in the same way. What the first layer should look like is in the z-offset guide.

Reading the printer, and the evaluation trap

The printer object exposes the live state of every configured section. The fields you will use most:

  • printer.extruder.temperature, target and can_extrude, the last one true once the nozzle is above min_extrude_temp.

  • printer.heater_bed.temperature and target.

  • printer.toolhead.homed_axes, a text such as "xyz".

  • printer.print_stats.state: standby, printing, paused, complete, cancelled or error.

  • printer.virtual_sdcard.progress, from 0 to 1, based on the position in the file.

  • printer.configfile.settings, the values from your configuration.

A section name with a space needs brackets: printer["gcode_macro HEAT_SOAK"]. A common use is homing only when needed, the check KlipperScreen's park macro uses:

  • {% if "xyz" not in printer.toolhead.homed_axes %}

  • G28

  • {% endif %}

Now the trap. Klipper renders the whole template before the first command runs. A test placed after G28 in the same macro still sees the unhomed state, and a temperature read after M109 still sees the cold nozzle. The fix is structural: put the part that depends on the result into a second macro and call it. A called macro is evaluated only when it is reached, after the earlier commands have run. The same applies to Klipper's action functions such as action_respond_info: they run during evaluation, which can be long before the commands they sit between.

Load and unload filament

KlipperScreen's Load and Unload buttons call macros with exactly these names and pass the chosen speed as SPEED. The version below follows KlipperScreen's documentation and adds a temperature guard. The guard reads printer state, which is safe because it does not depend on a command in the same macro:

  • [gcode_macro LOAD_FILAMENT]

  • variable_load_distance: 50

  • variable_purge_distance: 25

  • gcode:

  • {% if not printer.extruder.can_extrude %}

  • {action_raise_error("LOAD_FILAMENT: heat the nozzle first")}

  • {% endif %}

  • {% set speed = params.SPEED|default(300) %}

  • {% set max_velocity = printer.configfile.settings['extruder'].max_extrude_only_velocity * 60 %}

  • SAVE_GCODE_STATE NAME=load_state

  • G91

  • G92 E0

  • G1 E{load_distance} F{max_velocity}

  • G1 E{purge_distance} F{speed}

  • RESTORE_GCODE_STATE NAME=load_state

UNLOAD_FILAMENT is the same macro with variable_unload_distance: 50 and the two moves reversed: first a short purge, G1 E{purge_distance} F{speed}, then G1 E-{unload_distance} F{max_velocity}. SPEED is in mm/min, so 300 is 5 mm/s. Each move must stay within max_extrude_only_distance, 50 mm by default. For a long Bowden tube, KlipperScreen's documentation shows raising it in [extruder]; set the load distance to your own path from the drive gear to the nozzle.

Two macros that wait: an LED progress bar and power-off

An LED progress bar with delayed_gcode

A delayed_gcode runs once after a delay. It can schedule itself again, which gives you a loop that does not block printing. This one lights the LEDs of an 8-LED strip in proportion to progress; it assumes a [neopixel ring] section with chain_count: 8 and the pin your board uses:

  • [delayed_gcode led_progress]

  • gcode:

  • {% if printer.print_stats.state in ["printing", "paused"] %}

  • {% set count = 8 %}

  • {% set lit = (printer.virtual_sdcard.progress * count)|int %}

  • {% for i in range(1, count + 1) %}

  • SET_LED LED=ring GREEN={1 if i <= lit else 0} INDEX={i} TRANSMIT={1 if i == count else 0}

  • {% endfor %}

  • UPDATE_DELAYED_GCODE ID=led_progress DURATION=10

  • {% endif %}

Start it from START_PRINT with UPDATE_DELAYED_GCODE ID=led_progress DURATION=1; once the print has ended, it stops scheduling itself. In END_PRINT, UPDATE_DELAYED_GCODE ID=led_progress DURATION=0 cancels a pending run and SET_LED LED=ring GREEN=0 then clears the strip; without the cancel, a run that comes due while END_PRINT is still working lights it again. TRANSMIT=0 holds each change until the last LED, so the strip updates in one go. At 25% of a print, lit is 0.25 × 8 = 2, so two LEDs glow. If your slicer sends M73, printer.display_status.progress follows the slicer's estimate instead of the file position; it is only available with a display or a [display_status] section.

Switch the printer off after a print

Klipper cannot cut power itself, but Moonraker can if a power device such as a smart plug is set up as [power printer] in moonraker.conf. Moonraker's documentation gives the remote call; the rest waits for the hotend to cool first:

  • [gcode_macro POWER_OFF_PRINTER]

  • gcode:

  • {action_call_remote_method("set_device_power", device="printer", state="off")}

  • [gcode_macro POWER_OFF_WHEN_COOL]

  • description: Switch the printer off once the hotend is below 50 °C

  • gcode:

  • TURN_OFF_HEATERS

  • TEMPERATURE_WAIT SENSOR=extruder MAXIMUM=50

  • POWER_OFF_PRINTER

This is the evaluation trap in practice. Put the remote call straight into POWER_OFF_WHEN_COOL and it fires during evaluation, before the wait, cutting power on a hot nozzle. As its own macro it runs only after TEMPERATURE_WAIT returns. The 50 °C matches Klipper's default for a heater_fan, which keeps the hotend fan running until the nozzle is below that temperature. Cutting power earlier stops that fan, and the heat creep guide explains what follows. Check what the plug feeds, too: if the computer running Klipper is on the same plug, it goes off with the printer.

Override a built-in command with rename_existing

rename_existing keeps a built-in command under a new name, so your macro can wrap it. KlipperScreen's documentation parks the head on pause this way; this shorter version only lifts the nozzle:

  • [gcode_macro PAUSE]

  • description: Pause the print and lift the nozzle 2 mm

  • rename_existing: PAUSE_BASE

  • gcode:

  • PAUSE_BASE

  • G91

  • G1 Z2 F900

  • G90

PAUSE now runs the original as PAUSE_BASE, which saves the position, and then lifts the nozzle 2 mm; RESUME restores the saved state and moves the nozzle back. Near the top of the Z axis that lift is out of range. KlipperScreen's version therefore calls a helper, _TOOLHEAD_PARK_PAUSE_CANCEL, that lifts only as far as the axis allows, retracts and parks the head; copy the helper from the same page if you use that version. Its leading underscore hides it from KlipperScreen's macro list, and macros with rename_existing are hidden there too. Klipper warns that overriding commands "can cause complex and unexpected results", so override only what you need. Klipper has no built-in M600; its sample file defines one as a plain macro.

What belongs inside START_PRINT and END_PRINT, and how the slicer passes temperatures to them, is in start and end G-code. If you are still deciding whether Klipper is worth it, what Klipper changes covers the host, the board and the upkeep. Your LOAD_FILAMENT and UNLOAD_FILAMENT macros also drive the buttons on a touchscreen; choosing one is covered in KlipperScreen, a Sonic Pad or a phone.