# Writing back (lim backport)

A tool for projects that turned a TyranoScript (TyranoBuilder) project into .lim with `lim import` and then went on editing with .lim as the source of truth.
It writes the changes made in .lim back to .ks, so that if you hit a dead end on the .lim side, you can go back to TyranoScript and take your changes with you.

Writing back lives in `packages/ks-import` (`backportTyrano`) and the CLI, and isn't included in exported games.

## Usage

### 1. Make a base when you switch

```sh
lim backport [project] --make-base <base folder> --tyrano <TyranoScript project>
```

This imports the TyranoScript project again with the Liminalia project's import settings (the plugins' `./import`, the same as for `lim import`),
and puts what writing back needs in the base folder.

| In the base folder | Contents |
|---|---|
| `ks/` | A copy of `data/scenario` from the import source (the whole set, including `system/` and so on) |
| `lim/` | The .lim files imported from those .ks files |
| `import-sourcemap.json` | The source map ("Source map" below) |
| `import-report.md` | The import report |
| `base.json` | When the base was made, where the import source is, the git state of the import source (commit, branch and uncommitted changes in `data/scenario`), and the git state of the engine that made the base |

It also checks whether the project's current .lim files (`paths.scenario`) are the same as `lim/`, and reports the result. At the moment you switch, they should be the same. If they differ, make the project's .lim files match `lim/` before you switch.
Make the base only once, when you switch, and keep it with the project (if you remake it, the changes made to .lim until then no longer count as changes from the base).

### 2. Write back

```sh
lim backport [project] --base <base folder> [--tyrano <TyranoScript project>] [--out <folder>] [--write [--force]]
```

- Makes a full set of .ks files from the base and the project's current .lim files in `--out` (`.liminalia/backport/scenario` by default). It has the layout of `data/scenario` and includes files that didn't change.
  A .lim file in a subfolder (`part1/chapter2.lim`) is written back to the .ks file at the same path (`part1/chapter2.ks`)
- Writes a report (`backport-report.md`, in Japanese) next to `--out`: the places that couldn't be written back, deleted .lim files (candidates for deleting .ks files), and the result of the check
- Always checks at the end: it imports the written-back .ks files again with the same import settings, and compares the result with the project's current .lim files by line order, text and command meaning
  (blank lines, comments, indentation, parameter order and parameters equal to their defaults aren't compared). Differences appear in the report
- Without `--tyrano`, the import source recorded in `base.json` is used. The import source is only used to read things other than `data/scenario` (plugin settings and sprite images) in the import for the check
- Only with `--write` are the written-back .ks files written into `data/scenario` of the import source. Nothing is written if there are places that couldn't be written back, or if the check doesn't match.
  Files whose .ks in the import source differs from the base (because they were also edited on the TyranoScript side after you switched) aren't written and are reported. `--force` writes in both cases

The exit code is 0 if everything was written back, the check matched, and no file was left unwritten.

## Source map

`lim import` writes which .ks file and which line each line of the written .lim came from to `import-sourcemap.json`
(one level above the scenario output folder. It's also in `sourceMap` in the result of `importTyrano`). The import result (the contents of the .lim) doesn't change.

```json
{
  "version": 1,
  "files": {
    "chapter1.lim": {
      "source": "chapter1.ks",
      "sourceHash": "… (SHA-256 of the .ks)",
      "limHash": "… (SHA-256 of the .lim)",
      "lines": [
        {"kind":"command","from":3,"to":3,"tags":[1]},
        null,
        {"kind":"text","from":8,"to":9}
      ]
    }
  }
}
```

- `lines[i]` is where line i+1 of the .lim came from. Lines with no .ks counterpart, such as blank lines and `@use`, are `null`
- `from` / `to` are the range of .ks lines (starting at 1, including both ends). For a text line, the range runs from the start of the text to `[p]` (several lines if `[r]` continues it across lines)
- `tags` are the positions of the tags it came from (indexes in the command list from `compile`). Text lines don't have them. Conversions that combine several tags into one line (`[keyframe]` … `[endkeyframe]` and so on) list all the combined tags
- `kind` is `text` (text), `command` (commands, `@set` and so on), `label`, `if` `elif` `else` `end` (the `[if]` family, and `cond=` on tags other than choice tags),
  `choice` `option` `choice-end` (choices. `cond=` on a choice tag is `if=` on the `option` line, and no `if` or `end` line appears),
  `script` (`[iscript]` … `[endscript]`), `define` (macros) or `comment` (`// TODO ks:`)
- The file that gathers the macros (`macros.lim`) has `source` set to `null` and no line mapping

## How it works

1. Rewrite the base .lim and the current .lim into forms that behave the same way in TyranoScript ("Rules only Liminalia has" below)
2. Compare the base .lim and the current .lim line by line (ignoring indentation). Within the same block, a removed line and an added line of the same kind that are similar are paired as an edit
3. Use the source map to group the lines of the base .lim into ranges of .ks lines (lines whose ranges overlap become one. Text includes the `#Name` line just before it).
   .ks lines that don't correspond to any line (TyranoBuilder's `[tb_start_text]` `[_tb_end_text]`, tags that aren't written, blank lines and comments) are left as they are
4. Rewrite the .ks from the beginning. Parts that didn't change stay exactly as they are, character for character. Parts that changed are handled as follows
5. Import the rewritten .ks again and compare it with the current .lim

| Change in .lim | .ks |
|---|---|
| Editing a text line | Only that part of the text is rewritten. The speaker line, `[p]`, indentation, the text block wrapper and the line breaks made with `[r]` are kept |
| Adding a text line | Placed to match the surrounding style (inside the text block. If the speaker changes, a `#Name` line is added, written the way the base .ks writes speaker lines) |
| Deleting a text line | That line and the `#Name` line for it are deleted. If needed, a `#Name` line is added so that the speaker of later lines doesn't change |
| Changing the speaker | The `#Name` line is replaced or added |
| Syntax inside text | `{r base\|ruby}` (ruby: small reading aids above characters) uses the base's style (`｜base《ruby》`, `[srb text=…]base[erb]` or `[ruby text=…]`, whichever is most common in that line, then the file, then the project). `{click}` `{br}` become `[l]` `[r]`. `{noclick}` at the end of a line means the line gets no `[p]` at its end (removing it adds `[p]`). The display name for a line, `{name …}`, doesn't exist in TyranoScript, so it's written back as the speaker with a warning. `{= expr}` becomes `[emb exp=…]`, `{speed 0ms …}` becomes `[nowait]` … `[endnowait]`, `{speed …}` becomes `[delay speed=…]` … `[resetdelay]`, `{b}` `{i}` `{c}` `{size}` become `[font …]` … `[resetfont]`, `{mark}` becomes `[mark]` … `[endmark]`, and `{@command}` is written back as a command |
| Editing a command line | Only the parameters of the original tag are rewritten (the spacing between parameters, quotes, order and parameters that aren't converted are kept) |
| Adding a command line | Made using a nearby tag that became the same command as a model (in the same file, or another file if there's none). When it's added between text, the text block is closed before it and reopened after it |
| Deleting a command line | The tag is deleted (the whole line if the line has only that tag) |
| Labels | `*name` is rewritten, added or deleted (the heading in `*name\|heading` is kept) |
| `@if` `@elif` `@else` `@end` | `[if exp=…]` `[elsif exp=…]` `[else]` `[endif]` (expressions are converted back, `game.` → `f.` and so on). An `@if` that came from `cond=` becomes that tag's `cond` |
| Choices | Each choice line is one `[glink]` (or similar). Edits to the wording or jump target change those parameters, additions use the neighboring choice as a model, and the `@end` of `@choice` is `[s]`. The display condition `if=(expr)` is that tag's `cond` (added, edited or deleted; the expression is converted back as for `@if`). For `[link]` … `[endlink]` choices, the text between them and the `[link]` parameters (including `cond`) are rewritten, and additions use a neighboring `[link]` line that ends with a line break (`[r]`) as a model |
| `@set` | `exp` of `[eval]` / `[tb_eval]` (for TyranoBuilder's `[tb_eval]`, the editor fields `name` and `val` are updated to match) |
| Adding `@script` | `[iscript]` … `[endscript]` |
| Adding a comment (`//`) | A `;` comment |
| A new .lim | A new .ks (in the project's style. In a TyranoBuilder project, it's wrapped in text blocks. `[_tb_system_call]` isn't written) |
| A deleted .lim | The .ks isn't deleted. It's reported as a candidate for deletion |

### Rules only Liminalia has

Liminalia rules that have no counterpart in .ks are written out as .lim lines before comparing (`packages/ks-import/src/backport/lower.ts`). Line numbers in the report are those of the original .lim.

| Rule | Writing back |
|---|---|
| Command defaults (`commandDefaults` in `liminalia.json`) | Before comparing, the defaults are written into the parameters left out in the current .lim (including calls to `@define` macros). The base .lim keeps the standard defaults from the time of the import. A line where you removed a value equal to the default doesn't change the .ks, and if you change a default, the new value is also written into the tags of lines that left it out |
| Showing one character's sprite at a time (`solo=true` on `@chara`) | Expanded into two lines, `@chara-hide-all time=…` and `@chara` without `solo`, before comparing (including when it's set by the project's defaults). In .ks, the character also disappears once and is shown again |
| Hiding everyone and showing a sprite (`clear=…` on `@chara`) | Expanded into two lines, `@chara-hide-all time=…` with the given hiding time and `@chara` without `clear`, before comparing |
| Scene changes (`@scene-change`) | Expanded into the lines `@mask time=fade-out` `@chara-hide-all` `@bg background time=hold` `@mask-off time=fade-in` before comparing (if the background is left out, `@wait hold` replaces `@bg`. If the BGM is stopped or changed, `@stop-bgm` or `@bgm` comes right after `@mask`). In .ks this becomes the sequence `[mask]` `[chara_hide_all]` `[bg]` `[mask_off]` (modeled on the same tags in the project). Hiding the message window for the fade-in (`hide-window`) isn't written to the .ks |
| Sprites at a scene change (`hide-chara`, `hide-who`, `hide-chara-at`, `hide-fade`) | With `hide-chara=false`, the sprites aren't hidden. With `hide-who`, it's expanded into `@chara-hide`, otherwise into `@chara-hide-all`. `hide-chara-at=start` puts it before `@mask` and `covered` after it, and `hide-fade` is copied to `time` of the hiding line. Dynamic timings aren't converted |
| Unlocking a CG when it's shown (showing an image from `extra.cg` with `@bg` or a similar command unlocks it) | Before comparing, `@cg-unlock` is added after each line that shows an image listed in `extra.cg` if the same run (consecutive lines with only commands in between) has no `@cg-unlock` (in both the base and the current .lim. The `id` of `[tb_cg]` is that image's id in `extra.cg`). CGs added through `extra.cgAuto` aren't in TyranoBuilder's CG registry, so nothing is added for them. If you delete an unnecessary `@cg-unlock` from the .lim, the `[tb_cg]` stays |

The check doesn't compare `@cg-unlock` lines that aren't needed because the image is unlocked when it's shown (the import doesn't write them).

To turn a command line back into a .ks tag, the import conversion (the built-in conversion, the standard mapping `STD_MAPPINGS`, and `mappings` and `tags` in the project's `./import`) isn't inverted.
Instead, the parameters of a model tag are changed one at a time (two at a time if that doesn't get closer), each result is run through the import conversion, and the ones that get closer to the target line are kept.
It succeeds when the converted result means the same as the target line. The candidates for changes (.ks parameter names) come from `params` in the mappings, the parameter names of the built-in conversion, and the parameters in the model tag.

## What can't be written back

Places that couldn't be written back are listed under “書き戻せなかった箇所” (places that couldn't be written back) in the report, and the .ks is left as it was (added lines are left as `; lim backport: …` comments). They also show up as differences in the check.

- Edits to lines where the import settings replaced `[iscript]` with a command (`scriptRules`). Edits to the contents of `@script` (JS that couldn't be imported)
- Adding `@define` (macros), and changes to the file that gathers the macros (`macros.lim`). Fix `[macro]` in the .ks by hand
- Syntax that TyranoScript doesn't have: `@while`, `@with` (and `@content` and `@return (expr)` in macros), `@staff-roll`, `enter` `slide` on `@chara`, `exit` on `@chara-hide`, `{fx}` in text,
  and the progress functions in expressions (`visits()` `read()` `chosen()` `lang()` `platform()` `app()` `replaying()` `chapter()`)
- Editing only some of the lines that came from one .ks line (one of the two pieces of text in a line with two `[p]`s, adding a line inside an `@if` that came from `[cond=…]`, and so on)
- Commands with neither a model nor a mapping (ones that never appeared in the import and aren't in the built-in conversion or the mappings), and edits to tags that the import wrote in the generic form (`@tagname param…`)
- .lim syntax that can't be made from a single tag (things that are split into two tags in .ks)
- Choice text that contains ruby or commands

You can add these with `backport` (the reverse conversion) in the import settings. For each command name, write a function that returns the text of the .ks tag from the .lim line (and the original tag).
The returned tag is also run through the import conversion to check it. If it differs, it's used as a model and the parameter changes continue.

```ts
const profile: TyranoImportProfile = {
  backport: {
    // @stamp image=a.png → [stamp_show storage="a.png"]
    stamp: (line, original) => original ?? "[stamp_show]",
  },
};
```

## Things to watch out for

- Writing back also imports the base .ks again with the current import conversion and compares the result with the base .lim. If the conversion of the engine or the import settings has changed since the base was made,
  this appears under “注意” (notes) in the report (in that case, the differences in the check also include the effects of the changed conversion)
- The check compares .lim with .lim, so it doesn't check how the .ks looks (the arrangement in TyranoBuilder's editor). Before `--write`, look at the report and at the diff of the written-back .ks
- Variations in how text lines are written (how characters are escaped), the order of command parameters, how times are written (`1s` and `1000ms`), and whether parameters equal to their defaults are present are all treated as the same
- `--write` doesn't write files that were edited on the TyranoScript side after you switched. If you edited both sides, merge the written-back .ks and the import source by hand
- Information that the import conversion loses (the color, size and position of `[glink]`, `html5` on `[playbgm]`, and so on) is carried over as it is from the original tag and the model tag
- A base made by an import from before `cond=` on choice tags became `if=(expr)` on the choice line has an empty `@if` / `@end` before the choice in the base .lim.
  If you leave the project's .lim as it is, the check reports a difference, so rewrite that choice in the `if=(expr)` form (as in the .lim reimported with `--make-base`).
  After that, writing back combines the deletion of `@if` / `@end` and the addition of `if=` into the `cond` of the same tag, and the .ks doesn't change
- A base made by an import from before `zindex` on `[chara_show]` became `z=` on `@chara` has no `z=` in the base .lim (that version didn't convert zindex).
  In a project with `[chara_show]` tags that set `zindex` (to something other than 1), the difference between the base and the current conversion appears under “注意” (notes) in the report, and if you edit such a line and write it back,
  the check reports the presence or absence of `z=` as a difference. Add `z=` (the zindex value) to that line in the project's .lim, or remake the base with `--make-base` from the .ks at the time you switched.
  Projects that don't set `zindex` aren't affected. Writing back turns `z=` back into `zindex`
