This document compiles the Open Chinese Convert (OpenCC) project information to help quickly familiarize with the code structure, data organization, and accompanying tools.
- OpenCC is an open-source Chinese Simplified-Traditional and regional variant conversion tool, supporting Simplified↔Traditional, Hong Kong/Macau/Taiwan regional differences, Japanese Shinjitai/Kyujitai character forms, and other conversion schemes.
- The project provides a C++ core library, C language interface, command-line tools, as well as Python, Node.js and other language bindings. The dictionary and program are decoupled for easy customization and extension.
- Main dependencies:
rapidjsonfor configuration parsing,marisa-triefor high-performance dictionaries (.ocd2), optionalDartsfor legacy.ocdsupport, and optionalcppjiebaresources for the experimentalopencc-jiebasegmentation plugin.
- Dictionaries are maintained in
data/dictionary/*.txt, covering phrases, characters, regional differences, Japanese new characters, and other topic files; converted to.ocd2during build for acceleration. - Default configurations are located in
data/config/, such ass2t.json,t2s.json,s2tw.json, etc., defining segmenter types, dictionaries used, and combination methods. - Jieba-backed plugin configurations live under
plugins/jieba/data/config/, such ass2twp_jieba.json; they are packaged only when the optionalopencc-jiebaplugin is built or distributed. data/schemeanddata/scriptsprovide dictionary compilation scripts and specification validation tools.
- Put regional vocabulary differences, such as Mainland-to-Taiwan term choices and place-name translations, in
TWPhrases.txt/TWPhrasesRev.txt, not inTWVariantsPhrases.txt. Example: US state or territory names like特拉華 -> 德拉瓦,新澤西 -> 紐澤西, and美屬維爾京羣島 -> 美屬維京群島belong inTWPhrases.txt. - Reserve
TWVariantsPhrases.txtfor phrase-level exceptions to Taiwan variant character conversion, especially when a phrase must override character-level mappings fromTWVariants.txt. It is part ofs2tw,s2twp, andt2tw; using it for vocabulary translations will incorrectly affects2tw. - For
s2twpands2hkp, remember the conversion chain isSTPhrases/STCharacters -> regional phrases -> regional variants. The generatedSTPhrases_GeneratedFromRegionalPhrasesdictionary derives Simplified-to-regional-key entries from the first column ofTWPhrases.txtandHKPhrases.txt; standard Simplified-to-Traditional configs use it in both mmseg segmentation and the first ST conversion stage so whole regional keys do not get stranded in Simplified form. Add manualSTPhrases.txtentries when the generated mapping is not the desired plains2toutput, or whent2s(regional phrase key)does not match the real Simplified input. - Keep
TWPhrases.txtandTWPhrasesRev.txtbidirectionally consistent. Runbazel test //data/dictionary:dictionary_TWPhrases_reverse_mapping_testafter editing either file. - For intentional one-way Taiwan vocabulary conversions, keep the forward mapping in
TWPhrases.txtand add a self-mapping candidate on both sides sotw2spcan preserve the Taiwan term. For example, to makes2twpconvert信道 -> 通道without forcingtw2spto convert every通道back to信道, use信道 -> 通道plus通道 -> 通道inTWPhrases.txt, and makeTWPhrasesRev.txtmap通道 -> 通道 信道. The self-mapping keeps the reverse dictionary structurally consistent while making the reverse conversion prefer unchanged通道. - Use
python3 data/scripts/sort.py <file> <file>for edited dictionary files instead of hand-sorting. Dictionary tests enforce sorted unique keys. - Add tests to
test/testcases/testcases.jsonagainst the config that actually uses the dictionary. Taiwan vocabulary inTWPhrases.txtshould normally be tested withs2twp/tw2sp, nots2tw.
.ocd(legacy format) hasOPENCCDARTS1as the file header, with the main body being serialized Darts double-array trie data, combined withBinaryDictstructure to store key-value offsets and concatenation buffers. Loading process is detailed insrc/DartsDict.cppandsrc/BinaryDict.cpp. Commonly used in environments requiringENABLE_DARTSfor compatibility..ocd2(default format) hasOPENCC_MARISA_0.2.5as the file header, followed bymarisa::Triedata, then uses theSerializedValuesmodule to store all candidate value lists. Seesrc/MarisaDict.cpp,src/SerializedValues.cppfor details. This format is smaller and loads faster (e.g.,NEWS.mdrecordsSTPhrasesreduced from 4.3MB to 924KB).- The command-line tool
opencc_dictsupportstext ↔ ocd2(and optionallyocd) conversion. When adding or adjusting dictionaries, first edit.txt, then run the tool to generate the target format.
- The top-level build system supports CMake, Bazel, Python
pyproject.toml, with cross-platform CI integration. The Node.js native addon is built with Bazel (//node:opencc). src/*Test.cpp,data/config/*Test.cpp,plugins/jieba/tests/,test/, andtest/golden/contain tests covering dictionary matching, conversion chains, configuration validation, plugin segmentation, CLI behavior, and golden conversion outputs.- Tools
opencc_dict,opencc_phrase_extract(src/tools/) help developers convert dictionary formats and extract phrases. - Node.js tests live in
node/test.js. npm prebuilt binaries are built with Bazel viascripts/build-node-prebuild-bazel.sh(seenode/PUBLISHING.md). Thebinding.gyp/node-gyp source-build fallback has been replaced by a Bazel one: the native addon comes from@opencc/opencc-<platform>-<arch>scoped packages, and on platforms without onescripts/install.jsruns a full Bazel source build at install time (compiles//node:opencc, regenerates//data/dictionary:binary_dictionaries, and refreshesprebuilds/assets; prebuilt assets still ship in the tarball for the scoped-package path).
- When a change introduces an ABI-incompatible modification to the public C++ interface, bump
OPENCC_ABI_VERSIONinCMakeLists.txtso downstream libraries and applications relink instead of silently loading an incompatiblelibopenccshared library. - Treat installed headers under
include/opencc/, exported virtual interfaces, class layout, constructor/destructor signatures, inline public methods, and public symbol signatures as part of the ABI review surface. If in doubt, assume downstream C++ users may have compiled against it. - Keep private implementation helpers out of the installed header set when possible. Moving an installed header or public type to private is itself a compatibility decision and should be reflected in the release notes.
- There is ongoing work to align user-facing behavior across the native CLI, npm CLI, and Python CLI. Treat CLI behavior differences as intentional only when they are documented in
README.mdand covered by tests. - Known area to unify:
-c/--configvalues that omit.json. Current target behavior is the npm CLI rule:- Built-in config stems such as
s2tandt2sshould resolve tos2t.json/t2s.json. - Custom config paths should be preserved as given; do not auto-append
.jsonfor arbitrary filenames.
- Built-in config stems such as
- Before changing config resolution rules in one CLI, check the corresponding implementations in
src/tools/CommandLineMain.cpp,node/cli.js, andpython/opencc/__init__.py, then update tests for all affected surfaces. - When possible, add both direct tests and subprocess/integration-style tests so packaging entry points and standalone CLI invocation are covered, not just in-process helper calls.
- Python module is located in
python/, providing theOpenCCclass through the C API. - Node.js extension is in the
node/directory, using N-API/Node-API to call the core library. The optionalopencc-jiebanpm package lives inplugins/jieba/node/and supplies plugin configs, dictionaries, and platform-specific plugin binaries. - README lists third-party Swift, Java, Go, WebAssembly and other porting projects, showcasing ecosystem breadth.
BUILD_OPENCC_JIEBA_PLUGINenables the C++ jieba plugin in CMake builds. Since 1.4.1 it defaults to ON for top-level macOS builds (so Homebrew ships the plugin); other platforms, subproject builds (FetchContent /add_subdirectory), and Python wheel builds keep it OFF.- The merged jieba dictionary (
jieba_dict/jieba_merged.ocd2) is generated at build time byopencc_dict --from cppjieba_utf8; there is no separate dictionary helper tool. Standalone plugin builds locate an installedopencc_dictand require OpenCC >= 1.4.1. - Source packages:
OPENCC_SOURCE_PACKAGE_PROFILE(full/opencc/opencc-jieba) selects which CPack source archive is produced. Theopenccprofile is the trimmed C++-only package (no Node.js, Python, docs, packaging, orplugins/) and is intentionally buildable with both CMake and Bazel, so Bazel workspace files (BUILD.bazel,MODULE.bazel[.lock],.bazelrc,.bazelversion,.bazelignore) and the top-levelpatches/directory (referenced byMODULE.bazel) are kept; only.bazelrc.useris dropped. When editing the trimmed ignore list, do not re-exclude Bazel files orpatches/.release-source.ymlbuilds this package on aver.*tag (orworkflow_dispatchwithrelease_tag), smoke-tests it with CMake and Bazel, and uploads it to the draft release. plugins/README.mddocuments plugin loading, ABI expectations, and standalone plugin builds.scripts/release-windows-winget.ps1is the Windows portable/WinGet release path and produces the CLI zip, checksum, and WinGet manifests.- npm release packaging is separate from the native CLI release:
openccandopencc-jiebaare packed as npm.tgzartifacts and should be install-tested together when plugin-backed npm configs are changed. - Release flow (since 1.4.1) is draft-first: publish the
@opencc/*scoped binary packages via therelease-npm-binariesworkflow_dispatch, then push aver.*tag. The tag creates a draft GitHub release (release-draft.yml, notes taken from the matching NEWS.md section) and the deb/doc/resource/winget workflows upload assets to the draft; everything up to this point is reversible. Manually publishing the release then triggersrelease-npm(main npm packages) andrelease-pypi— the irreversible publishes.
- Edit or add dictionary entries in
data/dictionary/*.txt. - Use
opencc_dictto convert to.ocd2. - Copy/modify configuration JSON in
data/configand specify new dictionary files. - Add or update test cases in
test/testcases/testcases.jsonfor normal configs, orplugins/jieba/tests/data/jieba_comparison_testcases.json/ golden fixtures for jieba-backed behavior. - Load custom configuration through
SimpleConverter, command-line tools, or language bindings to verify results.
For deeper understanding, read the module documentation in
src/README.md, or refer to test cases intest/to understand conversion chain combinations.
- Missing segmentation and conversion chain order: If
groupconfiguration or dictionary priority is not restored, compound words may be split apart or overwritten by single characters. - Missing longest prefix logic: Character-by-character replacement alone will miss idioms and multi-character word results.
- Improper UTF-8 handling: Overlooking multi-byte characters or surrogate pair handling can easily cause offset or truncation issues.
- Incomplete dictionaries/configuration: Missing segmentation dictionaries, regional differences and other
.ocd2files will result in missing words in output. - Path and loading process differences: If OpenCC's path search and configuration parsing details are not followed, the actual loaded resources will differ from official ones, naturally leading to different results.
Respond in Traditional Chinese (繁體中文) preferred; Simplified Chinese acceptable. When quoting dictionary keys, code identifiers, file names, or any string literal that appears in the codebase in Simplified Chinese, preserve the original Simplified form verbatim — do not transliterate it.
- First line: action verb + concise description, no conventional-commit prefix (
feat:,fix:,perf:, etc.). Example:Implement single-dictionary lookup fast-path for PrefixMatch - Body: one or two sentences summarising motivation and scope, separated from the title by a blank line.
- Multi-area changes: add a
Detailed Changes:section with bold headers and sub-bullets:Detailed Changes: - **Section Name**: - Sub-point one. - Sub-point two. - No
Co-Authored-Bytrailer lines.
- CONTRIBUTING.md - Complete guide on how to contribute dictionary entries to OpenCC, write test cases, and execute testing procedures.
- src/README.md - Detailed technical documentation for core modules.
- README.md - Project overview, installation and usage guide.