# Language syntax

Shortcuty Script turns `.shortcuty` files into Apple Shortcuts. Studio projects also store the name, icon, input settings, and app choices.

## A complete shortcut

```shortcuty
shortcut:
  name = input("What is your name?")
  greeting = text("Hello, \(name)!")
  result(greeting)
```

Start with `shortcut:` and indent the steps you want it to run. Assign a value with `name = value`. Use `output name = action(...)` to refer directly to an action’s result.

**Read a line of code.** In `name = input.ask(prompt: "What is your name?", type: "Text")`, `name` is the variable, `input.ask` is the action, and `prompt:` and `type:` name its arguments. Use the variable without quotes to pass its value. Inside quoted text, write `\(name)` to insert it. A line ending in `:` begins a block when it follows a block header such as `shortcut`, `if`, or `for`; indent the lines it controls.

## Syntax at a glance

| Purpose | Syntax |
| --- | --- |
| Store a mutable value | `name = expression` |
| Bind an action output | `output name = action(...)` |
| Fill an existing missing value | `name ??= fallback` |
| Call an action | `module.action(parameter: value)` |
| Insert a value into text | `"Hello, \(name)"` |
| Read a dictionary field | `record["key"]` |
| Update a dictionary field | `record["key"] = expression` |
| Supply a missing-value fallback | `optional ?? fallback` |
| Choose between values | `condition ? first : second` |
| Combine Boolean values | `ready and (saved or approved)` |
| Remainder / power | `7 % 3`, `2 ** 3` |
| Check a value | `if value has value:` |
| Repeat a fixed count | `repeat 3 times:` |
| Visit a collection | `for row in values:` |
| Visit with a one-based index | `for index, row in values:` |
| Share a literal across files | `shared TITLE = "Daily report"` before the entry body |
| Declare a helper | `def greet(name: Text) -> Text:` |
| Return from a helper | `return value` |

References: [Values](/docs#values), [Variables](/docs#variables), [Calls](/docs#calls), [Control](/docs#control), [Types](/docs#types), [Functions](/docs#functions), [Imports](/docs#imports), [Actions](/docs#actions).


### Run an action only when a condition passes

Use `and` and `or` to combine checks. If a check calls an action or a helper, that call can run before the combined condition is tested. Put it inside an `if` block if it should only run after the first check passes:

```shortcuty
shortcut:
  route = input.ask(prompt: "Route code", type: "Text")
  if route == "manual":
    answer = input.ask(prompt: "Type yes to confirm", type: "Text")
    if answer == "yes":
      result("Manual route approved")
```

### Named action inputs

Use named inputs for app and device actions. For example, this sets a fixed alarm and prepares a phone-number value without placing a call:

```shortcuty
shortcut:
  alarms.create(time: "06:10", name: "Morning")
  contact_number = contacts.phone_number(number: "+1 202 555 0100")
```

Use the exact names from the [Action reference](/docs/actions.md). A quoted value such as `"Original"` is a choice only if the action lists it. Leaving out an optional input keeps the action's default. Some actions, such as Finder image conversion, are specific to Mac.

## Layout and comments

Identifiers use ASCII letters or underscore, followed by letters, digits, or underscores. Quote user-visible names containing spaces, emoji, or punctuation.

Use consistent space indentation; two spaces per level is recommended, not required. Sibling statements and menu cases must align. Tabs are rejected. Dedent to an earlier level; blank lines emit no actions.

`#` starts comments, including trailing comments. They preserve diagnostic line numbers but emit no actions. Use `comment()` for a visible Apple Comment action. Comment characters inside strings stay literal:

Double-quoted strings use JSON escapes such as `\n`, `\"`, and `\\`. Triple quotes keep line breaks and remove common indentation. Use `\(value)` to insert a value in either kind of string. For text that should display the placeholder literally, wrap it with `literal_text(...)`:

```shortcuty
shortcut:
  body = text("""
    First line
    Second line
  """)
  result(body)
```

Multiline text works the same with Windows and Unix line endings. Pasted Unicode separators inside quoted text stay part of the text. They do not start a new line of Shortcuty code.
Script files can start with a UTF-8 marker (BOM). Studio ignores that first marker and keeps the same character if you put it inside quoted text.

Open parentheses, brackets, and braces allow multiline expressions. Tabs, unmatched delimiters, unexpected indentation, statements outside the body, and trailing expression junk are errors.

## Reading syntax examples

A `shortcuty` code block shows source. A `text` block may be a fragment or an invalid example; `...` marks something to replace. Put imports, constants, and functions above `shortcut:`.

Use `=` to store, `==` to compare, and `has value` to test presence. A present `false` or `0` is not missing. For an end-to-end example by task, see [Recipes](/docs/recipes.md).

Standalone scripts can use `shortcut "Greeting":`. In Studio, set the name in **Shortcut details**.

## Unsupported spellings

Use `greeting = text("Hello")`, not `text "Hello" -> greeting`. Dollar-prefixed variable references and command-style statements are rejected. `break` and `continue` are not supported.

## What a build means

Use **Check** to find problems in the script and **Build** to turn it into an Apple Shortcut. Run the result in Apple Shortcuts to test it with your apps, permissions, and iOS version.

## Common repairs

- Dictionary key: use `record[key]` when the key is Text. A loop over a list of only text literals can use its item directly as a key. Run-time or mixed lists may need an explicit cast. A loop index can be used directly to access a list.
- List index: use `items[1]` for the first item. Use `items[index]` when the index is a Number. Literal indices start at 1 and cannot exceed 2147483647. A literal range can’t end before it starts.
- File picker: use `files.choose(select_multiple: false)`, not an empty `files.pick()`.
- Boolean decision: `if ready:` and `if ready == true:` test truth; use `has value` or `if let` for presence. Non-Boolean bare conditions are errors.
- Arithmetic comparison: `price * quantity > limit` groups arithmetic first in expressions and `if` headers; parentheses can make it clearer.
- Missing value: use `if let`, a terminating guard, or `??`; `require()` does not stop or alert.
- Unknown call or parameter: inspect the installed catalog instead of guessing a synonym or native identifier.

If `lists.make` contains only literal numbers, you can use each number as a list index directly. You don’t need to convert it first.

```shortcuty
shortcut:
  output labels = lists.make(items: ["Red", "Blue", "Green"])
  output picks = lists.make(items: [3, 1])
  for pick in picks:
    label = labels[pick]
    show(label)
```

You can also make the list right in the loop:

```shortcuty
shortcut:
  labels = ["North", "South", "West"]
  for pick in lists.make(items: [3, 1]):
    if let selected = labels[pick]:
      show(selected)
```

Fix the cause at the reported file and line, update other occurrences of the same mistake, and Check the entire project again. See [Diagnostics](/docs/diagnostics.md) for source errors and safe repairs.

For an interpreter or Python-like project, define the supported syntax and set a step limit. See [Interpreters](/docs/interpreters.md).

Migration notes are in [Diagnostics](/docs/diagnostics.md).

## Automation triggers

See [Automation triggers](/docs/triggers.md) to run a shortcut when an event occurs.


## Collection and assignment shortcuts

Use `items[1]` for the first item and `items[2:4]` for items 2, 3, and 4. Use `items[first:last]` with Number expressions. Both endpoints are included and required; a step is not supported. Indexing and slicing do not add runtime bounds checks. See [Variables and objects](/docs/variables) for computed keys and indices.

Already assigned mutable numeric names support `+=`, `-=`, `*=`, `/=`, `%=` and `**=`. These are numeric assignments, not text/list mutation. Read Variables and objects for source-evaluation rules, projection helpers, destructuring and optional-input limits.

### Start a typed list empty

Use `[]` for an empty list. Inside a list of lists, `[[]]` means one empty list, not zero lists. A function’s type tells Shortcuty what belongs in each list.

```shortcuty
def empty_day() -> List<List<Text>>:
  return [[]]

def start_log(days: List<List<Text>> = [[]]) -> List<List<Text>>:
  return days

shortcut:
  daily_notes = start_log([[]])
  default_notes = start_log()
  tomorrow = empty_day()
  result([daily_notes, default_notes, tomorrow])
```

### Look up a key that might be missing

If a function returns `Text?`, save its result and use `if let` before using it as a dictionary key. Use the name introduced by `if let` inside that branch.

```shortcuty
def selected_key() -> Text?:
  return "title"

shortcut:
  record = {title: "North"}
  candidate = selected_key()
  saved_key = candidate
  if let key = saved_key:
    if let title = record[key]:
      show(title)
```

### Use a value after a fixed repeat

When you write a positive integer count like `repeat 2 times:` and the loop sets a variable on every path that continues, you can use that value afterward. For example, if both branches of an `if` set `last_page`, `show("Page \(last_page)")` after the loop reads the variable itself instead of one branch's output. For a count that can be zero or is picked while the shortcut runs, check the value first or set a starting value before the loop.

```shortcuty
def next_page(page: Number) -> Number:
  return page + 1

shortcut:
  last_page: Value?
  repeat 2 times:
    last_page = repeat_index * 5
  page = next_page(last_page)
  show(page)
```

### Pick a dictionary key in a menu

Set the same variable to Text in every choice that continues. You can then use it as a dictionary key after the menu, without another conversion. A choice that stops the shortcut doesn’t need to set the variable.

```shortcuty
shortcut:
  record = {title: "North", detail: "South"}
  menu("Which field?"):
    case "Title":
      key = text("title")
    case "Detail":
      key = text("detail")
    case "Cancel":
      flow.stop()
  if let selected = record[key]:
    show(selected)
```

### Give a missing key a default

If a function returns a key that might be missing, use `??` to give it a default. When both choices are Text and the fallback is present, use the result as a dictionary key. The fallback is used only when the first value is missing.

```shortcuty
def preferred_key() -> Text?:
  return null

shortcut:
  record = {title: "North", detail: "South"}
  key = preferred_key() ?? "title"
  if let title = record[key]:
    show(title)
```

### Choose a dictionary key

Use `? :` to choose a key when both choices are present Text values.

```shortcuty
shortcut:
  record = {title: "North", detail: "South"}
  score = 12
  key = score >= 10 ? "title" : "detail"
  if let title = record[key]:
    show(title)
```

## Cross-file values

Use `shared NAME = value` at the top of Main when multiple files need the same fixed value. Imported functions can read it by name, including in defaults. Use a literal rather than a call or interpolation. Pass anything calculated during the run as an argument or return value. See [Functions](/docs#functions).


### Return an object from another file

You can use an object to build a record inside a function. Return it as a `Dictionary`, then read its keys with brackets in the calling file. Use typed function parameters as field values, such as `Route(label: name, score: points)`. Custom object names are not function parameter or return types.

**Main.shortcuty**

```shortcuty
import "Routes"
shortcut:
  current = Routes.build()
  if let label = current["label"]:
    result(label)
```

**Routes.shortcuty**

```shortcuty
def build() -> Dictionary:
  object Route:
    label: Text
    score: Number
  return Route(label: "Country", score: 3)
```

## Shortcut configuration and setup questions

For a new script, `workflow_settings({...}, merge_defaults: true)` keeps defaults for settings you leave out. Lists you supply replace the default lists. In Studio, saved project settings take priority over this line. See [Shortcut settings](/docs/settings).


Give the action an explicit output name with `output`, then use that name as the setup question target. You do not need to count actions.

```shortcuty
shortcut Greeting:
  output greeting = text("Hello")
  setup_question(target: greeting, parameter: "WFTextActionText", prompt: "Your greeting?", default: "Hello")
  show(greeting)
```

Put the question directly under `shortcut:`, targeting one named action outside any branch or loop. Use the action’s documented parameter key and a literal prompt. If you omit the default, the question uses the action’s fixed value. Use `default: null` for no preset answer. A value computed while the shortcut runs needs an explicit default or `null`.


Find action names, inputs, and choices in the [Action reference](/docs/actions.md).


### Imported setup question boundaries

Keep imported setup questions if you do not need to change them. They may point to actions inside a branch or loop, which new `setup_question` declarations cannot target.

## Native shortcut UI design

See [Native shortcut UI design patterns](/docs/ui-patterns.md) for prompts, lists, menus, and previews.

## Optional native storage

For optional native named storage without initialization, use `cached: Value?` or `variable("Cached value"): Value?` before executable actions. Read Variables → Optional native variable declarations for scope, collision and missing-value rules. This is not a runtime action or persistence.

### Copying a value that might be missing

A variable copy can carry a missing value forward. Use `if let` or `??`
when you need a real value, such as a number for a list index. Imported
`variables.set` and `variables.get` steps keep that same behavior without
adding a required-value check just to copy the variable.

### Ordering dates and numbers

With \`<\`, \`<=\`, \`>\` and \`>=\`, Shortcuts compares numbers. For a date
range, compare numeric \`yyyyMMdd\` keys. Keep \`yyyy-MM-dd\` for display.
Studio flags text on both sides of an ordering comparison (SS2117).


### Use an answer as a key or index

A question can supply a dictionary key directly when its type is omitted (Text by default) or set to `type: "Text"`:
`score = scores[answer]`. Use `if let score = scores[answer]:` when the
key may be missing. A question with `type: "Number"` can supply a
one-based list index directly. Check that the answer is in range before
reading the list.

This works with `output answer = input.ask(...)` too. In that form the
lookup uses the Ask action’s result directly, without storing a copy.
