# kaimei (改名)

A safe, scriptable batch renamer for the command line: new names come from
a template with variables and filters, sed-style expressions, or both.

- **Preview first.** Without `-y` nothing is renamed; you get old → new with
  the changed part highlighted.
- **All or nothing.** If any new name is empty, clashes with another, or
  belongs to a file outside the batch, nothing is renamed (exit 1).
- **Never overwrites.** Renames use `renameat2(RENAME_NOREPLACE)`.
- **Swaps, cycles and case-only changes just work.** They go through a
  temporary name, so `a.jpg → A.jpg` works on vfat/exFAT too.
- **Undo anything.** Every applied run is journaled *before* each rename, so
  `kaimei undo` works even after a crash part way through.
- **Folders from templates** with `--mkdir`, and **hand edits** in your
  editor with `-E`, both with the same preview, checks and undo.
- **Clean names.** New names are sanitized (`--safe posix|portable|windows`),
  normalized to NFC, and kept under the 255-byte limit without splitting a
  character or losing the extension.

## Quick start

```sh
kaimei -e 's/IMG_//' *.jpg          # preview: shows old → new, changes nothing
kaimei -e 's/IMG_//' -y *.jpg       # the same, and rename
kaimei undo                         # put it back
```

A new name comes from a **template** (`-t`), **sed expressions** (`-e`), or
both (the template first):

- `-t '{stem|lower}.{ext}'`: fields in braces are variables, optionally
  with filters after `|`. `{stem}` is the name without its extension,
  `{ext}` the extension, `{name}` both, `{n:03}` a counter.
- `-e 's/old/new/g'`: a regex replacement on the stem (the extension is
  left alone unless the expression mentions `\.`).

Three commands help you build one:

```sh
kaimei vars song.flac               # every variable this file has, with its value
kaimei translit --list              # every transliteration filter
kaimei translit romaji 東京の天気   # try a filter on some text: toukyou no tenki
```

`kaimei --help` has a page of examples, and `man kaimei` has everything.

## Japanese names

The `romaji` filter turns kanji, hiragana and katakana into romaji. Kanji
are read with a dictionary built into kaimei, with a space between words:

```sh
kaimei -t '{stem|romaji}.{ext}' *
# 東京の天気.txt → toukyou no tenki.txt
```

**1. Try it on text first.** `kaimei translit` runs a filter on whatever
you type, so you can find the right one before touching any files:

```sh
kaimei translit romaji 坂本龍一
# → sakamoto ryuuichi
kaimei translit romaji:none 坂本龍一
# → sakamoto ryuichi
ls | kaimei translit romaji         # a whole folder, one name per line
```

**2. Pick a style.** The long-vowel style is the option after `romaji:`;
add `|title` for capitals, `|slug` for lower case with hyphens:

| Template field                 | 東京の天気          | 坂本龍一             |
|--------------------------------|---------------------|----------------------|
| `{stem\|romaji}`               | toukyou no tenki    | sakamoto ryuuichi    |
| `{stem\|romaji:macron}`        | tōkyō no tenki      | sakamoto ryūichi     |
| `{stem\|romaji:double}`        | tookyoo no tenki    | sakamoto ryuuichi    |
| `{stem\|romaji:none}`          | tokyo no tenki      | sakamoto ryuichi     |
| `{stem\|romaji:none\|title}`   | Tokyo No Tenki      | Sakamoto Ryuichi     |
| `{stem\|romaji:none\|slug}`    | tokyo-no-tenki      | sakamoto-ryuichi     |
| `{stem\|romaji:kunrei}`        | toukyou no tenki    | sakamoto ryuuiti     |
| `{stem\|yomi\|romaji}`         | toukyounotenki      | sakamotoryuuichi     |
| `{stem\|yomi}`                 | とうきょうのてんき  | さかもとりゅういち   |
| `{stem\|yomi:kata}`            | トウキョウのテンキ  | サカモトリュウイチ   |

The default (`wapuro`, spelled as typed on a Japanese keyboard) is the
only one that `kana` turns back into exactly the same kana; `none` reads
best but loses the long vowels. To make another style your default, set
`romaji-long = "macron"` in `~/.config/kaimei/config.toml` or pass
`--romaji-long macron`.

```sh
kaimei -t '{stem|romaji:macron}.{ext}' *
# 東京の天気.txt → tōkyō no tenki.txt
kaimei -t '{stem|romaji:none|title}.{ext}' *
# 東京の天気.txt → Tokyo No Tenki.txt
kaimei -t '{stem|romaji:none|slug}.{ext}' *
# ローマ字 テスト.txt → romaji-tesuto.txt
```

**3. Particles and numbers.** When a name has kanji, は, へ and を come
out as said (wa, e, o), and counters after digits are read as counters. To
keep the particles as spelled, read the kanji with `yomi:space` first:

```sh
kaimei -t '{stem|romaji|title}.{ext}' *
# 君の名は.mp3 → Kimi No Na Wa.mp3
kaimei -t '{stem|yomi:space|romaji|title}.{ext}' *
# 君の名は.mp3 → Kimi No Na Ha.mp3
kaimei -t '{stem|romaji}.{ext}' *
# 写真 2024年8月.jpg → shashin 2024nen 8gatsu.jpg
```

A name with **no kanji** is romanized exactly as spelled, and kaimei
doesn't add spaces to it: without kanji, where one word ends and the next
begins is only a guess.

```sh
kaimei -t '{stem|romaji}.{ext}' *
# ひらがな テスト.txt → hiragana tesuto.txt
# きみのなは.mp3 → kiminonaha.mp3
```

**4. Fix wrong readings.** The dictionary guesses, and names can be read
several ways (it reads 米津 as よねつ). Put corrections in
`~/.config/kaimei/readings.csv`, one `word,reading` per line, a space in the
reading for a word break:

```sh
echo '米津玄師,よねづ けんし' >> ~/.config/kaimei/readings.csv
kaimei translit romaji 米津玄師     # yonedu kenshi
```

**5. Rename.** Check the preview, then add `-y`. `-E` opens the proposed
names in your editor first, to fix a few by hand:

```sh
kaimei -t '{stem|romaji:none|title}.{ext}' -y *
kaimei -E -t '{stem|romaji:none|title}.{ext}' *
kaimei undo                         # changed your mind
```

**Only part of a name.** Apply the filter to a `--match` capture, or to a
tag:

```sh
kaimei --match '^(\d+) (.+) - (.+)\.' -t '{orig.1} {orig.2} - {orig.3|romaji|title}.{ext}' *
# 01 Intro - 坂本龍一.mp3 → 01 Intro - Sakamoto Ryuuichi.mp3
kaimei -t '{track:02} {title|romaji:macron|title}.{ext}' *.mp3
kaimei -t '{artist|romaji|title} - {title|romaji|title}.{ext}' *.mp3
```

**A whole tree**, folders too. A folder's `{stem}` is its whole name and
its `{ext}` is empty, so one template does both:

```sh
kaimei -R --dirs -t '{stem|romaji:none|title}.{ext}' ~/music/j-pop
# 坂本龍一 → Sakamoto Ryuichi
```

**The other way**, and between scripts:

```sh
kaimei -t '{stem|yomi}.{ext}' *          # kanji → hiragana
# 東京の天気.txt → とうきょうのてんき.txt
kaimei -t '{stem|kana}.{ext}' *          # romaji → hiragana; English stays
# Track 01 - tsuki.mp3 → Track 01 - つき.mp3
kaimei -t '{stem|kkana}.{ext}' *         # romaji → katakana
# toukyou.txt → トウキョウ.txt
kaimei -t '{stem|kata}.{ext}' *          # hiragana → katakana (hira: back)
# ひらがな.txt → ヒラガナ.txt
kaimei -t '{stem|nfkc}.{ext}' *          # full-width letters, half-width kana
# ＡＢＣ１２３ ｶﾀｶﾅ.txt → ABC123 カタカナ.txt
```

**Garbled names** from an old Windows archive or zip are often Shift-JIS
bytes; this converts them to UTF-8 (undo puts the old bytes back):

```sh
kaimei -R --dirs --from-encoding sjis ~/old-archive
```

## Examples

Every command below only previews; add `-y` to rename, and `kaimei undo` to
take it back. A `#` line under a command shows what it does to one file.

### Simple changes

```sh
kaimei -e 's/IMG_//' *.jpg
# IMG_0042.jpg → 0042.jpg
kaimei -e 's/ +/_/g' -e 's/\.JPE?G$/.jpg/i' *     # several, in order
# my holiday photo.JPEG → my_holiday_photo.jpg
kaimei -t '{stem|lower}.{ext|lower}' *
# Holiday.JPG → holiday.jpg
kaimei -t '{stem|title}.{ext}' *
# the long road.mp3 → The Long Road.mp3
kaimei -e 's/\w+/\u&/g' *                         # Title Case, sed style
# the long road.mp3 → The Long Road.mp3
kaimei -t '{stem|slug}.{ext}' *
# Hello, World! (Live).mp3 → hello-world-live.mp3
kaimei -t '{stem|re:"\s*\(\d+\)$":""}.{ext}' *     # browser download " (1)"
# report (1).pdf → report.pdf
kaimei -e 's/(\d+)-(\d+)/$2-$1/' *                 # captures: $1, \1, ${name}
# 2024-11.pdf → 11-2024.pdf
kaimei -e 'y/abc/ABC/' *                           # character mapping
# cabbage.txt → CABBAge.txt
kaimei --fullwidth -t '{stem}.{ext}' *             # ? : / → ？ ： ／
```

### Numbering

```sh
kaimei -t '{n:03}_{stem}.{ext}' *.jpg
# beach.jpg → 001_beach.jpg
kaimei --sort mtime -t 'scan_{n:03}.{ext}' *.pdf               # oldest first
kaimei --start 10 --step 10 -t '{n:03} {stem}.{ext}' *
kaimei --sort mtime -t '{mtime:%Y%m%d}_{n:02}.{ext}' *         # date + counter
kaimei -R --counter-per-dir -t '{n:02} {stem}.{ext}' ~/albums  # restart per folder
```

### Other languages

```sh
kaimei -t '{stem|ascii}.{ext}' *
# Café Señor.txt → Cafe Senor.txt
kaimei -t '{stem|ascii:de}.{ext}' *
# Müller.txt → Mueller.txt
kaimei -t '{stem|tr:ru-simple}.{ext}' *
# Елена.txt → Yelena.txt
kaimei -t '{stem|compose}.{ext}' *                 # typed digraphs
# M\u:ller.txt → Müller.txt
kaimei -t '{stem|ascii:de|romaji:none}.{ext}' *    # plain ASCII, everything
# Müller 東京.txt → Mueller tokyo.txt
kaimei -t '{stem|restore:de}.{ext}' *              # Mueller → Müller (guesswork)
```

**Your own table**: put `NAME.csv` (`from,to` per line) or `NAME.toml` in
`~/.config/kaimei/translit/`, then

```sh
kaimei translit --test tr:NAME 'some text'
kaimei -t '{stem|tr:NAME}.{ext}' *
```

### Music, photos, videos and PDFs

`kaimei vars FILE` shows what a file has.

```sh
kaimei -R --include '*.flac' --include '*.mp3' --missing skip \
       -t '{track:02} - {title}.{ext}' ~/music/album
kaimei -t '{disc?"1"}-{track:02} {title}.{ext}' *.flac           # multi-disc
kaimei -t '{exif.date:%Y%m%d_%H%M%S}.{ext|lower}' *.JPG          # when taken
kaimei -t '{video.date:%Y%m%d_%H%M%S}_{width}x{height}.{ext|lower}' *.mp4
kaimei -t '{pdf.created:%Y-%m-%d} {title?stem} ({pages}p {pdf.paper?"?"}).{ext}' *.pdf
kaimei -t '{stem}.{type.ext?ext}' *                              # lying extensions
kaimei -t '{stem} [{crc32|upper}].{ext}' *.mkv                   # CRC in the name
kaimei -t '{sha256:16}.{ext}' ~/inbox/*                          # copies collide
```

### Patterns in the old name

```sh
kaimei --match '^Track (\d+) - (?P<t>.+)\.' -t '{orig.1:02} {orig.t|title}.{ext}' *
# Track 7 - some title.flac → 07 Some Title.flac
```

Files that don't match have no `{orig.1}`; add `--missing skip` to leave
them alone.

### Folders and trees

```sh
kaimei --mkdir -t '{albumartist?artist}/{album}/{track:02} {title}.{ext}' *.flac
kaimei --mkdir -t '{exif.date:%Y}/{exif.date:%m}/{stem}.{ext}' *.JPG
kaimei -R --include '*.mp3' --exclude demos -t '{stem|lower}.{ext}' ~/music
kaimei -R --dirs --safe windows --ci -y /media/stick   # FAT-safe, folders too
```

With `--mkdir`, a `/` inside a tag such as "AC/DC" stays part of the name.

### By hand

```sh
kaimei -E *.mp3                                   # edit names in $VISUAL/$EDITOR
kaimei -E -t '{track:02} {title}.{ext}' *.mp3     # start from a template
```

You see the preview and say yes before anything changes; deleting a line
leaves that file alone.

### Undo and history

```sh
kaimei undo                  # the newest run not yet undone
kaimei undo -n               # only show what it would put back
kaimei history -v            # every run, with its command line and renames
kaimei undo RUN-ID           # an older run; undoing an undo redoes it
kaimei forget --older-than 90d      # list journals more than 90 days old
kaimei forget --older-than 90d -y   # delete them (those runs can't be undone after)
```

Journals live in `~/.local/state/kaimei/runs` and are kept until you
`forget` them (by age, by run id, `--all`, or `--gone` for runs whose files
are no longer at the names the run gave them).

## Reference

Templates: `{var:format?fallback|filter:arg}`. Variables are `name`, `stem`,
`ext`, `parent`, `path`, `n` (counter: `--start`, `--step`,
`--counter-per-dir`), `size`, `size.h`, `mtime`/`ctime`/`atime` (strftime
formats), `orig.N` (captures of `--match`), and metadata read from the
files only when a template uses it: audio tags (`title`, `artist`, `album`,
`albumartist`, `track`, `tracktotal`, `disc`, `year`, `genre`, `composer`,
`duration`, `bitrate`), images (`width`, `height`, `exif.date`,
`exif.model`, ...), PDFs (`pages`, `pdf.title`, `pdf.created`,
`pdf.paper`, ...), videos through ffprobe (`vcodec`, `acodec`, `fps`,
`video.date`, plus width/height/duration) and the content type (`type`,
`type.ext`). Filters: `lower`, `upper`,
`title`, `sentence`, `trim`, `replace`, `re`, `pad`, `trunc`, `slug`, `nfc`,
`nfkc`, and transliteration: `ascii[:de|da|no|sv|fi]`, `compose` (digraphs
like `M\u:ller`), `restore:de` (experimental), `hira[:vowel]`, `kata`,
`half`, `full`, `kana`, `kkana[:loan]` (Hepburn, Kunrei and IME spellings;
a word converts only if it is all romaji), `romaji[:hepburn|kunrei|nihon]
[:wapuro|macron|double|none]` (the default wapuro style converts back to
the same kana exactly; kanji are read first), `yomi[:kata|space|particles]`
(kanji → kana readings, from a built-in dictionary; corrections go in
`~/.config/kaimei/readings.csv`), and `tr:NAME[:reverse]` with your own TOML or CSV
table in `~/.config/kaimei/translit/` (`tables/ru-simple.toml` is a built-in
example, with a `[[rule]]` for context: е is "ye" at the start of a word
and after a vowel). Content hashes `{crc32}`, `{md5}`, `{sha1}`, `{sha256}`
read the whole file; `{sha256:12}` keeps the first 12 digits. A field with no value stops the run unless it has a fallback or you
pass `--missing=skip|empty`. Template mistakes are caught before anything
runs.

The template is filled in first, then `-e` expressions run on the result.
Expressions see only the stem (the extension is left alone) unless they
mention a literal dot (`\.` or `[.]`); `--stem-only` and `--whole-name`
override that. `--trim-dot` removes a dot left at the end of a name (as
`{stem}.{ext}` leaves on a file with no extension; the default `portable`
profile already does this). Defaults for options can live in
`~/.config/kaimei/config.toml` (sample: `dist/config.toml.example`);
command-line options win, and each on/off setting has a `--no-` form
(`--no-ci`, `--no-trim-dot`, ...) for switching it off for one run. The
regex dialect is Rust's `regex` crate: ERE-like, linear time, no
backreferences in the pattern. See `man kaimei` for everything.

Exit codes: 0 success or clean preview, 1 nothing renamed (errors), 2 a run
stopped part way (undo is available).

The examples in this file, in `kaimei --help` and in the man page are run
by `crates/kaimei/tests/doc_examples.rs`: a `kaimei` line followed by
`# OLD → NEW` must really turn OLD into NEW.

## Build and install

Pure Rust, no C libraries. Minimum Rust is 1.85 (Debian 13's), and every
locked dependency builds with it.

```sh
cargo build --release --locked
sh dist/make-bin-tarball.sh            # as your user → /var/tmp/kaimei-bin-*.tar.gz
sh dist/make-bin-tarball.sh --static   # one binary that runs on any x86-64 Linux
# then in a root shell:
sh /var/tmp/install-kaimei-bin.sh --dry-run /var/tmp/kaimei-bin-<...>.tar.gz
sh /var/tmp/install-kaimei-bin.sh /var/tmp/kaimei-bin-<...>.tar.gz
sh /var/tmp/install-kaimei-bin.sh --uninstall      # removes exactly what it installed
```

`dist/test-install.sh TARBALL` runs the installer in a scratch directory
(no root): install, upgrade, uninstall, and checks nothing is left behind.

Everything goes under `/usr/local`: the binary, man page, bash/zsh/fish
completions, a sample config at `/usr/local/share/kaimei/config.toml.example`
and the example tables in `/usr/local/share/kaimei/translit/`. For another
machine, `dist/make-src-tarball.sh` packs the committed tree (`--vendor`
adds every dependency, for building offline); see `dist/INSTALL-debian.md`
for trixie (from source) and bookworm (the static binary).

`./check.sh` is the full local gate: clippy, tests (including property and
crash tests of the planner, and snapshot tests of real runs), an MSRV audit
of `Cargo.lock`, and cargo-deny. After an intended output change,
`KAIMEI_UPDATE_SNAPSHOTS=1 cargo test -p kaimei --test snapshots` rewrites
the golden files in `crates/kaimei/tests/snapshots/`; review the diff.

## Status

- v0.1, the safe core: sed-style `-e`, preview / `-y`, the planner, journal,
  `undo` and `history`.
- v0.2: templates, file and date variables, counters, `--match` captures,
  text filters, fallbacks and `--missing`, `kaimei vars`, `config.toml`.
- v0.3: transliteration in the standalone `kaimei-translit` crate: Latin
  folding and digraphs, kana/romaji both ways, width, user tables, and
  `kaimei translit` for trying filters.

- v0.4: metadata in the `kaimei-meta` crate (lofty, imagesize,
  kamadak-exif, lopdf with a pdfinfo fallback, infer), `--jobs` with
  spinning-disk detection. Timings: `docs/performance.md`.

- v0.5: video via ffprobe, shell completions, a static binary for older
  systems, a vendored source tarball, `--dry-run` and upgrade cleanup in the
  installer, recipes.
- v0.6: `--mkdir` (folders from templates, expressions or edits; undo
  removes the folders it made) and `-E`/`--edit` (edit the names in your
  editor, vidir style, minus the deleting).
- v0.7: context rules in transliteration tables (`[class]` and `[[rule]]`:
  "after a vowel", "at the start of a word"; ru-simple now gives Yelena,
  podyezd) and content hashes as variables (`{crc32}`, `{md5}`, `{sha1}`,
  `{sha256:12}`), with a progress line.
- v0.8: kanji readings (`yomi`, and kanji in `romaji`, via Lindera + IPADIC
  built in; `readings.csv` for corrections) and `--from-encoding` (Shift-JIS,
  EUC-JP, GBK, Big5, EUC-KR, CP1252 names to UTF-8, undoable byte for byte).
- 0.8.1: examples everywhere: `kaimei --help` (the short `-h` stays short),
  the subcommands' help, a step-by-step Japanese section here and in the
  man page; the examples' results are tested.
- 0.8.2: `romaji` writes は, へ, を as said in names with kanji (kimi no na
  wa); digits before a counter are kept and the counter read as one
  (2024年8月 → 2024nen 8gatsu, was 2024nen8tsuki); kana that isn't joined
  to kanji is left as written (no ひら が な); `kaimei ... | head` no
  longer panics (and a `-y` run still finishes).
- 0.8.3: fixes from a code review: the `--edit` list is always a new
  private file (it could overwrite a file through a symlink in a shared
  /tmp); a target that is a hard link of a file in the batch is a collision
  in the preview, not a failure half-way; undoing an older run leaves
  alone names a later run has renamed since; `--from-encoding` names get
  metadata and hashes; a reader that crashes costs one file a warning; huge
  widths are an error; a closed stderr no longer stops a run. New:
  `kaimei forget` deletes old journals (by id, `--older-than`, `--gone`,
  `--all`).
- 0.8.4: licence change only: CC0 where the code is not protected by
  copyright, GPL 3.0 or later where it is (was MIT or Apache-2.0); the
  tarballs carry the licences of the crates built in.

Still to come, per `batch-renamer-plan.md`: more scripts.

## License

CC0 1.0 (public domain) where the code is not protected by copyright, which
is the position for AI-written code in many countries, and most of this was
written by an AI model; GNU GPL 3.0 or later where it is. The exact terms
are in `LICENSE`, with the two licence texts beside it.

The Rust crates built into the program keep their own licences:
`THIRD-PARTY-LICENSES.txt`.

The kanji dictionary built into the binary is IPADIC (via Lindera), under
its own permissive licence: see `dist/IPADIC-NOTICE.txt`, installed as
`/usr/local/share/doc/kaimei-bin/IPADIC-NOTICE.txt`.

The static binary also contains parts of the GNU C Library, under the LGPL:
`dist/GLIBC-NOTICE.txt` says where its source is and how to rebuild with
your own.
