# Importing Ink, Yarn Spinner, Ren'Py and Twine

Scenarios written in Ink (inkle's `.ink`), Yarn Spinner 2 and 3 (`.yarn`), Ren'Py (`.rpy`) and Twine's Twee 3 (`.twee`, `.tw`; the basics of Harlowe and SugarCube)
are converted to `.lim` and imported. The conversion is in `packages/story-import`, and `lim import-ink` / `lim import-yarn` / `lim import-renpy` /
`lim import-twine` and Import text in Studio (Ink, Yarn Spinner, Ren'Py and Twine) all use the same conversion.
Syntax that can't be handled doesn't stop the conversion. It's kept as a comment and listed in the report.

## Usage

```bash
lim import-ink  [project] story.ink                 # also reads the files it INCLUDEs
lim import-yarn [project] dialogue/                 # every .yarn in the folder (you can also list files)
lim import-yarn [project] intro.yarn --name opening # the name of the .lim to write (Ink, and Yarn with a single file)
lim import-ink  [project] story.ink --end stop      # what the end of the story becomes (below)
lim import-renpy [project] game/                    # every .rpy in the folder (one .lim per .rpy; labels are shared; also copies the images and sounds it uses and turns tl/ into lang/)
lim import-renpy [project] game/ --no-assets        # don't copy assets
lim import-twine [project] story.twee               # Twee 3 (a folder or several files become one story in one .lim)
```

- The `.lim` is written to the scenario folder (`paths.scenario`) under the original file name (characters other than letters, digits, `_` and `-` become `_`).
  Ink becomes one `.lim` including its INCLUDEs, and Yarn Spinner becomes one `.lim` per `.yarn` (node names are shared across files.
  A `<<jump>>` to a node in another file becomes `file#label`)
- If a `.lim` with the same name already exists, it's overwritten only if it was made earlier by `lim import-ink` / `lim import-yarn` (its first line is a comment that marks it).
  Other files aren't overwritten and are listed in the report (`--force` overwrites them)
- Dialogue speakers are added to `speakers` in `cast.json`, and the initial values of variables to `variables` in `liminalia.json` (existing variables aren't changed)
- Dialogue becomes `Name「…」`. A story whose original files contain no hiragana or katakana (the Japanese kana) at all, that is, an English story, gets the English dialogue form `Name "…"` instead
  (`Name “…”` if the text contains `"`), so that the dialogue of an English story isn't shown in the game as 「…」. The form is the same throughout one import.
  The outer quotation marks of the original dialogue (Ink's `Name: "…"`, and the delimiters of Ren'Py's `e "…"`) are treated as delimiters and removed before the text is wrapped.
  To hide the quotation marks as the original game did, set `ui.text.quotes` in `liminalia.json` to `strip`
- The report is `ink-import-report.md` / `yarn-import-report.md` / `renpy-import-report.md` / `twine-import-report.md` in the project (in Japanese, in the same form as TyranoScript's `import-report.md`.
  `mapped` is what was converted, `dropped` is what was deliberately left out, `generic` is tags and commands not in the mapping that became comments,
  and `manual` is syntax that isn't converted). It also shows syntax errors and check errors from reading the converted `.lim` back in
- The exit code is 0 when `generic`, `manual`, errors and files not overwritten are all 0, and 1 otherwise
- `--end` sets what the end of the story (Ink's `END` and `DONE`, and the end of a Yarn node and `<<stop>>`) becomes:
  `title` (the default; `@title-screen` returns to the title screen), `stop` (`@stop`) or `return` (`@return`, for a story that's called with `@call`)

In Studio, choose Ink or Yarn Spinner as the Format in Import text (or drop an `.ink` or `.yarn` file, or let it detect the format automatically).
It's converted as a single file, and the initial values of variables are written as `@set` lines at the top. The number of places that couldn't be converted, and the reasons, are shown next to the converted result.

## What gets converted

### Ink

| Ink | .lim |
|---|---|
| `=== knot ===`, `= stitch` | `# knot`, `# knot-stitch` (a knot that has stitches but no content of its own goes to its first stitch) |
| Text, `Name: line`, a `#speaker: Name` tag | Narration, `Name「line」` (`Name "line"` in an English story; see above) |
| `<>` (glue) | Joins the lines before and after it into one line |
| `-> target`, `-> END`, `-> DONE` | `@jump #target`, the end |
| `-> target ->`, `->->` (tunnels) | `@call #target`, `@return` |
| `*` and `+` choices, `[ ]`, `{condition}`, `(label)`, nesting, gathers `-` (labeled ones too) | `@choice`, plus labels for what follows each choice and for the continuation |
| `*` (once only) | Hidden with a variable that records whether it was chosen (`game.once_…`), only when the story comes back to the same choices |
| A choice with no text, `* -> target` | Goes to `target` when none of the other choices are shown |
| `VAR`, `CONST`, `~ temp` | `game.` variables (initial values in liminalia.json), the value itself, `@let` |
| `~ x = …`, `+=`, `-=`, `++`, `--` | `@set` / `@let` |
| `{x}`, `{condition: A\|B}` | `{= …}` expressions |
| `{A\|B}`, `{&A\|B}`, `{!A\|B}`, `{~A\|B}` | Text variations `{seq A\|B}`, `{cycle …}`, `{once …}`, `{shuffle …}` (the number of times each was passed is kept in saves; sequences inside the branches of a condition are `{= …}` expressions as before, counted with `game.ink_seq…`) |
| `{condition: -> a \| -> b}` | `@if` for each line |
| Multiline `{condition: … - else: …}`, `{ - condition: … }`, `{ x: - 1: … }` | `@if` / `@elif` / `@else` (when they contain choices or labels, jumps to a label for each branch) |
| Multiline `{stopping: …}`, `{cycle: …}`, `{once: …}`, `{shuffle: …}` | `@if` on a count variable or a random number |
| Knot or stitch names used in expressions (visit counts), `READ_COUNT(-> x)` | `game.seen_…`, incremented at that label |
| `RANDOM`, `INT`, `FLOOR`, `CEILING`, `MIN`, `MAX`, `FLOAT` | `random`, `floor`, `ceil`, `min`, `max`, `(x * 1.0)` |
| Division of two integers (`7 / 2` is 3) | `floor(a / b)` ("Integer division" below) |
| `and` `or` `not` `mod` | `&&` `\|\|` `!` `%` |
| `#tag` (at the end of a line, or on a line by itself) | The command from the mapping (placed before that line) |
| `=== function name(args) ===` and `~ return` | A macro that returns a value, `@define ink-name(arg: type, ink-result: variable)`, and `@return (expr)` ("Functions" below) |
| `LIST` | A `game.` variable holding an array of item names ("LIST" below) |
| Threads, `<- knot` | Shows that knot's text here, and its choices together with the current choices ("Threads" below) |
| `INCLUDE` | Reads only files inside the starting file's folder, appended after it |
| `TODO:` | A comment |

Not converted (kept as comments and listed in the report): parameters on knots and stitches, threads with parameters, `EXTERNAL`, `ref` parameters of functions (passed as values instead),
expressions whose value is a divert target and diverts to variables, functions such as `TURNS`, comparing lists by size and functions such as `LIST_MIN`,
and sequences inside choice text (the text for the same pass is always shown). `shuffle once` and the like are converted as `shuffle`.

#### Functions

`=== function name(args) ===` becomes `@define ink-name(arg: type, ink-result: variable)`, using the engine's macro return values (the section on return values (`@return (expr)`) in [format.md](design/format.md)).
Names are made of lowercase letters, digits and `-` (`add_gold` becomes `ink-add-gold`, and `maxHP` becomes `max-hp`,
which is `max_hp` in the expressions inside). `~ return expr` becomes `@return (expr)`.

```
@define ink-double(x: number, ink-result: variable)
  @return (x * 2)
@end
```

- A call inside an expression (`{double(gold)}`, `~ x = double(gold) + 1`) calls the macro before that statement, puts the return value in a local variable, and then uses it
  (`@ink-double x=(game.gold) ink-result=temp.ink_ret` and `@let ink_r1 = temp.ink_ret`). `~ add_gold(2)`, which doesn't use the value, is just a macro call.
  Calls in choice conditions and choice text are made before `@choice`. Because of this, `f` in `a && f()` is called even when `a` is false
- Recursion (`fact(n - 1)`) works too. A function that assigns to a parameter (`~ n = n - 1`) uses a local variable copied from the parameter (`v_n`) (`@let` can't use the same name as a parameter)
- Parameter types are decided from the arguments in calls (`string` if they're only strings. Values are always passed as `(expr)`, so this is for readability)
- A function that outputs text (dialogue or narration) shows it as a separate page before the line that called it (Ink shows it inside that line). The report's information section lists it as `ink-function-text`
- Choices and diverts inside functions (which Ink doesn't allow either) become comments and are reported

#### LIST

`LIST name = a, (b), c = 5` becomes `game.name`, an array of the names of the items it contains (the initial value is the items in `( )`, here `["b"]`).
Item names (`a`, `name.a`) are the string `"a"` in expressions.

| Ink | .lim |
|---|---|
| `{L}` (in text) | `{= join(game.L, ", ")}` |
| `L ? a`, `L has (a, b)`, `L !? a`, `L hasnt a` | `includes(game.L, "a")` (joined with `&&` for two or more), and its negation |
| `L == a`, `L == (a, b)`, `L != a`, `L == M` | Whether it has exactly the same items (in any order) |
| `L` in a condition | `len(game.L) > 0` (whether it isn't empty) |
| `~ L = a`, `~ L = (a, b)`, `~ L = ()`, `~ L = M` | `@set game.L = ["a"]` and so on |
| `~ L += a`, `~ L -= (a, b)`, `~ L = L + a` | `unique(push(…))`, `remove(…)` |
| `~ L += M`, `~ L -= M` (another list) | Adds or removes items one at a time with `@while` |
| `LIST_COUNT(L)`, `LIST_RANDOM(L)`, `LIST_VALUE(a)` | `len(game.L)`, an array with one item picked from it, the item's value (a number) |

- `{L}` in text lists items in the order they were added (Ink uses the order written in the LIST)
- If two LISTs have items with the same name, both become the same string (warning)
- Comparing lists by size (`<` `>`), `+` and `-` expressions (except in the assignment forms), `LIST_MIN`, `LIST_MAX`, `LIST_ALL`, `LIST_INVERT` and `LIST_RANGE` aren't converted (`ink-list`)

#### Threads

`<- knot` shows that knot's text before its choices here, and shows its choices together with the choices of the current flow
(before the next choice, gather or jump-only line, or at the end of the flow if there's none). Jump targets inside the pulled-in choices are resolved by the name of the knot that was pulled in.
For a knot with no content of its own, its first stitch is pulled in. Threads with parameters, threads that pull in themselves, and pulling in a knot that has labeled choices twice aren't converted.

#### Integer division

Ink rounds down when it divides one integer by another (`7 / 2` is 3), but `/` in .lim always divides with decimals, so divisions in converted expressions
where both sides are known to be integers become `floor(a / b)`. Whether a value is an integer is decided from the following.

- How numbers are written (`2` is an integer, `2.0` is a decimal), and `FLOAT(x)` (turned into `(x * 1.0)` so that it's recognizably a decimal)
- The kind of the `VAR`'s initial value (`VAR gold = 0` is an integer. For a variable that will hold decimals later, write the initial value as `0.0` and it's treated as a decimal)
- The kind of expression stored with `~ temp` (stitches inherit the kinds of their knot's temps)
- Functions that return integers (`INT`, `FLOOR`, `CEILING`, `RANDOM`, and `MIN` and `MAX` of integers)

If either side is known to be a decimal, it stays decimal division. Divisions where it isn't known whether both sides are integers (function parameters and so on) also stay decimal division,
and their locations are listed as `ink-division` under “情報” (information) in the report. Division of negative numbers differs: Ink rounds toward 0 (`-7 / 2` is -3),
while `floor` rounds down to the smaller number (-4).

### Yarn Spinner

| Yarn Spinner | .lim |
|---|---|
| Nodes (`title:` … `---` … `===`) | `# title` (the node named `Start` is placed at the top of the file) |
| Text, `Name: line` | Narration, `Name「line」` (`Name "line"` in an English story) |
| `-> choice` (with indented content), `-> choice <<if condition>>` | `@choice`, plus labels for what follows each choice and for the continuation |
| `<<jump node>>`, `<<detour node>>`, `<<return>>`, `<<stop>>` | `@jump`, `@call`, `@return`, the end |
| `<<declare $x = value>>`, `<<set $x to …>>` (`=` `+=` `-=` `*=` `/=`) | The initial value of `game.x` (in liminalia.json), `@set` |
| Undeclared variables | `game.x` (the initial value is 0, "" or false, depending on the kind of value in `<<set>>`. Listed in the report's information section) |
| `<<if>> <<elseif>> <<else>> <<endif>>` | `@if` / `@elif` / `@else` / `@end` |
| `{$x}`, `{expr}` | `{= …}` |
| `visited("node")`, `visited_count("node")` | `game.seen_…`, incremented at that node |
| `random()`, `random_range(a, b)`, `dice(n)`, `round`, `floor`, `ceil`, `int` | Expressions that do the same thing |
| `and` `or` `not` `xor` `is` `eq` `neq` `gt` `lt` `gte` `lte` | `&&` `\|\|` `!` `!=` `==` `==` `!=` `>` `<` `>=` `<=` |
| `[b]` `[i]` `[wave]` `[shake]`, `[pause=500 /]`, `[nomarkup]` | `{b …}` `{i …}` `{fx wave …}` `{fx shake …}`, `{@wait 500ms}`, the text as it is |
| `#line:…` (line IDs) | Not written |
| Other `<<command>>`s and `#tag`s | The command from the mapping |

Not converted (kept as comments and listed in the report): jumps to expressions (`<<jump {$x}>>`), replacement markup such as `[select]`
(only the text inside is kept), other functions, and `<<endonce>>` without a matching `<<once>>`.

#### `<<once>>`

Whether something has been shown is recorded in a `game.once_node` variable (from the second one in a node on, `_2`, `_3` and so on).

| Yarn Spinner | .lim |
|---|---|
| `<<once>>` … `<<endonce>>` (`<<once if condition>>`, `<<else>>`) | `@if !game.once_X && (condition)`, with `@set game.once_X = true` at the start of the content. `<<else>>` becomes `@else` |
| `<<once>>` or `<<once if condition>>` on a line | That line is wrapped in an `@if` of the same form |
| `-> text <<once>>` on a choice | `if=(!game.once_X)` on the choice, and `@set` at the start of what follows the choice |

Choices could also be written with `chosen()`, but that can't tell them apart from other choices with the same text, so a variable is used.

#### Line groups

A run of `=>` lines (including `<<if>>` and `<<once>>` on lines, and indented continuations) collects the lines that can be shown into `temp.yarn_pick`, picks one with `pick()`,
and shows it in an `@if temp.yarn_pick == number` branch. A group with no conditions uses `random(number of lines)`. If no line can be shown, nothing is shown.
Instead of Yarn Spinner 3's default selection (preferring lines with more conditions, and lines that haven't been shown recently), a line is picked at random from those that can be shown.

### Ren'Py

| Ren'Py | .lim |
|---|---|
| `label name:`, local labels `label .name:` | `# name`, `# parent-name`. The end of a label continues into the next label (as in Ren'Py) |
| `define e = Character("Name")` | A speaker (`speakers` in `cast.json`). `e "…"` becomes `Name「…」` (`Name "…"` in an English story) |
| `"…"`, `"Name" "…"`, `centered "…"`, `extend "…"` | Narration, dialogue, narration, narration on a separate line (`extend` isn't joined to the previous line) |
| `default x = value`, `define x = value`, `persistent.x` | The initial value of `game.x`, `system.x` |
| `$ x = expr` (and `+=` and so on), `$ renpy.pause(1.0)` | `@set`, `@wait 1s` |
| `jump`, `call`, `return` | `@jump`, `@call`, and `@return` in labels that are `call`ed. Otherwise, the end of the story (`--end`) |
| `menu:` (a question line, `"text" if condition:`), `menu name:` | A question line (`{noclick}`) and `@choice` (`if=`), a label |
| `if`, `elif`, `else`, `while` (with no choices or jumps inside) | `@if`, `@elif`, `@else`, the engine's `@while` |
| `scene background`, `scene black`, `scene` | `@chara-hide-all` and `@bg`, `@mask`, `@chara-hide-all` |
| `show tag attribute at left`, `hide tag` | `@chara tag attribute at=auto`, `@chara-hide tag` |
| `with dissolve`, `with Dissolve(1.0)`, `with fade` | `time=` on the previous command (500ms, 1s, 1s). Other transitions keep only their time |
| `play music "…" fadein 1.0`, `play sound`, `play voice`, `voice "…"`, `stop music fadeout 2.0` | `@bgm … time=1s`, `@se`, `@voice`, `@voice`, `@stop-bgm time=2s` |
| `pause 1.0`, `pause`, `window show` and `hide` | `@wait 1s`, `@wait-click`, `@window` |
| `{b}` `{i}` `{color=#…}` `{size=30}`, `{w}` `{p}` `{nw}`, `[variable]` and `\n` in text | `{b …}` `{i …}` `{c #… …}` `{size 30 …}`, `{click}` `{click}{br}` `{noclick}`, `{= expr}`, `{br}` |
| `and` `or` `not` `is` `True` `None`, `len` `int` `renpy.random.randint` `renpy.random.choice` in expressions | `&&` `\|\|` `!` `==` `true` `null`, `len` `floor` `randint` `pick` |

- The tag and attributes of `show` become a character and a variant in `cast.json` (`show eileen happy` is the variant `happy` of the character `eileen`). The image is the file given by `image eileen happy = "…"` if there is one,
  otherwise the image in `game/images` that Ren'Py names automatically (the file name without folders and extension, in lower case; `images/chars/eileen happy.webp` becomes `eileen happy.webp`),
  and otherwise `eileen happy.png`. Once you've decided the positions (`positions` in the frame), you can change it to `at=left`. Until then, `at left` and `at right` become `at=auto` (lines up the sprites on screen)
- Sounds written without quotes, such as `play music main_theme`, use the file in `game/audio` (Ren'Py's `audio.` names)
- **Assets**: the images and sounds the script uses are copied from `game/` to the project's asset folders (backgrounds to `bgimage`, sprites to `fgimage`, `play music` to `bgm`, `play sound` to `sound`,
  `voice` to `voice`). Files already there aren't overwritten, and images and sounds the script doesn't use aren't copied. The report's assets section lists each Ren'Py name and where it was copied.
  With `--no-assets`, nothing is copied and the report only lists the names the script uses. `game/` is the folder you pass (or the folder of the file) or one of its parents that is named `game` or has `images` or `audio`
- **Translations**: `translate` blocks in `tl/<language>/` become `lang/<language>.json` (files that only hold translations aren't turned into scripts). The same entries as `lim i18n` are made,
  and entries whose source matches a dialogue or narration line (the `# e "…"` comment in the block) or an `old` string in `translate … strings:` get the translation (choices and speaker names too).
  Language names become language codes (`english` is `en`, `japanese` is `ja`, `schinese` is `zh-Hans`, and so on), and the language is added to `languages` in `liminalia.json`.
  The source language and names that can't be turned into a language code aren't imported (listed in the report)
- Settings such as `define config.…`, ATL in `image`, `screen`, `transform`, `style` and `init python` aren't written (listed in the report's information section)
- Not converted (kept as comments and listed in the report): `python:` blocks and `$` lines other than assignments, `jump expression`, `call screen`, `show screen`,
  label parameters, `queue`, `set` in `menu`, `in`, `//`, `**` and conditional expressions in expressions, and labels inside blocks
- The report's information section shows which file and which label Ren'Py's starting point (`label start`) is in. Set `entry` in `liminalia.json` to that file

### Twine (Twee 3)

The story format is decided from `format` in `StoryData` (if there's none, it's detected from the syntax).

| Twine | .lim |
|---|---|
| Passages, `:: Name [tags]` | `# Name` (`start` in `StoryData`, or `Start`, goes first) |
| Lines of text, `''bold''`, `//italic//`, `<br>` | Narration, `{b …}`, `{i …}`, `{br}` |
| Links `[[Text]]`, `[[Text->Target]]`, `[[Target<-Text]]`, `[[Text\|Target]]` | An `@choice` at the end of the passage. Links inside a conditional branch are only shown when that branch was taken (`temp.twine_l…`) |
| `$x`, `_x` (including variables in text) | `game.x`, `temp.x` (`{= …}`) |
| Harlowe `(set: $x to it + 1)`, `(put: 1 into $x)` | `@set game.x = game.x + 1` |
| Harlowe `(if:)[…]`, `(else-if:)[…]`, `(else:)[…]`, `(unless:)[…]` | `@if`, `@elif`, `@else` |
| Harlowe `(print:)`, `(goto:)`, `(link-goto:)`, `(either:)`, `(random:)` | `{= …}`, `@jump`, a choice, `pick([…])`, `randint` |
| SugarCube `<<set $x to 1, $y += 2>>`, `<<if>>`, `<<elseif>>`, `<<else>>`, `<</if>>` | `@set`, `@if`, `@elif`, `@else` |
| SugarCube `<<print>>`, `<<=>>`, `<<goto>>`, `<<link "Text" "Target">>` | `{= …}`, `@jump`, a choice |
| `is` `is not` `eq` `neq` `gt` `gte` `lt` `lte` `and` `or` `not`, `===` in expressions | `==` `!=` `==` `!=` `>` `>=` `<` `<=` `&&` `\|\|` `!`, `==` |

- `StoryInit` (SugarCube) and passages tagged `startup` (Harlowe) are run before the starting passage, and their `set` values become the initial values of the variables
- Special passages such as `StoryData` and `StoryTitle`, and passages tagged `script`, `stylesheet` or `widget`, aren't written (listed in the report's information section)
- Twine shows a whole passage at once, but .lim waits for a click on each line of text. Text inside the hooks of conditional branches also goes on separate lines
- Not converted (kept as comments and listed in the report): other macros (`(display:)`, `<<include>>`, `<<widget>>` and so on), `contains` and `in` in expressions,
  and links to passages that don't exist. HTML tags are removed and the text inside is kept. Published .html files aren't read (export Twee 3 from Twine and import that)

## How tags and commands map

Ink tags (`# bg: forest.png` and `# bg forest.png` are the same) and Yarn Spinner commands (`<<bg forest.png>>`) are looked up in the mapping by name.
The built-in mapping:

| Name | .lim |
|---|---|
| `bg`, `background` | `@bg {1}` |
| `bgm`, `music` | `@bgm {1}` |
| `stop-bgm`, `stop_bgm`, `stopmusic`, `stop_music` | `@stop-bgm` |
| `se`, `sfx`, `sound` | `@se {1}` |
| `voice` | `@voice {1}` |
| `wait` | `@wait {1:s}` (seconds) |
| `chara`, `show` | `@chara {1} {2?}` |
| `hide` | `@chara-hide {1}` |
| `hide-all`, `hide_all` | `@chara-hide-all` |
| `quake`, `shake` | `@quake` |

To add mappings or override them for your project, write them in `liminalia.json` (names are case-insensitive).

```json
"import": {
  "ink": { "commands": { "flash": "@quake time=200ms", "mood": null } },
  "yarn": { "commands": { "fade_out": "@mask time={1:s}", "camera": "@camera zoom={1}" } }
}
```

- In a template, `{1}` `{2}` are the values by position (if one is missing, the tag isn't converted and becomes a comment), `{2?}` is empty if it's missing, `{1:s}` turns a number of seconds into a time (`2` → `2s`),
  `{1:ms}` is milliseconds, and `{*}` is all the values. Values that contain spaces are wrapped in `"…"`. Use `\n` to split a template into several lines
- `null` means that tag or command isn't written (it's counted as `dropped`)
- Anything not in the mapping becomes a `// #tag` or `// <<command>>` comment, and the count appears under “対応表に無いタグとコマンド（コメントにしたもの）” (tags and commands not in the mapping, made into comments) in the report
