Metadata-Version: 2.4
Name: zotdocx
Version: 0.4.0
Summary: Repair Zotero citation fields in .docx files: GB/T 7714, IEEE, Nature, Vancouver
Author: zotdocx contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/HbS66-pro/zotdocx
Project-URL: Repository, https://github.com/HbS66-pro/zotdocx
Project-URL: Issues, https://github.com/HbS66-pro/zotdocx/issues
Keywords: zotero,docx,citation,word,bibliography,gbt7714
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Text Processing :: Markup
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: lxml
Dynamic: license-file

# zotdocx

[![tests](https://github.com/HbS66-pro/zotdocx/actions/workflows/tests.yml/badge.svg)](https://github.com/HbS66-pro/zotdocx/actions/workflows/tests.yml)

**English** | [中文](README.zh-CN.md)

When writing Word manuscripts with Zotero, three citation issues come up repeatedly: AI-drafted or rewritten manuscripts contain plain-text citations (`[1]`, `[2,3]`, `[4-6]`) that otherwise have to be re-inserted into Zotero one by one; deleting or moving a citation leaves plain-text `[12]` refs inside tables, captions, and notes stuck on old numbers; and heavy editing splits citation fields across paragraphs or leaves broken links after library edits.

`zotdocx` inspects and repairs Zotero citation fields directly inside `.docx` files. It only writes to the document you pass in, leaving your Zotero database untouched and preserving your existing layout.

## Install and quick try

Requires Python 3.9+ (`lxml` is the only dependency):

```bash
pip install zotdocx
```

To see what it reports before touching a real manuscript, run `demo`:

```bash
zotdocx demo
```

This creates a small synthetic `demo.docx` in the current directory with a couple of intentional citation defects, runs `status`, and prints a dry-run preview of `renumber`:

```text
demo.docx
  部件 7 个；document.xml 0.00 MB
  样式 未记录

域      3 = 引注 2 + 书目 1 + 其他 0
        跨段落：引注 0 · 书目 0
        位置：正文 2
条目    2 个
编号   显示 1–2；同条目多编号 0；单条目编号不符 2；多条目编号不符 0
上标   数字制引注 2 个：整条上标 2 · 整条非上标 0 · 域内混排 0
纯文本 正文 1 · 表格 1 · 表注图注 1 · 图题表题 1
```

Console output is currently in Chinese. For scripts or CI checks, use `--json` and exit codes (`0` = clean, `1` = issues found, `2` = usage or file error).

## Which command to run

Every command that modifies a `.docx` runs as a **dry run by default**. Add `--apply` to write changes; the original file is backed up as `*.bak_<timestamp>` (or pass `--out new.docx` to write elsewhere).

| Situation | Command |
|---|---|
| Check what is wrong in a manuscript | `zotdocx status paper.docx` |
| Citation fields split across paragraphs, or stored vs. shown numbers disagree | `zotdocx heal paper.docx --apply` |
| Numbers are out of order, or table/caption/note `[12]` refs need syncing | `zotdocx renumber paper.docx --apply` |
| AI-drafted or plain-text `[1]`, `[2,3]`, `[4-6]` in body paragraphs should become live Zotero fields (even with zero existing Zotero fields) | `zotdocx lift paper.docx --apply` |
| Citations point to items removed or re-imported in Zotero | `zotdocx repair paper.docx --apply` |
| Zotero keeps throwing "Cannot delete range" on refresh | `zotdocx patch --zotero-dir "C:\Program Files\Zotero" --auto --apply` |

A typical cleanup pass on a numbered thesis looks like:

```bash
zotdocx status paper.docx
zotdocx heal paper.docx --apply
zotdocx renumber paper.docx --apply
```

## Commands reference

| Command | Summary |
|---|---|
| `demo` | Create a synthetic `demo.docx` and run `status` + dry-run `renumber` |
| `status` | Report field structure, item count, numbering mismatches, superscript state, plain-text refs, and broken links |
| `heal` | Pull cross-paragraph field ends back into the right paragraph and align stored vs. displayed numbers |
| `renumber` | Reorder citations by first appearance and sync plain-text numbers in tables, captions, and notes |
| `lift` | Convert plain-text body citations (`[1]`, `[2,3]`, `[4-6]`) into live superscript Zotero fields, reusing existing fields or synthesizing new ones from the reference list + `zotero.sqlite` |
| `repair` | Relink broken citations by item key or exact title against `zotero.sqlite` |
| `patch` | Inspect or apply the `omni.ja` workaround for Zotero's "Cannot delete range" error |

## Locating `zotero.sqlite`

`lift` (when synthesizing new fields), `repair`, and the broken-link check in `status` read `zotero.sqlite` via a temporary read-only copy (cleaned up right after reading). `zotdocx` checks these locations in order:

1. `--zotero-db <path>`
2. `ZOTERO_DB` environment variable
3. `~/Zotero/zotero.sqlite`

If no database is found, document-side checks still run and broken-link checking is skipped.

## How it handles the file

- Only `word/document.xml` is modified; every other file inside the `.docx` archive is copied byte for byte.
- Plain-text numbers inside table cells, figure/table captions, and notes stay plain text; `renumber` updates the digits without converting them into Zotero fields.
- Recognizes both Chinese (`图` / `表` / `注` / `参考文献`) and English (`Figure` / `Table` / `Note` / `References`) labels when scanning captions, notes, and bibliography sections.
- Works with any Zotero CSL style for `status`, `heal`, and `repair`. `renumber` and `lift` only apply to numeric styles (such as GB/T 7714, IEEE, Nature, and Vancouver) and are skipped for author-date styles like APA or Harvard.

## Fixing "Cannot delete range" (Zotero integration patch)

If Zotero repeatedly fails with **Cannot delete range** when refreshing, the bug happens inside Zotero's Word integration script rather than your `.docx`. You can patch it with:

```powershell
zotdocx patch --zotero-dir "C:\Program Files\Zotero" --auto --apply
```

`patch` backs up `omni.ja`, updates `integration.js` inside it using this project's own MIT-licensed snippet, and verifies the rebuilt archive before replacing the original. Note that Zotero updates overwrite `omni.ja`, so you will need to re-apply the patch after upgrading Zotero. Full details and manual steps are in [docs/integration-patch.md](docs/integration-patch.md).

One side effect: because the patched write path inserts plain text without `\super`, body citation numbers come out flat instead of superscript. The Word macro in [docs/word-superscript.md](docs/word-superscript.md) restores superscript formatting and keeps it updated on refresh. You can check superscript coverage at any time with `zotdocx status`:

```text
上标   数字制引注 32 个：整条上标 32 · 整条非上标 0 · 域内混排 0
```

## Known limitations

- Tested on Windows with Microsoft Word.
- When synthesizing fields from scratch, `lift` uses the manuscript's plain-text reference list as clues and matches strictly against `zotero.sqlite` by DOI or normalized title (with year/author disambiguation). Unmatched or ambiguous entries are skipped and reported (pass `--show-text` to print titles and raw reference lines), and the original plain-text bibliography is left intact.
- After running `lift --apply` on a fresh plain-text manuscript, open Word and click Zotero **Refresh** once to take over the new fields (Word will prompt for a citation style on first use), then insert a live bibliography with **Add/Edit Bibliography** if needed.
- `repair` matches strictly by item key or exact title; ambiguous items are reported for manual handling.
- `patch` requires write access to the Zotero installation folder and aborts without changing anything if `setText` does not match the expected pattern.

## Development and tests

Install from a local clone with `pip install .`, then run the test suite:

```bash
python tests/run_all.py
```

Tests build synthetic Chinese and English `.docx` fixtures on the fly (no real manuscripts or library data are stored in this repository) and run on GitHub Actions across Python 3.9, 3.11, and 3.13.

## License

MIT. See [LICENSE](LICENSE).
