main ac9657c77066 cached
128 files
445.3 KB
119.3k tokens
286 symbols
1 requests
Download .txt
Showing preview only (477K chars total). Download the full file or copy to clipboard to get everything.
Repository: windingwind/zotero-pdf-translate
Branch: main
Commit: ac9657c77066
Files: 128
Total size: 445.3 KB

Directory structure:
gitextract_bhxnv728/

├── .gitattributes
├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   ├── dependabot.yml
│   └── workflows/
│       ├── issuebot.yml
│       ├── prbot.yml
│       └── release.yml
├── .gitignore
├── .husky/
│   └── pre-commit
├── .prettierignore
├── .prettierrc.json
├── .vscode/
│   ├── extensions.json
│   ├── launch.json
│   ├── settings.json
│   └── toolkit.code-snippets
├── LICENSE
├── README.md
├── addon/
│   ├── bootstrap.js
│   ├── chrome/
│   │   └── content/
│   │       ├── preferences.xhtml
│   │       ├── standalone.xhtml
│   │       └── styles/
│   │           ├── mathTextbox.css
│   │           ├── panel.css
│   │           └── standalone.css
│   ├── locale/
│   │   ├── en-US/
│   │   │   ├── addon.ftl
│   │   │   ├── mainWindow.ftl
│   │   │   ├── panel.ftl
│   │   │   ├── preferences.ftl
│   │   │   └── standalone.ftl
│   │   ├── it-IT/
│   │   │   ├── addon.ftl
│   │   │   ├── mainWindow.ftl
│   │   │   ├── panel.ftl
│   │   │   ├── preferences.ftl
│   │   │   └── standalone.ftl
│   │   └── zh-CN/
│   │       ├── addon.ftl
│   │       ├── mainWindow.ftl
│   │       ├── panel.ftl
│   │       ├── preferences.ftl
│   │       └── standalone.ftl
│   ├── manifest.json
│   └── prefs.js
├── eslint.config.mjs
├── package.json
├── src/
│   ├── addon.ts
│   ├── api.ts
│   ├── elements/
│   │   ├── base.ts
│   │   ├── mathTextbox.ts
│   │   └── panel.ts
│   ├── extras/
│   │   └── customElements.ts
│   ├── hooks.ts
│   ├── index.ts
│   ├── modules/
│   │   ├── defaultPrefs.ts
│   │   ├── fields.ts
│   │   ├── infoBox.ts
│   │   ├── itemTree.ts
│   │   ├── menu.ts
│   │   ├── notify.ts
│   │   ├── popup.ts
│   │   ├── preferenceWindow.ts
│   │   ├── prompt.ts
│   │   ├── reader.ts
│   │   ├── services/
│   │   │   ├── _template.ts
│   │   │   ├── aliyun.ts
│   │   │   ├── baidu.ts
│   │   │   ├── baidufield.ts
│   │   │   ├── base.ts
│   │   │   ├── bing.ts
│   │   │   ├── bingdict.ts
│   │   │   ├── caiyun.ts
│   │   │   ├── cambridgedict.ts
│   │   │   ├── claude.ts
│   │   │   ├── cnki.ts
│   │   │   ├── collinsdict.ts
│   │   │   ├── deepl.ts
│   │   │   ├── deeplcustom.ts
│   │   │   ├── deeplx.ts
│   │   │   ├── freedictionaryapi.ts
│   │   │   ├── gemini.ts
│   │   │   ├── google.ts
│   │   │   ├── gpt.ts
│   │   │   ├── haici.ts
│   │   │   ├── haicidict.ts
│   │   │   ├── huoshan.ts
│   │   │   ├── huoshanweb.ts
│   │   │   ├── index.ts
│   │   │   ├── libretranslate.ts
│   │   │   ├── microsoft.ts
│   │   │   ├── mtranserver.ts
│   │   │   ├── niutrans.ts
│   │   │   ├── nllb.ts
│   │   │   ├── openl.ts
│   │   │   ├── pot.ts
│   │   │   ├── qwenmt.ts
│   │   │   ├── tencent.ts
│   │   │   ├── tencenttransmart.ts
│   │   │   ├── webliodict.ts
│   │   │   ├── xftrans.ts
│   │   │   ├── youdao.ts
│   │   │   ├── youdaodict.ts
│   │   │   ├── youdaozhiyun.ts
│   │   │   └── youdaozhiyunllm.ts
│   │   ├── settings/
│   │   │   ├── manageKeys.ts
│   │   │   └── renameServices.ts
│   │   ├── shortcuts.ts
│   │   └── tabpanel.ts
│   └── utils/
│       ├── config.ts
│       ├── crypto.ts
│       ├── index.ts
│       ├── llmPrompt.ts
│       ├── locale.ts
│       ├── mathRenderer.ts
│       ├── prefs.ts
│       ├── secret.ts
│       ├── settingsDialog.ts
│       ├── str.ts
│       ├── task.ts
│       ├── wait.ts
│       ├── window.ts
│       └── ztoolkit.ts
├── tsconfig.json
├── typings/
│   ├── global.d.ts
│   ├── i10n.d.ts
│   └── prefs.d.ts
├── update-beta.json
├── update.json
├── update.rdf
└── zotero-plugin.config.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
* text=auto eol=lf

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: [windingwind]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ["https://paypal.me/windingwind"]


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: Bug report
description: File a bug / issue
title: "[Bug] "
labels:
  - bug
  # - Needs Triage
assignees: windingwind
body:
  - type: checkboxes
    id: check-search
    attributes:
      label: Is there an existing issue for this?
      description: Please search to see if an issue already exists for the bug you encountered.
      options:
        - label: I have searched the existing issues
          required: true

  - type: checkboxes
    id: check-frequent
    attributes:
      label: Have you checked the FAQ (https://github.com/windingwind/zotero-pdf-translate/issues/6)?
      description: Please check the FAQ to see if your question has already been answered.
      options:
        - label: I have checked the FAQ
          required: true

  - type: checkboxes
    id: check-version
    attributes:
      label: Are you using the latest Zotero and the latest plugin?
      description: Only bug reports that can be reproduced on the latest Zotero and plugin will be considered.
      options:
        - label: I have confirmed I'm using the latest Zotero and the latest plugin
          required: true

  - type: textarea
    attributes:
      label: Environment
      description: |
        examples:
          - **OS**: Windows 11 22H2
          - **Zotero Version**: 7.0.0
          - **Plugin Version**: 1.0.0
      value: |
        - OS: 
        - Zotero Version: 
        - Plugin Version:
    validations:
      required: true

  - type: textarea
    id: description
    attributes:
      label: Describe the bug
      description: |
        A clear and concise description of what the bug is.
        If applicable, add screenshots and log to help explain your problem.
    validations:
      required: true

  - type: textarea
    id: debug-output
    attributes:
      label: Debug Output
      description: |
        Steps to get debug output:
        1. Disable all other plugins, exit Zotero, and restart Zotero
        2. menu -> `Help` -> `Debug Output` -> `View Output`
        3. Do steps to reproduce the bug
        4. In the debug output window, press `Ctrl/Cmd + S`
        5. Upload the debug output here
    validations:
      required: true

  - type: textarea
    id: additional-context
    attributes:
      label: Anything else?
      description: |
        Links? References? Anything that will give us more context about the issue you are encountering!
        Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
    validations:
      required: false


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: Documentation in Chinese (中文文档)
    url: https://zotero.yuque.com/staff-gkhviy/pdf-trans
    about: 如果你是中文用户,请先阅读中文文档。文档中已经说明的问题不会回复。


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
name: Feature request
description: Suggest an idea for this project
title: "[Feature] "
labels:
  - enhancement
assignees: windingwind
body:
  - type: checkboxes
    id: check-search
    attributes:
      label: Is there an existing issue for this?
      description: Please search to see if an issue already exists for this feature request.
      options:
        - label: I have searched the existing issues
          required: true

  - type: textarea
    attributes:
      label: Environment
      description: |
        examples:
          - **OS**: Windows 11 22H2
          - **Zotero Version**: 7.0.0
          - **Plugin Version**: 1.0.0
      value: |
        - OS: 
        - Zotero Version: 
        - Plugin Version:
    validations:
      required: true

  - type: textarea
    id: description
    attributes:
      label: Describe the feature request
      value: |
        **Is your feature request related to a problem? Please describe.**
        A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

        **Why do you need this feature?**
        A clear and concise description of why you need this feature.
    validations:
      required: false

  - type: textarea
    id: solution
    attributes:
      label: Describe the solution you'd like
      value: |
        **The solution you'd like**
        A clear and concise description of what you want to happen.

        **Alternatives you've considered**
        A clear and concise description of any alternative solutions or features you've considered.
    validations:
      required: false

  - type: textarea
    id: additional-context
    attributes:
      label: Anything else?
      description: |
        Links? References? Anything that will give us more context about the issue you are encountering!
        Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
    validations:
      required: false


================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
  - package-ecosystem: "npm" # See documentation for possible values
    directory: "/" # Location of package manifests
    schedule:
      interval: "weekly"
    groups:
      all-non-major:
        update-types:
          - "minor"
          - "patch"


================================================
FILE: .github/workflows/issuebot.yml
================================================
name: Close inactive issues
on:
  schedule:
    - cron: "30 1 * * *"
  issues:
    types:
      - labeled

jobs:
  close-issues:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
    steps:
      - uses: actions/stale@v9
        with:
          days-before-issue-stale: 30
          days-before-issue-close: 7
          stale-issue-label: "stale"
          stale-issue-message: "This issue is stale because it has been open for 30 days with no activity."
          close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
          exempt-issue-labels: "help wanted"
          days-before-pr-stale: -1
          days-before-pr-close: -1
          repo-token: ${{ secrets.GITHUB_TOKEN }}
  issue-invalid:
    name: close invalid issue
    if: github.event.label.name == 'invalid'
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
    steps:
      - uses: actions-cool/issues-helper@v3
        with:
          actions: close-issue, create-comment
          token: ${{ secrets.GITHUB_TOKEN }}
          body: |
            Hello @${{ github.event.issue.user.login }}. This issue is marked as `invalid` and closed. Please make sure you are reporting an issue and following the issue template.
  issue-duplicate:
    name: close duplicate issue
    if: github.event.label.name == 'duplicate'
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
    steps:
      - uses: actions-cool/issues-helper@v3
        with:
          actions: close-issue, create-comment
          token: ${{ secrets.GITHUB_TOKEN }}
          body: |
            Hello @${{ github.event.issue.user.login }}. This issue is marked as `duplicate` and closed. Please make sure you have searched to see if an issue already exists for the bug you encountered.


================================================
FILE: .github/workflows/prbot.yml
================================================
name: Pull Request

on:
  pull_request_target:
    types: [opened, synchronize, reopened]

permissions:
  contents: write # allow pushing code
  pull-requests: write # allow commenting on PRs

jobs:
  lint:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: true

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: "npm"

      - name: Install dependencies
        run: npm ci

      - name: Run lint
        run: npm run lint

      - name: Commit & push fixes
        id: git_push
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          if ! git diff --quiet; then
            git add .
            git commit -m "chore: apply lint fixes"
            if git push "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" \
                    HEAD:${{ github.head_ref }}; then
              echo "push_succeeded=true" >> $GITHUB_OUTPUT
            else
              echo "push_succeeded=false" >> $GITHUB_OUTPUT
            fi
          else
            echo "push_succeeded=true" >> $GITHUB_OUTPUT
          fi

      - name: Comment on PR if push failed
        if: steps.git_push.outputs.push_succeeded == 'false'
        uses: peter-evans/create-or-update-comment@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          issue-number: ${{ github.event.pull_request.number }}
          body: |
            @${{ github.event.pull_request.user.login }}
            I automatically applied lint fixes but couldn’t push to your branch—could you please run:

            ```bash
            npm run lint
            ```

            and push the results? Thanks!


================================================
FILE: .github/workflows/release.yml
================================================
name: Release

on:
  push:
    tags:
      - v**

permissions:
  contents: write
  issues: write
  pull-requests: write

jobs:
  release:
    runs-on: ubuntu-latest
    env:
      GITHUB_TOKEN: ${{ secrets.GitHub_TOKEN }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install deps
        run: npm install -f

      - name: Build
        run: |
          npm run build

      - name: Release to GitHub
        run: |
          npm run release
          # cp build/update.json update.json
          # cp build/update-beta.json update-beta.json
          # git add update.json
          # git add update-beta.json
          # git commit -m 'chore(publish): synchronizing `update.json`'
          # git push
          sleep 1s

      - name: Notify release
        uses: apexskier/github-release-commenter@v1
        continue-on-error: true
        with:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          comment-template: |
            :rocket: _This ticket has been resolved in {release_tag}. See {release_link} for release notes._


================================================
FILE: .gitignore
================================================
build
logs
node_modules
pnpm-lock.yaml
yarn.lock
tsconfig.tsbuildinfo
zotero-cmd.json
.DS_Store
.env
.scaffold

================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged


================================================
FILE: .prettierignore
================================================
.vscode
build
logs
node_modules
package-lock.json
yarn.lock
pnpm-lock.yaml
# zotero-cmd.json


================================================
FILE: .prettierrc.json
================================================
{
  "printWidth": 80,
  "tabWidth": 2,
  "endOfLine": "lf",
  "overrides": [
    {
      "files": ["*.xhtml"],
      "options": {
        "htmlWhitespaceSensitivity": "css"
      }
    }
  ]
}


================================================
FILE: .vscode/extensions.json
================================================
{
  "recommendations": [
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "macabeus.vscode-fluent"
  ]
}


================================================
FILE: .vscode/launch.json
================================================
{
  // 使用 IntelliSense 了解相关属性。
  // 悬停以查看现有属性的描述。
  // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Restart",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "restart-dev"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Restart in Prod Mode",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "restart-prod"]
    }
  ]
}


================================================
FILE: .vscode/settings.json
================================================
{
  "editor.formatOnType": false,
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "typescript.tsdk": "node_modules/typescript/lib"
}


================================================
FILE: .vscode/toolkit.code-snippets
================================================
{
  "appendElement - full": {
    "scope": "javascript,typescript",
    "prefix": "appendElement",
    "body": [
      "appendElement({",
      "\ttag: '${1:div}',",
      "\tid: '${2:id}',",
      "\tnamespace: '${3:html}',",
      "\tclassList: ['${4:class}'],",
      "\tstyles: {${5:style}: '$6'},",
      "\tproperties: {},",
      "\tattributes: {},",
      "\t[{ '${7:onload}', (e: Event) => $8, ${9:false} }],",
      "\tcheckExistanceParent: ${10:HTMLElement},",
      "\tignoreIfExists: ${11:true},",
      "\tskipIfExists: ${12:true},",
      "\tremoveIfExists: ${13:true},",
      "\tcustomCheck: (doc: Document, options: ElementOptions) => ${14:true},",
      "\tchildren: [$15]",
      "}, ${16:container});",
    ],
  },
  "appendElement - minimum": {
    "scope": "javascript,typescript",
    "prefix": "appendElement",
    "body": "appendElement({ tag: '$1' }, $2);",
  },
  "register Notifier": {
    "scope": "javascript,typescript",
    "prefix": "registerObserver",
    "body": [
      "registerObserver({",
      "\t notify: (",
      "\t\tevent: _ZoteroTypes.Notifier.Event,",
      "\t\ttype: _ZoteroTypes.Notifier.Type,",
      "\t\tids: string[],",
      "\t\textraData: _ZoteroTypes.anyObj",
      "\t) => {",
      "\t\t$0",
      "\t}",
      "});",
    ],
  },
}


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# ![Translate for Zotero](addon/chrome/content/icons/favicon.png)Translate for Zotero

[![zotero target version](https://img.shields.io/badge/Zotero-7/8-green?style=flat-square&logo=zotero&logoColor=CC2936)](https://www.zotero.org)
[![Using Zotero Plugin Template](https://img.shields.io/badge/Using-Zotero%20Plugin%20Template-blue?style=flat-square&logo=github)](https://github.com/windingwind/zotero-plugin-template)

_Translate for Zotero_, a.k.a. _Zotero PDF Translate_, is a [Zotero](https://www.zotero.org/) plugin.  
Translate PDF, EPub, webpage, metadata, annotations, notes to the target language. Support 20+ translate services.

[中文文档](https://zotero.yuque.com/books/share/4443494c-c698-4e08-9d1e-ed253390346d)

![](docs/res/translate.gif)

# Quick Start Guide

## Install

- Download the plugin (.xpi file) from below.
  - [Latest Stable](https://github.com/windingwind/zotero-pdf-translate/releases/latest)
  - [All Releases](https://github.com/windingwind/zotero-pdf-translate/releases)

  _Note_ If you're using Firefox as your browser, right-click the `.xpi` and select "Save As.."

- In Zotero click `Tools` in the top menu bar and then click `Plugins`
- Go to the Extensions page and then click the gear icon in the top right.
- Select `Install Plugin from file`.
- Browse to where you downloaded the `.xpi` file and select it.
- Finish!

## Usage

Open any PDF/EPub/webpage in the Zotero reader.

- Select text, the translations are shown on the pop-up and the item pane(v0.2.0).
  ![](docs/res/en2zh.jpg)

- Highlight/Underline some text, the translations are added to the annotation comment(v0.3.0); Modify & retranslate the annotation text in the item pane and click the `Update Annotation` to modify the annotation text and translation(v0.6.6);
- Add selected text along with translation to note(v0.4.0); _Only works when a note editor is active._
  ![](docs/res/addtonote.jpg)

- Translate item titles with right-click menu or shortcut `Ctrl+T`(v0.6.0).
- Translate item abstract with right-click menu(v0.8.0). Thanks @iShareStuff
- Standalone translation window available(v0.7.0). View & compare translations from multiply services in one window!
  ![](docs/res/standalone.jpg)

- Dictionary for single word translation(v0.7.1).
- SentenceBySentence Translation(v1.1.0). After a translation, press `shift`+`P` and select `Translate Sentences`. _Only for en2zh and en2en now_. Thanks @MuiseDestiny
- Since v2.2.0, the concat mode shortcut is ctrl (on Windows/Linux) or ⌘ (on macOS).

### Q&A

**Q** I want to translate manually.  
**A** Go to `Edit->Settings->Translate->General`, uncheck the `Automatically Translate Selection`. Click the `Translate` button on the pop-up or item pane to translate.

**Q** I want a translate shortcut.  
**A**
Press shortcut `Ctrl+T` after you selected some text. If you are in the collection view, the titles' translation will show/hide.

**Q** I want to concat different selections and translate them together.  
**A** Press `Ctrl/⌘` or select the `Concat Mode` check box on item pane when selecting text in PDF/EPub/webpage.

**Q** Not the language I want.  
**A** The default target language is the same as your Zotero language. Go to `Edit->Settings->Translate->Service` and change the language settings.

**Q** Translation not correct or report an error.  
**A** See _Language Settings_ above and FAQ([#6](https://github.com/windingwind/zotero-pdf-translate/issues/6)). Make sure you use the right secret.

**Q** I want to change the font size.  
**A** Go to `Edit->Settings->Translate->User Interface` and set the font size.

**Q** I want to resize the raw and result text area in the translate panel.  
**A** Drag the separator up and down to adjust the size. Double-click the separator to reset the size.

## Settings

### General

<!-- - Enable Translation, default `true` -->

- Automatically Translate Selection, default `true`
- Automatically Translate Annotation: Save annotation's translation to annotation comment or annotation body, default `false`
  - Automatically Translate Annotation from Sync: Automatically translate annotations synced from other devices if `true`, default `false`
- Enable Reader Selection Pop-up: Show results in the pop-up panel or only in the item pane, default `true`
- Show "Add Translation to Note" in Pop-up: default `true`
  > Invisible if no active note editor opened.
  - Replace Raw: Use translation to replace the raw text when adding to note, default `false`
- Enable Dictionary: Single word will be translated using dictionary service instead of translate service, default `true`
  - Show Play Buttons: Show the word pronunciation play buttons if available, default `true`
  - Auto-play Pronunciation, default `false`

### Service

The default service is Google Translate. Currently, we support:

| Translate Service            | Require Secret                | Supported Languages                                                                                                                                                                        |
| ---------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Google Translate             | No **[Free]**                 | [100+](https://translate.google.com/about/languages/)                                                                                                                                      |
| Google Translate(API)        | No **[Free]**                 | Use `translate.googleapis.com`                                                                                                                                                             |
| CNKI                         | No **[Free]**                 | <https://dict.cnki.net>                                                                                                                                                                    |
| Haici Translate              | No **[Free]**                 | <https://fanyi.dict.cn>                                                                                                                                                                    |
| Youdao Translate             | No **[Free]**                 | [100+?](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html)                                                                                                                     |
| Bing                         | No **[Free]**                 | [en-zh](https://learn.microsoft.com/en-us/azure/ai-services/translator/text-translation/reference/v3/reference)                                                                            |
| DeepLX                       | No **[Free]**                 | Based on [DeepLX](https://github.com/OwO-Network/DeepLX?tab=readme-ov-file)                                                                                                                |
| DeepLX(API)                  | No **[Require config]**       | [DeepLX](https://github.com/OwO-Network/DeepLX?tab=readme-ov-file) related projects                                                                                                        |
| LibreTranslate               | Optional **[Require config]** | [LibreTranslate](https://github.com/LibreTranslate/LibreTranslate)                                                                                                                         |
| MTranServer                  | Optional **[Require config]** | [MTranServer](https://github.com/xxnuo/MTranServer)                                                                                                                                        |
| NLLB                         | No **[Require config]**       | [nllb-api](https://github.com/winstxnhdw/nllb-api?tab=readme-ov-file#self-hosting) or [NLLB Serve](https://github.com/thammegowda/nllb-serve?tab=readme-ov-file#setup)                     |
| Pot                          | No **[Require config]**       | [Pot](https://github.com/pot-app/pot-desktop) _Translate results show in Pot_                                                                                                              |
| Huoshan                      | Yes                           | [50+](https://www.volcengine.com/docs/4640/127681)                                                                                                                                         |
| Volcengine Web               | No **[Free]**                 | [en, zh, and more (auto-detect, web version)](https://translate.volcengine.com/)                                                                                                           |
| Youdao Zhiyun                | Yes                           | [100+](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html)                                                                                                                      |
| Youdao LLM                   | Yes                           | [LLM-based](https://ai.youdao.com/DOCSIRMA/html/trans/api/dmxfy/index.html)(en-zh)                                                                                                         |
| Niu Trans                    | Yes                           | [400+](https://niutrans.com/documents/contents/trans_text#accessMode)                                                                                                                      |
| Microsoft Translate          | Yes(free 2M)                  | [200+](https://docs.microsoft.com/en-us/azure/cognitive-services/translator/language-support)                                                                                              |
| LingoCloud(Caiyun) Translate | Yes                           | [10+](https://docs.caiyunapp.com/lingocloud-api/index.html)                                                                                                                                |
| DeepL Translate              | Yes(free 500k)                | [100+](https://www.deepl.com/pro?cta=header-prices/#developer)                                                                                                                             |
| Aliyun Translate             | Yes(free-1M)                  | [200+](https://help.aliyun.com/document_detail/158269.html)                                                                                                                                |
| Baidu Translate              | Yes(free-QPS1/free-2M)        | [200+](https://fanyi-api.baidu.com/product/11)                                                                                                                                             |
| Baidu Field                  | Yes(free-QPS1/free-2M)        | [en-zh](https://fanyi-api.baidu.com/product/12)                                                                                                                                            |
| OpenL                        | Yes                           | [11](https://docs.openl.club/#/API/format)                                                                                                                                                 |
| Tencent Translate            | Yes(QPS5, free-5M)            | [15](https://cloud.tencent.com/document/product/551/7372)                                                                                                                                  |
| Tencent Transmart            | No **[Free]**                 | [en, zh, and more (auto-detect, web version)](https://transmart.qq.com/)                                                                                                                   |
| Xftrans                      | Yes(free 2M)                  | [Xftrans API](https://www.xfyun.cn/doc/nlp/xftrans/API.html)(70+), [NiuTrans API](https://www.xfyun.cn/doc/nlp/niutrans/API.html)(100+)                                                    |
| GPT                          | Yes(free-$18)                 | [OpenAI](https://openai.com/pricing#chat)(ChatGPT), [AzureGPT](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/reference#chat-completions), compatible GPT-like LLM (Custom GPT) |
| Gemini                       | Yes(free-)                    | [LLM-based](https://ai.google.dev/available_regions#available_languages)                                                                                                                   |
| Qwen-MT                      | Yes(free-)                    | [LLM-based](https://help.aliyun.com/zh/model-studio/user-guide/machine-translation)                                                                                                        |
| Claude                       | Yes                           | [LLM-based](https://docs.anthropic.com/claude/docs/getting-started-with-the-claude-api)                                                                                                    |

> If the service you want is not yet supported, please post an issue.

**Google**  
Google does not require a secret, but you can put your own API URL in the secret to replace the default URL (translate.google.com/translate.googleapi.com).

**Huoshan**  
Apply [here](https://www.volcengine.com/docs/4640/65067).  
The secret format is `accessKeyId#accessKeySecret`

**Youdao Zhiyun Translate 有道智云**  
Apply [here](https://ai.youdao.com/login.s).  
The secret format is `MY_APPID#MY_SECRET#MY_VOCABID(optional)`.

> About `VOCABID`  
> 登录控制台,选择文本翻译服务,点击右侧的术语表,选择新建,填写表名称和语言方向,添加需要的术语表,然后获取对应词表 id 即可。  
> About `Config -> Domain`  
> 登录控制台,点击创建应用,输入应用名称,在*选择服务*一栏勾选**文本翻译**,然后勾选**领域化翻译**即可开通领域化翻译。领域化翻译仅支持中英互译。
>
> [Official Document](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html)

**Youdao LLM Translate 有道智云子曰大模型**  
Apply [here](https://ai.youdao.com/login.s).  
The secret format is `MY_APPID#MY_SECRET`.

> 登录控制台,点击创建应用,输入应用名称,在*选择服务*一栏勾选**大模型翻译**,大模型翻译仅支持中英互译。
>
> [Official Document](https://ai.youdao.com/DOCSIRMA/html/trans/api/dmxfy/index.html)

**NiuTrans**  
Apply [here](https://niutrans.com/NiuTransAuthCenter/login).  
The secret format is `MY_APIKEY#dictNo(optional)#memoryNo(optional)`.

> [Chinese Document](https://doc.tern.1c7.me/zh/folder/setting/#%E5%B0%8F%E7%89%9B)

**Microsoft Translate**  
Apply [here](https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-translator?tabs=csharp). Copy your secret and paste it into the settings.  
The secret format is `serviceKEY#region(required if the region is not global)`.

> See [this issue](https://github.com/windingwind/zotero-pdf-translate/issues/3#issuecomment-1064688597) for detailed steps to set up the Microsoft Translate.

**LingoCloud(Caiyun) Translate**  
Apply [here](https://docs.caiyunapp.com/lingocloud-api/index.html#%E7%94%B3%E8%AF%B7%E8%AE%BF%E9%97%AE%E4%BB%A4%E7%89%8C).

**DeepL Translate**  
Apply [official API](https://www.deepl.com/pro?cta=header-prices/#developer) or [third-party API](https://deepl-pro.com/#/translate).  
The secret format is `secretToken` or `secretToken#glossaryId` (if you want to specify some translate glossary).

**Aliyun Translate**  
Apply [here](https://www.aliyun.com/product/ai/base_alimt).  
The secret format is `accessKeyId#accessKeySecret#endpoint(optional)`.

> The endpoint is the region of the service, default `https://mt.aliyuncs.com`. For `cn-hangzhou`, the endpoint is `mt.cn-hangzhou.aliyuncs.com`. See also [here](https://help.aliyun.com/zh/machine-translation/developer-reference/api-alimt-2018-10-12-endpoint?spm=a2c4g.11186623.help-menu-30396.d_4_1_0.6c702fa7WlNkX1).

> [Chinese Document](https://help.aliyun.com/document_detail/158269.html)

**Baidu Translate**  
Apply [here](https://fanyi-api.baidu.com/product/11).  
The secret format is `MY_APPID#MY_KEY#ACTION(optional, see https://api.fanyi.baidu.com/doc/21, default 0)`(split with '#').

**Baidu Field Translate 百度垂直领域翻译**  
Apply [here](https://fanyi-api.baidu.com/product/12).  
The secret format is `MY_APPID#MY_KEY#DOMAIN_CODE`(split with '#').

| Domain Code | 领域         | 支持语言方向                          |
| ----------- | ------------ | ------------------------------------- |
| it          | 信息技术领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| finance     | 金融财经领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| machinery   | 机械制造领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| senimed     | 生物医药领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| novel       | 网络文学领域 | 中文(简)-> 英语                     |
| academic    | 学术论文领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| aerospace   | 航空航天领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| wiki        | 人文社科领域 | 中文(简)-> 英语                     |
| news        | 新闻资讯领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| law         | 法律法规领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| contract    | 合同领域     | 中文(简)-> 英语、英语 -> 中文(简) |

> [Chinese Document](https://doc.tern.1c7.me/zh/folder/setting/#%E8%85%BE%E8%AE%AF%E4%BA%91)

**OpenL Translate**  
Apply [here](https://my.openl.club/).  
The secret format is `service1,service2,...#apikey`(split with '#'; split service codes with ',').

Supported service codes are: `deepl,youdao,tencent,aliyun,baidu,caiyun,wechat,sogou,azure,ibm,aws,google`, See [Service Code](https://docs.openl.club/#/API/format?id=%e7%bf%bb%e8%af%91%e6%9c%8d%e5%8a%a1%e4%bb%a3%e7%a0%81%e5%90%8d)

> [Chinese Document](https://docs.openl.club/#/)

**Tencent Translate**  
Apply [here](https://cloud.tencent.com/product/tmt).  
The secret format is `secretId#SecretKey#Region(optional, default ap-shanghai)#ProjectId(optional, default 0)`(split with '#').

> [Chinese Document](https://doc.tern.1c7.me/zh/folder/setting/#%E8%85%BE%E8%AE%AF%E4%BA%91)

**Xftrans 讯飞翻译**  
Apply [here](https://www.xfyun.cn/doc/authentication/personal.html#%E6%93%8D%E4%BD%9C%E6%AD%A5%E9%AA%A4).

**GPT**  
Apply [OpenAI ChatGPT API](https://auth.openai.com/create-account) or [Azure OpenAI REST API](https://azure.microsoft.com/free/cognitive-services).  
The secret format is `sk-*` for ChatGPT, and `MY_APIKEY` for AzureGPT and Custom GPT.

Support third-party or self-deployed compatible APIs.

> [Chinese Document](https://gist.github.com/GrayXu/f1b72353b4b0493d51d47f0f7498b67b)

**Gemini**  
Apply [here](https://ai.google.dev/gemini-api/docs).  
The secret format is `MY_APIKEY`.

**Qwen-MT**  
Apply [here](https://help.aliyun.com/zh/model-studio/user-guide/machine-translation).  
The secret format is `MY_APIKEY`.

**Claude**  
Apply [here](https://docs.anthropic.com/claude/docs/getting-started-with-the-claude-api).

**LibreTranslate**  
See [LibreTranslate](https://github.com/LibreTranslate/LibreTranslate). API Key is optional.

**MTranServer**  
See [MTranServer](https://github.com/xxnuo/MTranServer). Token is optional.

> MTranServer only supports `zh`-`en` language pairs for v2.1.1 and previous versions. For MTranServer v3.0.0+, please check the checkbox in the Config panel to use `zh-Hans` or `zh-Hant` language. See [explanation of the supported languages](https://github.com/xxnuo/MTranServer/issues/59#issuecomment-3131551779).

**NLLB**  
See [nllb-api](https://github.com/winstxnhdw/nllb-api?tab=readme-ov-file#self-hosting) or [NLLB Serve](https://github.com/thammegowda/nllb-serve?tab=readme-ov-file#setup).

**Pot**  
See [Pot](https://github.com/pot-app/pot-desktop?tab=readme-ov-file#%E5%A4%96%E9%83%A8%E8%B0%83%E7%94%A8). _Translate results show in Pot._

### User Interface

- `Font Size`: The font size of result text, default `12`
- `Line Height`: The line height of result text, default `1.5`
- `Item Context Menu: Show xxx`: Show or hide Title/Abstract tanslation, default `true`
- `Item Pane Section: Show xxx`: Show or hide elements in the item pane, default `true`
- `Item Pane Section: Hold down Ctrl/⌘`: Press key to enable concat mode when selecting text in PDF/EPub/webpage if `true`, default `true`
- `Item Pane Section: Reverse Raw/Result`: Reverse the order of Raw/Result in the item pane if `true`, default `false`
- `Item Pane Info: Show xxx`: Show or hide Title/Abstract tanslation in the item info rows
- `Standalone: Keep Windows on Top`: Top the standalone translate panel if `true`, default `false`
- `Pop-up: Remember Size`: Remember size of pop-up if `true`, else automatically adjust the size, default `false`

### Advanced

- Strip empty lines and thinking from translation results: Automatically remove empty lines or thinking labels from translation results, especially for some LLM translation services.
- Automatically Detect Item Language
  - Disable Automatic Translation when File Language is(comma-separated): If you want to disable automatic translation in `zh` and `ja` files, set `zh,ja`. Default `zh,zh-CN,中文`.
- Delimiter (between text and translation): When translating annotations, the result will be wrapped inside this character to allow safe re-translate. If set to empty, re-translating annotations will replace the annotation comment/body with the new translate result.
- Regex for removing extra text from translation results (leave empty to disable): Automatically remove text from translation results using regex. You need to understand how to use regex in advance.
- Reset field of selected items in library: Batch reset the _Title Translation_ or _Abstract Translation_ of selected items. Please select the items in Library or Collection panel and then click the button.

## Development & Contributing

This plugin is built based on the [Zotero Plugin Template](https://github.com/windingwind/zotero-plugin-template). See the setup and debug details there.

To startup, run

```bash
git clone https://github.com/windingwind/zotero-pdf-translate.git
cd zotero-pdf-translate
npm install
npm run build
```

The plugin is built to `./build/*.xpi`.

### Contributing

**Add new translate service**

1. Copy `src/modules/services/_template.ts` > `src/services/<your-service-id>.ts`;
2. Fill in the required fields (id, type, and translate) and optional fields (name, helpUrl, defaultSecret, secretValidator(secret), and config(settings)) following the introduction. The translation function sets the translation result to `data.result` if runs successfully and throws an error if fails;
3. Import the new service object in `src/modules/services/index.ts`.
4. Add locale string `service.${serviceId}` and `service-<your-service-id>-dialog-xxx`(if necessary) in `addon/locale/${lang}/addon.ftl`.
5. Build and test.

## Disclaimer

Use this code under AGPL. No warranties are provided. Keep the laws of your locality in mind!

## My Zotero Plugins

- [Better Notes for Zotero](https://github.com/windingwind/zotero-better-notes): Everything about note management. All in Zotero.
- [Actions & Tags for Zotero](https://github.com/windingwind/zotero-tag): Customize your Zotero workflow.
- [Bionic for Zotero](https://github.com/windingwind/bionic-for-zotero): Bionic reading experience with Zotero.

## Sponsors

Thanks
[peachgirl100](https://github.com/peachgirl100),
[youngfish42](https://github.com/youngfish42),
and other anonymous sponsors!

If you want to leave your name here, please email me or leave a message with the donation.

## Contributors

<a href="https://github.com/windingwind/zotero-pdf-translate/graphs/contributors">
  <img src="https://contrib.rocks/image?repo=windingwind/zotero-pdf-translate" />
</a>


================================================
FILE: addon/bootstrap.js
================================================
/**
 * Most of this code is from Zotero team's official Make It Red example[1]
 * or the Zotero 7 documentation[2].
 * [1] https://github.com/zotero/make-it-red
 * [2] https://www.zotero.org/support/dev/zotero_7_for_developers
 */

var chromeHandle;

function install(data, reason) {}

async function startup({ id, version, resourceURI, rootURI }, reason) {
  await Zotero.initializationPromise;

  // String 'rootURI' introduced in Zotero 7
  if (!rootURI) {
    rootURI = resourceURI.spec;
  }

  var aomStartup = Components.classes[
    "@mozilla.org/addons/addon-manager-startup;1"
  ].getService(Components.interfaces.amIAddonManagerStartup);
  var manifestURI = Services.io.newURI(rootURI + "manifest.json");
  chromeHandle = aomStartup.registerChrome(manifestURI, [
    ["content", "__addonRef__", rootURI + "chrome/content/"],
  ]);

  /**
   * Global variables for plugin code.
   * The `_globalThis` is the global root variable of the plugin sandbox environment
   * and all child variables assigned to it is globally accessible.
   * See `src/index.ts` for details.
   */
  const ctx = {
    rootURI,
  };
  ctx._globalThis = ctx;

  Services.scriptloader.loadSubScript(
    `${rootURI}/chrome/content/scripts/__addonRef__.js`,
    ctx,
  );
}

async function onMainWindowLoad({ window }, reason) {
  Zotero.__addonInstance__?.hooks.onMainWindowLoad(window);
}

async function onMainWindowUnload({ window }, reason) {
  Zotero.__addonInstance__?.hooks.onMainWindowUnload(window);
}

function shutdown({ id, version, resourceURI, rootURI }, reason) {
  if (reason === APP_SHUTDOWN) {
    return;
  }

  Zotero.__addonInstance__?.hooks.onShutdown();

  Cc["@mozilla.org/intl/stringbundle;1"]
    .getService(Components.interfaces.nsIStringBundleService)
    .flushBundles();

  if (chromeHandle) {
    chromeHandle.destruct();
    chromeHandle = null;
  }
}

function uninstall(data, reason) {}


================================================
FILE: addon/chrome/content/preferences.xhtml
================================================
<linkset>
  <html:link rel="localization" href="__addonRef__-preferences.ftl" />
</linkset>
<vbox
  id="zotero-prefpane-__addonRef__"
  onload="Zotero.__addonInstance__.hooks.onPrefsLoad(event)"
>
  <groupbox>
    <label><html:h2 data-l10n-id="pref-general"></html:h2></label>
    <checkbox
      id="__addonRef__-enableAuto"
      data-l10n-id="pref-basic-enableAuto"
      native="true"
      preference="__prefsPrefix__.enableAuto"
    />
    <vbox>
      <checkbox
        id="__addonRef__-enableComment"
        data-l10n-id="pref-basic-enableComment"
        native="true"
        preference="__prefsPrefix__.enableComment"
      />
      <radiogroup
        id="__addonRef__-annotationTranslationPosition"
        class="auto-annotation"
        style="padding-left: 18px"
        orient="horizontal"
        native="true"
        preference="__prefsPrefix__.annotationTranslationPosition"
      >
        <radio
          data-l10n-id="pref-basic-annotationTranslationInComment"
          value="comment"
        />
        <radio
          data-l10n-id="pref-basic-annotationTranslationInBody"
          value="body"
        />
      </radiogroup>
      <checkbox
        id="__addonRef__-enableAnnotationFromSyncTranslation"
        data-l10n-id="pref-basic-enableAnnotationFromSyncTranslation"
        style="padding-left: 18px"
        native="true"
        preference="__prefsPrefix__.enableAnnotationFromSyncTranslation"
      />
    </vbox>
    <vbox>
      <checkbox
        id="__addonRef__-enableAutoTagAnnotation"
        data-l10n-id="pref-basic-enableAutoTagAnnotation"
        style="padding-left: 18px"
        native="true"
        preference="__prefsPrefix__.enableAutoTagAnnotation"
      />
      <hbox align="center" style="padding-left: 36px">
        <label data-l10n-id="pref-basic-annotationTagContent"></label>
        <html:input
          id="__addonRef__-annotationTagContent"
          type="text"
          class="enable-auto-tag-annotation"
          preference="__prefsPrefix__.annotationTagContent"
        ></html:input>
      </hbox>
    </vbox>
    <vbox>
      <checkbox
        id="__addonRef__-enablePopup"
        data-l10n-id="pref-basic-enablePopup"
        native="true"
        preference="__prefsPrefix__.enablePopup"
      />
      <checkbox
        id="__addonRef__-enableHidePopupTextarea"
        data-l10n-id="pref-basic-enableHidePopupTextarea"
        class="enable-popup"
        style="padding-left: 18px"
        native="true"
        preference="__prefsPrefix__.enableHidePopupTextarea"
      />
      <checkbox
        id="__addonRef__-enableAddToNote"
        data-l10n-id="pref-basic-enableNote"
        class="enable-popup"
        style="padding-left: 18px"
        native="true"
        preference="__prefsPrefix__.enableNote"
      />
      <checkbox
        id="__addonRef__-enableNoteReplaceMode"
        data-l10n-id="pref-basic-enableNoteReplaceMode"
        class="enable-popup enable-popup-addtonote"
        style="padding-left: 18px"
        native="true"
        preference="__prefsPrefix__.enableNoteReplaceMode"
      />
    </vbox>
    <vbox>
      <checkbox
        id="__addonRef__-showPlayBtn"
        class="use-word-service"
        data-l10n-id="pref-audio-showPlayBtn"
        native="true"
        preference="__prefsPrefix__.showPlayBtn"
      />
      <checkbox
        data-l10n-id="pref-audio-autoPlay"
        class="use-word-service show-play-btn"
        style="padding-left: 18px"
        native="true"
        preference="__prefsPrefix__.autoPlay"
      />
    </vbox>
  </groupbox>
  <groupbox>
    <label><html:h2 data-l10n-id="pref-service"></html:h2></label>
    <hbox align="center">
      <label data-l10n-id="pref-service-sentenceServices"></label>
      <!-- Replace -->
      <box id="__addonRef__-sentenceServices-placeholder"></box>
      <label data-l10n-id="pref-service-sentenceServicesSecret"></label>
      <html:input
        type="text"
        id="__addonRef__-sentenceServicesSecret"
      ></html:input>
      <button id="__addonRef__-sentenceServicesStatus"></button>
    </hbox>
    <label
      data-l10n-id="pref-service-hint"
      style="padding-left: 18px; margin-top: 8px; margin-bottom: 8px"
    ></label>
    <hbox align="center">
      <label data-l10n-id="pref-service-langfrom"></label>
      <!-- Replace -->
      <box id="__addonRef__-langfrom-placeholder"></box>
      <label data-l10n-id="pref-service-langto"></label>
      <!-- Replace -->
      <box id="__addonRef__-langto-placeholder"></box>
    </hbox>
    <checkbox
      id="__addonRef__-attachPaperContext"
      data-l10n-id="pref-service-attachPaperContext"
      native="true"
      preference="__prefsPrefix__.attachPaperContext"
    />
    <checkbox
      id="__addonRef__-useWordService"
      data-l10n-id="pref-service-useWordService"
      native="true"
      preference="__prefsPrefix__.enableDict"
    />
    <hbox align="center">
      <label data-l10n-id="pref-service-wordServices"></label>
      <!-- Replace -->
      <box id="__addonRef__-wordServices-placeholder"></box>
      <label data-l10n-id="pref-service-wordServicesSecret"></label>
      <html:input
        type="text"
        id="__addonRef__-wordServicesSecret"
        class="use-word-service"
      ></html:input>
    </hbox>
  </groupbox>
  <groupbox>
    <label><html:h2 data-l10n-id="pref-interface"></html:h2></label>
    <hbox align="center">
      <label data-l10n-id="pref-interface-fontSize"></label>
      <html:input
        id="__addonRef__-fontSize"
        type="text"
        preference="__prefsPrefix__.fontSize"
      ></html:input>
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-interface-lineHeight"></label>
      <html:input
        id="__addonRef__-lineHeight"
        type="text"
        preference="__prefsPrefix__.lineHeight"
      ></html:input>
    </hbox>
    <checkbox
      data-l10n-id="pref-interface-showItemMenuTitleTranslation"
      native="true"
      preference="__prefsPrefix__.showItemMenuTitleTranslation"
    />
    <checkbox
      data-l10n-id="pref-interface-showItemMenuAbstractTranslation"
      native="true"
      preference="__prefsPrefix__.showItemMenuAbstractTranslation"
    />
    <checkbox
      data-l10n-id="pref-interface-showSidebarEngine"
      native="true"
      preference="__prefsPrefix__.showSidebarEngine"
    />
    <checkbox
      id="__addonRef__-hideUnconfiguredServices"
      data-l10n-id="pref-interface-hideUnconfiguredServices"
      native="true"
      preference="__prefsPrefix__.hideUnconfiguredServices"
    />
    <checkbox
      data-l10n-id="pref-interface-showSidebarLanguage"
      native="true"
      preference="__prefsPrefix__.showSidebarLanguage"
    />
    <checkbox
      data-l10n-id="pref-interface-showSidebarRaw"
      native="true"
      preference="__prefsPrefix__.showSidebarRaw"
    />
    <checkbox
      id="__addonRef__-enableMathRendering"
      data-l10n-id="pref-interface-enableMathRendering"
      native="true"
      preference="__prefsPrefix__.enableMathRendering"
    />
    <checkbox
      data-l10n-id="pref-interface-rawResultOrder"
      native="true"
      preference="__prefsPrefix__.rawResultOrder"
    />
    <checkbox
      data-l10n-id="pref-interface-showSidebarSettings"
      native="true"
      preference="__prefsPrefix__.showSidebarSettings"
    />
    <checkbox
      data-l10n-id="pref-interface-showSidebarConcat"
      native="true"
      preference="__prefsPrefix__.showSidebarConcat"
    />
    <checkbox
      data-l10n-id="pref-interface-enableConcatKey"
      native="true"
      preference="__prefsPrefix__.enableConcatKey"
    />
    <checkbox
      data-l10n-id="pref-interface-showSidebarCopy"
      native="true"
      preference="__prefsPrefix__.showSidebarCopy"
    />
    <checkbox
      data-l10n-id="pref-interface-showItemBoxTitleTranslation"
      native="true"
      preference="__prefsPrefix__.showItemBoxTitleTranslation"
    />
    <checkbox
      data-l10n-id="pref-interface-showItemBoxAbstractTranslation"
      native="true"
      preference="__prefsPrefix__.showItemBoxAbstractTranslation"
    />
    <checkbox
      data-l10n-id="pref-interface-keepWindowTop"
      native="true"
      preference="__prefsPrefix__.keepWindowTop"
    />
    <checkbox
      data-l10n-id="pref-interface-keepPopupSize"
      native="true"
      preference="__prefsPrefix__.keepPopupSize"
    />
  </groupbox>
  <groupbox>
    <label><html:h2 data-l10n-id="pref-advanced"></html:h2></label>
    <hbox align="center">
      <checkbox
        data-l10n-id="pref-advanced-stripEmptyLines"
        native="true"
        preference="__prefsPrefix__.stripEmptyLines"
      />
    </hbox>
    <hbox align="center">
      <checkbox
        data-l10n-id="pref-advanced-enableAutoDetectLanguage"
        native="true"
        preference="__prefsPrefix__.enableAutoDetectLanguage"
      />
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-advanced-disabledLanguages"></label>
      <html:input
        type="text"
        preference="__prefsPrefix__.disabledLanguages"
        style="min-width: 80px"
      ></html:input>
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-advanced-extraEngines"></label>
      <html:input
        type="text"
        preference="__prefsPrefix__.extraEngines"
      ></html:input>
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-advanced-splitChar"></label>
      <html:input
        type="text"
        preference="__prefsPrefix__.splitChar"
      ></html:input>
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-advanced-resultRegex"></label>
      <html:input
        type="text"
        preference="__prefsPrefix__.resultRegex"
        style="min-width: 80px"
      ></html:input>
    </hbox>
    <hbox align="center" style="gap: 8px">
      <label data-l10n-id="pref-advanced-reset"></label>
      <button
        id="__addonRef__-reset-titleTranslation"
        data-l10n-id="pref-advanced-reset-titleTranslation"
      ></button>
      <button
        id="__addonRef__-reset-abstractTranslation"
        data-l10n-id="pref-advanced-reset-abstractTranslation"
      ></button>
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-service-manageKeys-hint"></label>
      <button
        id="__addonRef__-manageKeys"
        data-l10n-id="pref-service-manageKeys"
      ></button>
    </hbox>
    <hbox align="center">
      <label data-l10n-id="pref-service-renameServices-hint"></label>
      <button
        id="__addonRef__-renameServices"
        data-l10n-id="pref-service-renameServices"
      ></button>
    </hbox>
  </groupbox>
  <groupbox>
    <label><html:h2 data-l10n-id="pref-about"></html:h2></label>
    <label
      data-l10n-id="pref-about-version"
      data-l10n-args='{"time": "__buildTime__","name": "__addonName__","version":"__buildVersion__"}'
    ></label>
    <hbox align="center">
      <label
        data-l10n-id="pref-about-feedback"
        is="zotero-text-link"
        class="zotero-text-link"
        href="https://github.com/windingwind/zotero-pdf-translate/issues"
        style="margin-right: 4px"
      ></label>
      <label
        data-l10n-id="pref-about-docs"
        is="zotero-text-link"
        class="zotero-text-link"
        href="https://zotero.yuque.com/staff-gkhviy/pdf-trans"
      ></label>
    </hbox>
  </groupbox>
</vbox>


================================================
FILE: addon/chrome/content/standalone.xhtml
================================================
<?xml version="1.0"?>
<!-- prettier-ignore -->
<!DOCTYPE window>
<!-- prettier-ignore -->
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<!-- prettier-ignore -->
<?xml-stylesheet href="chrome://zotero/skin/zotero.css" type="text/css"?>
<!-- prettier-ignore -->
<?xml-stylesheet href="chrome://zotero-platform/content/zotero.css" type="text/css"?>
<!-- prettier-ignore -->
<?xml-stylesheet href="chrome://__addonRef__/content/styles/standalone.css" type="text/css"?>

<window
  id="__addonRef__-standalone"
  title="Translate Panel"
  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  xmlns:html="http://www.w3.org/1999/xhtml"
  windowtype="__addonRef__-standalone"
  persist="screenX screenY width height"
  onload="window.arguments[0].loadLock.resolve()"
>
  <xul:linkset>
    <html:link rel="localization" href="browser/menubar.ftl" />
    <html:link rel="localization" href="browser/browserSets.ftl" />
    <html:link rel="localization" href="toolkit/global/textActions.ftl" />
    <html:link rel="localization" href="zotero.ftl" />
    <html:link rel="localization" href="__addonRef__-standalone.ftl" />
  </xul:linkset>

  <xul:commandset id="mainCommandSet">
    <xul:command id="cmd_close" oncommand="window.close();" />
  </xul:commandset>
  <xul:keyset id="mainKeyset">
    <xul:key
      id="key_close"
      data-l10n-id="close-shortcut"
      command="cmd_close"
      modifiers="accel"
      reserved="true"
    />
  </xul:keyset>

  <script src="chrome://zotero/content/include.js"></script>
  <script src="chrome://zotero/content/customElements.js"></script>
  <script src="chrome://__addonRef__/content/scripts/customElements.js"></script>
  <translator-plugin-panel id="__addonRef__-panel" />
  <hbox id="extra-buttons" align="center">
    <button id="add-source" data-l10n-id="add-source" />
    <button id="pin-window" data-l10n-id="pin-window" />
  </hbox>
  <html:div class="separator"></html:div>
  <vbox id="extra-container"></vbox>
</window>


================================================
FILE: addon/chrome/content/styles/mathTextbox.css
================================================
math-textbox[hidden] {
  display: none;
}


================================================
FILE: addon/chrome/content/styles/panel.css
================================================
translator-plugin-panel {
  display: flex;
  flex-direction: column;
  gap: 6px;
  height: var(--details-height, 450px);
}

translator-plugin-panel linkset {
  display: none;
}

translator-plugin-panel .separator {
  border-top: var(--material-border);
}

translator-plugin-panel .icon-button {
  width: 24px;
  height: 24px;
  fill: var(--fill-secondary);
  stroke: var(--fill-secondary);
  -moz-context-properties: fill, fill-opacity, stroke, stroke-opacity;
  list-style-image: url(chrome://__addonRef__/content/icons/swap.svg);
}

translator-plugin-panel #__addonRef__-translate {
  flex: 1;
  min-width: auto;
}

translator-plugin-panel .lang-menulist {
  flex: 1;
}

translator-plugin-panel editable-text {
  flex: 1;
  min-height: 100px;
}

/* Minimal styles for math-textbox to match editable-text without intruding */
translator-plugin-panel math-textbox {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100px;
  flex: 1;
  position: relative;
}

translator-plugin-panel math-textbox editable-text {
  flex: 1;
  min-height: 100px;
}

translator-plugin-panel math-textbox[overlay-visible] editable-text {
  visibility: hidden;
}

translator-plugin-panel math-textbox .math-overlay {
  position: absolute;
  inset: 0;
  overflow: auto;
  display: block; /* ensure layout box for HTML namespace */
}

translator-plugin-panel .editor-container {
  display: flex;
  flex: 1;
  min-height: 213px;
  flex-direction: column;
  position: relative;
}

translator-plugin-panel .draggable-container {
  height: 13px;
  cursor: ns-resize;
  display: flex;
  flex-direction: column;
  position: relative;
  justify-content: center;
}

translator-plugin-panel .draggable-container[hidden] {
  display: none;
}

translator-plugin-panel .options-container {
  display: grid;
  grid-template-columns: max-content 1fr;
  column-gap: 8px;
  row-gap: 2px;
  width: inherit;
}

translator-plugin-panel .options-grid:not([hidden]) {
  display: grid;
  grid-template-columns: subgrid;
  grid-column: span 2;
}

translator-plugin-panel .options-label {
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: var(--fill-secondary);
}

translator-plugin-panel .options-content {
  display: flex;
  flex-direction: row;
  gap: 4px;
}

translator-plugin-panel #__addonRef__-copy-container button {
  min-width: auto;
  flex: 1;
}


================================================
FILE: addon/chrome/content/styles/standalone.css
================================================
window {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 20px;
}

linkset {
  display: none;
}

.separator {
  border-top: var(--material-border);
}

translator-plugin-panel {
  width: 100%;
  flex-grow: 1;
}

#extra-buttons button {
  flex: 1;
}

#extra-container {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  gap: 8px;
}

#extra-container:empty {
  display: none;
}

#extra-container editable-text {
  min-height: 60px;
  height: 100px;
  flex-shrink: 1;
  flex-grow: 1;
}


================================================
FILE: addon/locale/en-US/addon.ftl
================================================
service-huoshanweb=Volcengine Web
service-tencenttransmart=Tencent Transmart
service-huoshan=Huoshan
service-googleapi=Google(API)
service-google=Google
service-cnki=CNKI
service-youdao=Youdao
service-youdaozhiyun=Youdao Zhiyun
service-youdaozhiyunllm=Youdao LLM
service-niutranspro=Niu Trans
service-microsoft=Microsoft
service-caiyun=Caiyun
service-libretranslate=LibreTranslate
service-mtranserver=MTranServer
service-deeplfree=DeepL(Free Plan)
service-deeplpro=DeepL(Pro Plan)
service-deeplcustom=DeepLX(API)
service-deeplx=DeepLX
service-baidu=Baidu
service-baidufield=Baidu Field
service-openl=OpenL
service-tencent=Tencent
service-aliyun=Aliyun
service-xftrans=Xftrans
service-chatgpt=ChatGPT
service-customgpt1=Custom GPT 1
service-customgpt2=Custom GPT 2
service-customgpt3=Custom GPT 3
service-azuregpt=AzureGPT
service-gemini=Gemini
service-qwenmt=Qwen-MT
service-claude=Claude
service-haici=Haici
service-bing=Bing
service-pot=Pot
service-nllb=NLLB
service-bingdict=Bing Dict(en→zh)🔊
service-cambridgedict=Cambridge Dict(en→other)🔊
service-haicidict=Haici Dict(en→zh)🔊
service-collinsdict=Collins Dict(en→zh)🔊
service-youdaodict=Youdao Dict(en→zh)🔊
service-freedictionaryapi=FreeDictionaryAPI(en→en)
service-webliodict=Weblio Dict(en→ja)
service-errorPrefix=[Request Error]
    Service not available, invalid secret, or request too fast.
    Use another translation service or post the issue here: 
    https://github.com/windingwind/zotero-pdf-translate/issues
    
    The message below is not Zotero or the Translate plugin, but from

service-dialog-config=Config
service-dialog-title={ $service } Config
service-dialog-save=Save
service-dialog-close=Close
service-dialog-help=Help
service-dialog-custom-request-description=Refer to API documentation of service provider, add custom parameters. These will be merged with the standard parameters (model, messages, temperature, stream).
service-dialog-custom-request-title=Custom Request Parameters
service-dialog-custom-request-add-param=Add Parameter

service-niutranspro-dialog-endpoint=Endpoint
service-niutranspro-dialog-username=Username
service-niutranspro-dialog-password=Password
service-niutranspro-dialog-signup=Sign up
service-niutranspro-dialog-forget=Forget
service-niutranspro-dialog-dictLib=Dict Lib
service-niutranspro-dialog-memoryLib=Memory Lib
service-niutranspro-dialog-tip0=Please go to the
service-niutranspro-dialog-tip1=Niutrans Cloud Platform
service-niutranspro-dialog-tip2=to add the term dictionary library
service-niutranspro-dialog-signin=Sign In
service-niutranspro-dialog-refresh=Refresh
service-niutranspro-dialog-signout=Sign Out

service-deeplcustom-dialog-endPoint=EndPoint
service-deeplx-dialog-endPoint=EndPoint

service-chatgpt-dialog-endPoint=API
service-chatgpt-dialog-model=Model
service-chatgpt-dialog-temperature=Temp
service-chatgpt-dialog-prompt=Prompt
service-chatgpt-dialog-stream=Stream
service-chatgpt-dialog-custom-request=Custom Request

service-azuregpt-dialog-endPoint=EndPoint
service-azuregpt-dialog-model=Name
service-azuregpt-dialog-temperature=Temp
service-azuregpt-dialog-apiVersion=Version
service-azuregpt-dialog-prompt=Prompt
service-azuregpt-dialog-stream=Stream
service-azuregpt-dialog-custom-request=Custom Request

service-xftrans-dialog-engine=API Engine

service-gemini-dialog-endPoint=EndPoint
service-gemini-dialog-prompt=Prompt
service-gemini-dialog-stream=Stream

service-qwenmt-dialog-endPoint=EndPoint
service-qwenmt-dialog-model=Model
service-qwenmt-dialog-domains=Domains

service-claude-dialog-endPoint=EndPoint
service-claude-dialog-model=Model
service-claude-dialog-temperature=Temp
service-claude-dialog-prompt=Prompt
service-claude-dialog-stream=Stream
service-claude-dialog-maxTokens=Max Tokens

service-cnki-settings=Settings
service-cnki-dialog-regex=CNKI Addvertisements Regex
service-cnki-dialog-split=Automatically split translation for more than 800 characters

service-aliyun-dialog-action=Action
service-aliyun-dialog-scene=Scene

service-tencent-dialog-secretid=Secret ID
service-tencent-dialog-secretkey=Secret Key
service-tencent-dialog-region=Region
service-tencent-dialog-projectid=Project ID
service-tencent-dialog-termrepoid=Term Repo IDs (optional)
service-tencent-dialog-sentrepoid=Sent Repo IDs (optional)

service-youdaozhiyun-dialog-domain=Domain
service-youdaozhiyunllm-dialog-model=Model
service-youdaozhiyunllm-dialog-pro=Youdao LLM Pro-14B
service-youdaozhiyunllm-dialog-lite=Youdao LLM Lite-1.5B
service-youdaozhiyunllm-dialog-prompt=Prompt
service-youdaozhiyunllm-dialog-stream=Stream

readerpopup-translate-label=Translate
readerpopup-addToNote-label=Add Translation to Note

pref-title=Translate

field-titleTranslation=Title Translation
field-abstractTranslation=Abstract Translation

status-translating=Translating...
sideBarIcon-title=Translate annotation

service-manageKeys-title=Manage Translation Service Keys
service-manageKeys-head=Manage all translation service keys. Edit the JSON directly and click Save.
service-manageKeys-save=Save
service-manageKeys-close=Close

service-renameServices-title=Rename Custom GPT Services
service-renameServices-head=Input the new name and click Save.
service-renameServices-hint=Changes take effect after restarting the plugin or Zotero
service-renameServices-save=Save
service-renameServices-close=Close

service-libretranslate-dialog-endPoint=API Endpoint

service-mtranserver-dialog-endPoint=EndPoint
service-mtranserver-dialog-versionlabel=Use MTranServer v3.0.0+

service-pot-dialog-port=Port

service-nllb-dialog-model=nllb Model
service-nllb-dialog-apiendpoint=nllb-api EndPoint
service-nllb-dialog-apistream=nllb-api Stream
service-nllb-dialog-serveendpoint=nllb-serve EndPoint
service-nllb-dialog-apilabel=nllb-api Docs
service-nllb-dialog-servelabel=nllb-serve Docs



================================================
FILE: addon/locale/en-US/mainWindow.ftl
================================================
itemPaneSection-header =
    .label = Translate
itemPaneSection-sidenav =
    .tooltiptext = Translate
itemPaneSection-fullHeight =
    .tooltiptext = Full height
itemPaneSection-openStandalone =
    .tooltiptext = Open in standalone window

field-titleTranslation = Title Translation
field-abstractTranslation = Abstract Translation

itemmenu-translateTitle =
    .label = Translate Title
itemmenu-translateAbstract =
    .label = Translate Abstract


================================================
FILE: addon/locale/en-US/panel.ftl
================================================
translate =
    .label = Translate
    .tooltiptext = { PLATFORM() ->
        [macos] ⌘
       *[other] Ctrl
    } + T

swapLanguage =
    .tooltiptext = Swap Language

auto = Auto-Trans:
autoTranslateSelection =
    .label = Selection
autoTranslateAnnotation =
    .label = Annotation

selection = Selection:
enableConcat =
    .label = Concat Mode
clearConcat =
    .label = Clear

copy = Copy:
copyRaw =
    .label = Raw
copyResult =
    .label = Result
copyBoth =
    .label = Both


================================================
FILE: addon/locale/en-US/preferences.ftl
================================================
pref-general = General

pref-basic-enableAuto =
    .label = Automatically Translate Selection
pref-basic-enableComment =
    .label = Automatically Translate Annotation
pref-basic-enablePopup =
    .label = Enable Reader Selection Pop-up
pref-basic-enableHidePopupTextarea =
    .label = Hide Pop-up Text Area
pref-basic-annotationTranslationInComment =
    .label = Save Translation in Annotation Comment
pref-basic-annotationTranslationInBody =
    .label = Save Translation in Annotation Body
pref-basic-enableAnnotationFromSyncTranslation =
    .label = Automatically Translate Annotation from Sync
pref-basic-enableNote =
    .label = Show "Add Translation to Note" in Pop-up
pref-basic-enableNoteReplaceMode =
    .label = Replace Raw Text When Adding Translation to Note
pref-basic-enableAutoTagAnnotation =
    .label = Automatically Tag Annotation After Translation
pref-basic-annotationTagContent =
    .value = Tag
pref-audio-autoPlay =
    .label = Auto-play Pronunciation
pref-audio-showPlayBtn =
    .label = Show Play Buttons🔊 in Pop-up Panel

pref-service = Service

pref-service-sentenceServices =
    .value = Translation Services
pref-service-sentenceServicesSecret =
    .value = Secret
pref-service-attachPaperContext =
    .label = Feed GPT/Claude/Gemini Services with Title and Abstract
pref-service-useWordService =
    .label = Use Dictionary Service for Word Translation
pref-service-wordServices =
    .value = Dictionary Services
pref-service-wordServicesSecret =
    .value = Secret
pref-service-langfrom =
    .value = Translate From
pref-service-langto =
    .value = To
pref-service-hint =
    .value = Service📍requires custom configuration; 🗝️requires a secret key. See GitHub for details

pref-service-manageKeys =
    .label = Manage Secret Keys
pref-service-manageKeys-hint =
    .value = Display saved secret keys for bulk import and export:
pref-service-renameServices =
    .label = Rename Custom GPT🗝️ Services
pref-service-renameServices-hint =
    .value = Show Services to rename or view mappings:

pref-interface = User Interface

pref-interface-fontSize =
    .value = Font Size
pref-interface-lineHeight =
    .value = Line Height
pref-interface-showItemMenu =
    .label = Show Item Context Menu
pref-interface-showItemMenuTitleTranslation =
    .label = Item Context Menu: Show Title Translation
pref-interface-showItemMenuAbstractTranslation =
    .label = Item Context Menu: Show Abstract Translation
pref-interface-showSidebarEngine =
    .label = Item Pane Section: Show Service Selection Menu
pref-interface-hideUnconfiguredServices =
    .label = Item Pane Section: Hide Unconfigured Services from Menu
pref-interface-showSidebarLanguage =
    .label = Item Pane Section: Show Language Selection Menu
pref-interface-showSidebarSettings =
    .label = Item Pane Section: Show Auto-Trans Settings
pref-interface-showSidebarConcat =
    .label = Item Pane Section: Show Concatenated Translation Menu
pref-interface-enableConcatKey =
    .label = Item Pane Section: Hold down { PLATFORM() ->
        [macos] ⌘
       *[other] Ctrl
    } to enable Concat Mode
pref-interface-showSidebarRaw =
    .label = Item Pane Section: Show Raw
pref-interface-enableMathRendering =
    .label = Item Pane Section: Render LaTeX math in translation
pref-interface-showSidebarCopy =
    .label = Item Pane Section: Show Copy Buttons
pref-interface-rawResultOrder =
    .label = Item Pane Section: Reverse Order of Raw and Translated Text
pref-interface-showItemBoxTitleTranslation =
    .label = Item Pane Info: Show Title Translation
pref-interface-showItemBoxAbstractTranslation =
    .label = Item Pane Info: Show Abstract Translation
pref-interface-keepWindowTop =
    .label = Standalone: Keep Window on Top
pref-interface-keepPopupSize =
    .label = Pop-up: Remember Size

pref-advanced = Advanced

pref-advanced-enableAutoDetectLanguage =
    .label = Automatically Detect Item Language
pref-advanced-disabledLanguages =
    .value = Disable automatic translation for file languages (comma-separated)
pref-advanced-disabledLanguages-alert = Reopen files or restart Zotero to apply changes.
pref-advanced-extraEngines =
    .value = Additional services in standalone window (comma-separated)
pref-advanced-splitChar =
    .value = Delimiter (between text and translation)
pref-advanced-resultRegex =
    .value = Regex for removing extra text from translation results (leave empty to disable)
pref-advanced-reset =
    .value = Reset field of selected items in library:
pref-advanced-reset-titleTranslation =
    .label = Title Translation
pref-advanced-reset-abstractTranslation =
    .label = Abstract Translation

pref-about = About

pref-about-feedback =
    .value = GitHub
pref-about-docs =
    .value = Documentation (ZH)
pref-about-version =
    .value = { $name } Version { $version } Build { $time }

pref-advanced-stripEmptyLines =
    .label = Strip empty lines and thinking from translation results


================================================
FILE: addon/locale/en-US/standalone.ftl
================================================
add-source =
    .label = Add Source
remove-source =
    .label = Remove
pin-window =
    .label = { $mode ->
        [pinned] 📌Unpin
        *[other] 📍Pin
    }


================================================
FILE: addon/locale/it-IT/addon.ftl
================================================
service-huoshanweb=Volcengine Web
service-tencenttransmart=Tencent Transmart
service-huoshan=Huoshan
service-googleapi=Google(API)
service-google=Google
service-cnki=CNKI
service-youdao=Youdao
service-youdaozhiyun=Youdao Zhiyun
service-youdaozhiyunllm=Youdao LLM
service-niutranspro=Niu Trans
service-microsoft=Microsoft
service-caiyun=Caiyun
service-libretranslate=LibreTranslate
service-mtranserver=MTranServer
service-deeplfree=DeepL(Free Plan)
service-deeplpro=DeepL(Pro Plan)
service-deeplcustom=DeepLX(API)
service-deeplx=DeepLx
service-baidu=Baidu
service-baidufield=Baidu Field
service-openl=OpenL
service-tencent=Tencent
service-aliyun=Aliyun
service-xftrans=Xftrans
service-chatgpt=ChatGPT
service-customgpt1=Custom GPT 1
service-customgpt2=Custom GPT 2
service-customgpt3=Custom GPT 3
service-azuregpt=AzureGPT
service-gemini=Gemini
service-qwenmt=Qwen-MT
service-claude=Claude
service-haici=Haici
service-bing=Bing
service-pot=Pot
service-nllb=NLLB
service-bingdict=Bing Dict(en→zh)🔊
service-cambridgedict=Cambridge Dict(en→other)🔊
service-haicidict=Haici Dict(en→zh)🔊
service-collinsdict=Collins Dict(en→zh)🔊
service-youdaodict=Youdao Dict(en→zh)🔊
service-freedictionaryapi=FreeDictionaryAPI(en→en)
service-webliodict=Weblio Dict(en→ja)
service-errorPrefix=[Errore nella richiesta]
    Servizio di traduzione non disponibile, segreto non valido, o richiesta troppo rapida.
    Si prega di usare un altro servizio di traduzione o di segnalare il problema qui: 
    https://github.com/windingwind/zotero-pdf-translate/issues
    
    Il messaggio seguente non è di Zotero o dell'estensione Translate ma proviene da

service-dialog-config=Config
service-dialog-title={ $service } Config
service-dialog-save=Save
service-dialog-close=Close
service-dialog-help=Help
service-dialog-custom-request-description=Refer to API documentation of service provider, add custom parameters. These will be merged with the standard parameters (model, messages, temperature, stream).
service-dialog-custom-request-title=Custom Request Parameters
service-dialog-custom-request-add-param=Add Parameter

service-niutranspro-dialog-endpoint=Endpoint
service-niutranspro-dialog-username=Nome utente
service-niutranspro-dialog-password=Password
service-niutranspro-dialog-signup=Registrati
service-niutranspro-dialog-forget=Dimentica
service-niutranspro-dialog-dictLib=Lib. Diz.
service-niutranspro-dialog-memoryLib=Lib. Mem.
service-niutranspro-dialog-tip0=Si prega di collegarsi a
service-niutranspro-dialog-tip1=Niutrans Cloud Platform
service-niutranspro-dialog-tip2=per aggiungere il vocabolo alla libreria dei dizionari
service-niutranspro-dialog-signin=Autenticati
service-niutranspro-dialog-refresh=Aggiorna
service-niutranspro-dialog-signout=Esci

service-deeplcustom-dialog-endPoint=EndPoint
service-deeplx-dialog-endPoint=API

service-chatgpt-dialog-endPoint=API
service-chatgpt-dialog-model=Modello
service-chatgpt-dialog-temperature=Temperatura
service-chatgpt-dialog-prompt=Prompt
service-chatgpt-dialog-stream=Stream
service-chatgpt-dialog-custom-request=Custom Request

service-azuregpt-dialog-endPoint=EndPoint
service-azuregpt-dialog-model=Nome
service-azuregpt-dialog-temperature=Temperatura
service-azuregpt-dialog-apiVersion=Versione
service-azuregpt-dialog-prompt=Prompt
service-azuregpt-dialog-stream=Stream
service-azuregpt-dialog-custom-request=Custom Request

service-xftrans-dialog-engine=API Engine

service-gemini-dialog-endPoint=EndPoint
service-gemini-dialog-prompt=Prompt
service-gemini-dialog-stream=Stream

service-qwenmt-dialog-endPoint=EndPoint
service-qwenmt-dialog-model=Model
service-qwenmt-dialog-domains=Domains

service-claude-dialog-endPoint=EndPoint
service-claude-dialog-model=Model
service-claude-dialog-temperature=Temp
service-claude-dialog-prompt=Prompt
service-claude-dialog-stream=Stream
service-claude-dialog-maxTokens=Max Tokens

service-cnki-settings=Impostazioni
service-cnki-dialog-regex=Regex per gli annunci CNKI
service-cnki-dialog-split=Dividi automaticamente la traduzione per più di 800 caratteri

service-aliyun-dialog-action=Azione
service-aliyun-dialog-scene=Scena

service-tencent-dialog-secretid=Segreto ID
service-tencent-dialog-secretkey=Segreto Key
service-tencent-dialog-region=Regione
service-tencent-dialog-projectid=Progetto ID
service-tencent-dialog-termrepoid=Term Repo IDs (opzionale)
service-tencent-dialog-sentrepoid=Sent Repo IDs (opzionale)

service-youdaozhiyun-dialog-domain=Settore
service-youdaozhiyunllm-dialog-model=Modello
service-youdaozhiyunllm-dialog-pro=Youdao LLM Pro-14B
service-youdaozhiyunllm-dialog-lite=Youdao LLM Lite-1.5B
service-youdaozhiyunllm-dialog-prompt=Prompt
service-youdaozhiyunllm-dialog-stream=Stream

readerpopup-translate-label=Traduci
readerpopup-addToNote-label=Aggiungi traduzione alla nota

pref-title=Translate

field-titleTranslation=Traduzione del titolo
field-abstractTranslation=Traduzione dell'Abstract

status-translating=Traduzione in corso...
sideBarIcon-title=Translate annotation

service-manageKeys-title=Gestione delle chiavi dei segreto di traduzione
service-manageKeys-head=Gestisci tutte le dei segreto di traduzione. Modifica direttamente il file JSON e clicca su Salva.
service-manageKeys-save=Salva
service-manageKeys-close=Chiudi

service-renameServices-title=Rinominare i servizi Custom GPT
service-renameServices-head=Inserisci il nuovo nome e clicca su Salva.
service-renameServices-hint=Le modifiche avranno effetto dopo il riavvio del plugin o di Zotero
service-renameServices-save=Salva
service-renameServices-close=Chiudi

service-libretranslate-dialog-endPoint=API Endpoint

service-mtranserver-dialog-endPoint=EndPoint
service-mtranserver-dialog-versionlabel=Use MTranServer v3.0.0+

service-pot-dialog-port=Port

service-nllb-dialog-model=nllb Modello
service-nllb-dialog-apiendpoint=nllb-api EndPoint
service-nllb-dialog-apistream=nllb-api Stream
service-nllb-dialog-serveendpoint=nllb-serve EndPoint
service-nllb-dialog-apilabel=nllb-api Docs
service-nllb-dialog-servelabel=nllb-serve Docs



================================================
FILE: addon/locale/it-IT/mainWindow.ftl
================================================
itemPaneSection-header =
    .label = Translate
itemPaneSection-sidenav =
    .tooltiptext = Translate
itemPaneSection-fullHeight =
    .tooltiptext = Full height
itemPaneSection-openStandalone =
    .tooltiptext = Open in standalone window

field-titleTranslation = Title Translation
field-abstractTranslation = Abstract Translation

itemmenu-translateTitle =
    .label = Traduci Titolo
itemmenu-translateAbstract =
    .label = Traduci Abstract

================================================
FILE: addon/locale/it-IT/panel.ftl
================================================
translate =
    .label = Translate
    .tooltiptext = { PLATFORM() ->
        [macos] ⌘
       *[other] Ctrl
    } + T

swapLanguage =
    .tooltiptext = Swap Language

auto = Auto-Trans:
autoTranslateSelection =
    .label = Selection
autoTranslateAnnotation =
    .label = Annotation

selection = Selection:
enableConcat =
    .label = Concat Mode
clearConcat =
    .label = Clear

copy = Copy:
copyRaw =
    .label = Raw
copyResult =
    .label = Result
copyBoth =
    .label = Both


================================================
FILE: addon/locale/it-IT/preferences.ftl
================================================
pref-general = Generale

pref-basic-enableAuto =
    .label = Traduci automaticamente la selezione
pref-basic-enableComment =
    .label = Traduci automaticamente le annotazioni
pref-basic-enablePopup =
    .label = Attiva popup di selezione nel lettore
pref-basic-enableHidePopupTextarea =
    .label = Nascondi l'area del testo del popup
pref-basic-annotationTranslationInComment =
    .label = Salva traduzione nel commento dell'annotazione
pref-basic-annotationTranslationInBody =
    .label = Salva traduzione nel corpo dell'annotazione
pref-basic-enableAnnotationFromSyncTranslation =
    .label = Auto-traduci annotazioni da Sync
pref-basic-enableNote =
    .label = Mostra "Aggiungi traduzione alla nota" nel popup
pref-basic-enableNoteReplaceMode =
    .label = Sostituisci il testo d'origine quando aggiungi traduzione alla nota
pref-basic-enableAutoTagAnnotation =
    .label = Tagga automaticamente l'annotazione dopo la traduzione
pref-basic-annotationTagContent =
    .value = Tag
pref-audio-autoPlay =
    .label = Riproduci automaticamente la pronuncia
pref-audio-showPlayBtn =
    .label = Mostra i pulsanti di riproduzione🔊 nel pannello del popup

pref-service = Servizio

pref-service-sentenceServices =
    .value = Servizi di traduzione
pref-service-sentenceServicesSecret =
    .value = Segreto
pref-service-attachPaperContext =
    .label = Fornisci servizi GPT/Claude/Gemini con titolo e abstract
pref-service-useWordService =
    .label = Usa un dizionario online per la traduzione di termini
pref-service-wordServices =
    .value = Dizionari online
pref-service-wordServicesSecret =
    .value = Segreto
pref-service-langfrom =
    .value = Traduci da
pref-service-langto =
    .value = A
pref-service-hint =
    .value = Servizio📍richiede configurazione personalizzata; 🗝️richiede un segreto. Vedi GitHub per maggiori dettagli

pref-service-manageKeys =
    .label = Gestisci segreto
pref-service-manageKeys-hint =
    .value = Visualizza le segreto salvate per l'importazione e l'esportazione in blocco:
pref-service-renameServices =
    .label = Rinominare i servizi Custom GPT🗝️
pref-service-renameServices-hint =
    .value = Mostra servizi per rinominare o visualizzare le mappature:

pref-interface = Interfaccia utente

pref-interface-fontSize =
    .value = Dimensione font
pref-interface-lineHeight =
    .value = Altezza delle linee
pref-interface-showItemMenu =
    .label = Mostra menu contestuale dell'elemento
pref-interface-showItemMenuTitleTranslation =
    .label = Menu contestuale: Mostra la traduzione del titolo
pref-interface-showItemMenuAbstractTranslation =
    .label = Menu contestuale: Mostra la traduzione dell'abstract
pref-interface-showSidebarEngine =
    .label = Sezione del pannello dell'elemento: Mostra il menu di selezione della Servizi
pref-interface-hideUnconfiguredServices =
    .label = Sezione del pannello dell'elemento: Nascondi servizi non configurati dal menu
pref-interface-showSidebarLanguage =
    .label = Sezione del pannello dell'elemento: Mostra il menu di selezione della lingua
pref-interface-showSidebarSettings =
    .label = Sezione del pannello dell'elemento: Mostra le Traduci automaticamente impostazioni
pref-interface-showSidebarConcat =
    .label = Sezione del pannello dell'elemento: Mostra il menu per la traduzione concatenata
pref-interface-enableConcatKey =
    .label = Sezione del pannello dell'elemento: Tenere premuto il tasto { PLATFORM() ->
        [macos] ⌘
       *[other] Ctrl
    } per attivare la modalità di giunzione
pref-interface-showSidebarRaw =
    .label = Sezione del pannello dell'elemento: Mostra il testo originale
pref-interface-enableMathRendering =
    .label = Sezione del pannello: Render LaTeX nella traduzione
pref-interface-showSidebarCopy =
    .label = Sezione del pannello dell'elemento: Mostra i pulsanti di copia
pref-interface-rawResultOrder =
    .label = Sezione del pannello dell'elemento: Inverti l'ordine del testo originale e della traduzione
pref-interface-showItemBoxTitleTranslation =
    .label = Pannello informazioni: Mostra la traduzione del titolo
pref-interface-showItemBoxAbstractTranslation =
    .label = Pannello informazioni: Mostra la traduzione dell'abstract
pref-interface-keepWindowTop =
    .label = Finestra indipendente: Mantieni in primo piano
pref-interface-keepPopupSize =
    .label = Popup: Ricorda la dimensione

pref-advanced = Avanzate

pref-advanced-enableAutoDetectLanguage =
    .label = Rilevamento automatico della lingua dell'elemento
pref-advanced-disabledLanguages =
    .value = Disabilita la traduzione automatica per i file in lingue specifiche (separare con ',')
pref-advanced-disabledLanguages-alert = Riapri i file o riavvia Zotero per applicare le modifiche.
pref-advanced-extraEngines =
    .value = Servizi extra nella finestra indipendente (separare con ',')
pref-advanced-splitChar =
    .value = Carattere di divisione (tra testo e traduzione)
pref-advanced-resultRegex =
    .value = Regex per rimuovere il testo extra dai risultati della traduzione (lasciare vuoto per disabilitare)
pref-advanced-reset =
    .value = Reimposta il campo degli elementi selezionati nella libreria:
pref-advanced-reset-titleTranslation =
    .label = Traduzione del titolo
pref-advanced-reset-abstractTranslation =
    .label = Traduzione dell'abstract

pref-about = Informazioni

pref-about-feedback =
    .value = GitHub
pref-about-docs =
    .value = Documentazione (ZH)
pref-about-version =
    .value = { $name } Versione { $version } Build { $time }

pref-advanced-stripEmptyLines =
    .label = Rimuovi le righe vuote e pensieri dai risultati della traduzione


================================================
FILE: addon/locale/it-IT/standalone.ftl
================================================
add-source =
    .label = Aggiungi servizio di traduzione
remove-source =
    .label = Rimuovi
pin-window =
    .label = { $mode ->
        [pinned] 📌Sblocca
        *[other] 📍Fissa
    }


================================================
FILE: addon/locale/zh-CN/addon.ftl
================================================
service-huoshanweb=火山网页翻译
service-tencenttransmart=腾讯TranSmart
service-huoshan=火山翻译
service-googleapi=Google(API)
service-google=Google
service-cnki=CNKI
service-youdao=有道
service-youdaozhiyun=有道智云
service-youdaozhiyunllm=有道子曰
service-niutranspro=小牛
service-microsoft=微软
service-caiyun=彩云
service-libretranslate=LibreTranslate
service-mtranserver=MTranServer
service-deeplfree=DeepL(免费订阅)
service-deeplpro=DeepL(Pro订阅)
service-deeplcustom=DeepLX(API)
service-deeplx=DeepLX
service-baidu=百度
service-baidufield=百度垂直领域
service-openl=OpenL
service-tencent=腾讯
service-aliyun=阿里
service-xftrans=讯飞
service-chatgpt=ChatGPT
service-customgpt1=自定义GPT1
service-customgpt2=自定义GPT2
service-customgpt3=自定义GPT3
service-azuregpt=AzureGPT
service-gemini=Gemini
service-qwenmt=Qwen-MT
service-claude=Claude
service-haici=海词
service-bing=必应
service-pot=Pot
service-nllb=NLLB
service-bingdict=必应词典(en→zh)🔊
service-cambridgedict=剑桥词典(en→other)🔊
service-haicidict=海词词典(en→zh)🔊
service-collinsdict=科林斯词典(en→zh)🔊
service-youdaodict=有道词典(en→zh)🔊
service-freedictionaryapi=FreeDictionaryAPI(en→en)
service-webliodict=Weblio Dict(en→ja)
service-errorPrefix=[请求错误]
    此翻译服务不可用,可能是密钥错误,也可能是请求过快。
    可以尝试其他翻译服务,或者来此查看相关回答:
    https://zotero.yuque.com/staff-gkhviy/pdf-trans/age09f
    
    请注意,这些错误与 Zotero 和本翻译插件无关,由该翻译服务引起:

service-dialog-config=配置
service-dialog-title={ $service } 配置
service-dialog-save=保存
service-dialog-close=关闭
service-dialog-help=帮助
service-dialog-custom-request-description=参考服务提供商的API文档,添加自定义参数。这些参数将与标准参数合并。
service-dialog-custom-request-title=自定义请求参数
service-dialog-custom-request-add-param=添加参数

service-niutranspro-dialog-endpoint=接口
service-niutranspro-dialog-username=用户名
service-niutranspro-dialog-password=密码
service-niutranspro-dialog-signup=注册
service-niutranspro-dialog-forget=忘记密码
service-niutranspro-dialog-dictLib=术语词典
service-niutranspro-dialog-memoryLib=翻译记忆
service-niutranspro-dialog-tip0=请到
service-niutranspro-dialog-tip1=小牛翻译云平台
service-niutranspro-dialog-tip2=进行添加术语词典库
service-niutranspro-dialog-signin=登录
service-niutranspro-dialog-refresh=刷新
service-niutranspro-dialog-signout=退出登录

service-deeplcustom-dialog-endPoint=接口
service-deeplx-dialog-endPoint=接口

service-chatgpt-dialog-endPoint=接口
service-chatgpt-dialog-model=模型
service-chatgpt-dialog-temperature=温度
service-chatgpt-dialog-prompt=提示词
service-chatgpt-dialog-stream=流式输出
service-chatgpt-dialog-custom-request=自定义请求

service-azuregpt-dialog-endPoint=接口
service-azuregpt-dialog-model=部署名
service-azuregpt-dialog-temperature=温度
service-azuregpt-dialog-stream=流式输出
service-azuregpt-dialog-apiVersion=版本
service-azuregpt-dialog-prompt=提示词
service-azuregpt-dialog-custom-request=自定义请求

service-xftrans-dialog-engine=翻译引擎

service-gemini-dialog-endPoint=接口
service-gemini-dialog-prompt=提示词
service-gemini-dialog-stream=流式输出

service-qwenmt-dialog-endPoint=API地址
service-qwenmt-dialog-model=模型
service-qwenmt-dialog-domains=领域提示词

service-claude-dialog-endPoint=接口
service-claude-dialog-model=模型
service-claude-dialog-temperature=温度
service-claude-dialog-prompt=提示词
service-claude-dialog-stream=流式输出
service-claude-dialog-maxTokens=最大输出长度

service-cnki-settings=设置
service-cnki-dialog-regex=CNKI广告移除正则表达式
service-cnki-dialog-split=超过800字符自动拆分翻译

service-aliyun-dialog-action=版本
service-aliyun-dialog-scene=场景

service-tencent-dialog-secretid=密钥ID
service-tencent-dialog-secretkey=密钥Key
service-tencent-dialog-region=地域
service-tencent-dialog-projectid=项目ID
service-tencent-dialog-termrepoid=术语库IDs (可选)
service-tencent-dialog-sentrepoid=例句库IDs (可选)

service-youdaozhiyun-dialog-domain=领域
service-youdaozhiyunllm-dialog-model=模型
service-youdaozhiyunllm-dialog-pro=有道智云子曰大模型Pro-14B
service-youdaozhiyunllm-dialog-lite=有道智云子曰大模型Lite-1.5B
service-youdaozhiyunllm-dialog-prompt=提示词
service-youdaozhiyunllm-dialog-stream=流式输出

readerpopup-translate-label=翻译
readerpopup-addToNote-label=添加翻译至笔记

pref-title=翻译

field-titleTranslation=标题翻译
field-abstractTranslation=摘要翻译

status-translating=正在翻译...
sideBarIcon-title=翻译注释

service-manageKeys-title=管理翻译服务密钥
service-manageKeys-head=管理所有翻译服务密钥,直接编辑 JSON 文件并点击保存。
service-manageKeys-save=保存
service-manageKeys-close=关闭

service-renameServices-title=重命名自定义GPT服务
service-renameServices-head=输入新的服务名称并点击保存。
service-renameServices-hint=所做更改将在插件或Zotero重启后生效
service-renameServices-save=保存
service-renameServices-close=关闭

service-libretranslate-dialog-endPoint=API 地址

service-mtranserver-dialog-endPoint=接口
service-mtranserver-dialog-versionlabel=使用MTranServer v3.0.0+

service-pot-dialog-port=端口

service-nllb-dialog-model=nllb 模型
service-nllb-dialog-apiendpoint=nllb-api 接口
service-nllb-dialog-apistream=nllb-api 流式输出
service-nllb-dialog-serveendpoint=nllb-serve 接口
service-nllb-dialog-apilabel=nllb-api 文档
service-nllb-dialog-servelabel=nllb-serve 文档



================================================
FILE: addon/locale/zh-CN/mainWindow.ftl
================================================
itemPaneSection-header =
    .label = 翻译
itemPaneSection-sidenav =
    .tooltiptext = 翻译
itemPaneSection-fullHeight =
    .tooltiptext = 自适应高度
itemPaneSection-openStandalone =
    .tooltiptext = 在独立窗口中打开

field-titleTranslation = 标题翻译
field-abstractTranslation = 摘要翻译

itemmenu-translateTitle =
    .label = 翻译标题
itemmenu-translateAbstract =
    .label = 翻译摘要


================================================
FILE: addon/locale/zh-CN/panel.ftl
================================================
translate =
    .label = 翻译
    .tooltiptext = { PLATFORM() ->
        [macos] ⌘
       *[other] Ctrl
    } + T

swapLanguage =
    .tooltiptext = 交换语言

auto = 自动翻译: 
autoTranslateSelection =
    .label = 选择内容
autoTranslateAnnotation =
    .label = 注释

selection = 选区: 
enableConcat =
    .label = 拼接模式
clearConcat =
    .label = 清空

copy = 复制: 
copyRaw =
    .label = 源文本
copyResult =
    .label = 结果
copyBoth =
    .label = 两者


================================================
FILE: addon/locale/zh-CN/preferences.ftl
================================================
pref-general = 通用

pref-basic-enableAuto =
    .label = 自动翻译选择内容
pref-basic-enableComment =
    .label = 自动翻译注释
pref-basic-enablePopup =
    .label = 启用阅读器选择弹窗
pref-basic-enableHidePopupTextarea =
    .label = 隐藏弹窗文本区域
pref-basic-annotationTranslationInComment =
    .label = 保存翻译至注释评论
pref-basic-annotationTranslationInBody =
    .label = 保存翻译至注释正文
pref-basic-enableAnnotationFromSyncTranslation =
    .label = 自动翻译来自同步的注释
pref-basic-enableNote =
    .label = 在弹窗中显示“添加翻译至笔记”
pref-basic-enableNoteReplaceMode =
    .label = 添加翻译至笔记时替换原始文本
pref-basic-enableAutoTagAnnotation =
    .label = 翻译后自动为注释添加标签
pref-basic-annotationTagContent =
    .value = 标签
pref-audio-autoPlay =
    .label = 自动播放发音
pref-audio-showPlayBtn =
    .label = 弹窗中显示播放按钮🔊

pref-service = 服务

pref-service-sentenceServices =
    .value = 翻译服务
pref-service-sentenceServicesSecret =
    .value = 密钥
pref-service-attachPaperContext =
    .label = 向GPT/Claude/Gemini服务提供论文标题和摘要
pref-service-useWordService =
    .label = 使用字典服务翻译词语
pref-service-wordServices =
    .value = 字典服务
pref-service-wordServicesSecret =
    .value = 密钥
pref-service-langfrom =
    .value = 从
pref-service-langto =
    .value = 翻译到
pref-service-hint =
    .value = 服务📍需要自定义配置;🗝️需要密钥。详情请参阅GitHub

pref-service-manageKeys =
    .label = 密钥管理
pref-service-manageKeys-hint =
    .value = 展示已保存的密钥以便批量导入和导出:
pref-service-renameServices =
    .label = 重命名自定义GPT🗝️服务
pref-service-renameServices-hint =
    .value = 显示服务以重命名或查看映射:

pref-interface = 用户界面

pref-interface-fontSize =
    .value = 字体大小
pref-interface-lineHeight =
    .value = 行高
pref-interface-showItemMenu =
    .label = 显示条目上下文菜单
pref-interface-showItemMenuTitleTranslation =
    .label = 条目上下文菜单:显示标题翻译
pref-interface-showItemMenuAbstractTranslation =
    .label = 条目上下文菜单:显示摘要翻译
pref-interface-showSidebarEngine =
    .label = 条目面板区块:显示翻译服务选择菜单
pref-interface-hideUnconfiguredServices =
    .label = 条目面板区块:在菜单中隐藏未配置的服务
pref-interface-showSidebarLanguage =
    .label = 条目面板区块:显示语言选择菜单
pref-interface-showSidebarSettings =
    .label = 条目面板区块:显示自动翻译设置
pref-interface-showSidebarConcat =
    .label = 条目面板区块:显示拼接翻译菜单
pref-interface-enableConcatKey =
    .label = 条目面板区块:按住 { PLATFORM() ->
        [macos] ⌘
       *[other] Ctrl
    } 键激活拼接模式
pref-interface-showSidebarRaw =
    .label = 条目面板区块:显示原文
pref-interface-enableMathRendering =
    .label = 条目面板区块:在翻译中渲染 LaTeX 公式
pref-interface-showSidebarCopy =
    .label = 条目面板区块:显示复制按钮
pref-interface-rawResultOrder =
    .label = 条目面板区块:反转原文与翻译文本顺序
pref-interface-showItemBoxTitleTranslation =
    .label = 信息栏:显示标题翻译
pref-interface-showItemBoxAbstractTranslation =
    .label = 信息栏:显示摘要翻译
pref-interface-keepWindowTop =
    .label = 独立窗口:保持最前
pref-interface-keepPopupSize =
    .label = 弹窗:记住大小

pref-advanced = 高级

pref-advanced-enableAutoDetectLanguage =
    .label = 自动检测条目语言
pref-advanced-disabledLanguages =
    .value = 对文件语言禁用自动翻译(用逗号分隔)
pref-advanced-disabledLanguages-alert = 重新打开文件或重启Zotero以应用更改。
pref-advanced-extraEngines =
    .value = 独立窗口额外翻译服务(用逗号分隔)
pref-advanced-splitChar =
    .value = 分隔符(原文与翻译之间)
pref-advanced-resultRegex =
    .value = 用于移除翻译结果中多余文本的正则表达式(留空以禁用)
pref-advanced-reset =
    .value = 重置库中选中条目的字段:
pref-advanced-reset-titleTranslation =
    .label = 标题翻译
pref-advanced-reset-abstractTranslation =
    .label = 摘要翻译

pref-about = 关于

pref-about-feedback =
    .value = GitHub
pref-about-docs =
    .value = 文档 (中文)
pref-about-version =
    .value = { $name } 版本 { $version } Build { $time }

pref-advanced-stripEmptyLines =
    .label = 从翻译结果中删除空行和思考内容



================================================
FILE: addon/locale/zh-CN/standalone.ftl
================================================
add-source =
    .label = 添加源
remove-source =
    .label = 移除
pin-window =
    .label = { $mode ->
        [pinned] 📌取消置顶
        *[other] 📍置顶
    }


================================================
FILE: addon/manifest.json
================================================
{
  "manifest_version": 2,
  "name": "__addonName__",
  "version": "__buildVersion__",
  "description": "__description__",
  "author": "__author__",
  "homepage_url": "__homepage__",
  "icons": {
    "48": "chrome/content/icons/favicon.png",
    "96": "chrome/content/icons/favicon@2x.png"
  },
  "applications": {
    "zotero": {
      "id": "__addonID__",
      "update_url": "__updateURL__",
      "strict_min_version": "7.9.9",
      "strict_max_version": "9.9.9"
    }
  }
}


================================================
FILE: addon/prefs.js
================================================
pref("__prefsPrefix__.enableAuto", true);
pref("__prefsPrefix__.enableDict", true);
pref("__prefsPrefix__.attachPaperContext", false);
pref("__prefsPrefix__.enablePopup", true);
pref("__prefsPrefix__.enableComment", false);
pref("__prefsPrefix__.enableAnnotationFromSyncTranslation", false);
pref("__prefsPrefix__.enableAutoTagAnnotation", false);
pref("__prefsPrefix__.annotationTagContent", "");
pref("__prefsPrefix__.annotationTranslationPosition", "comment");
pref("__prefsPrefix__.enableNote", true);
pref("__prefsPrefix__.enableNoteReplaceMode", false);
pref("__prefsPrefix__.translateSource", "");
pref("__prefsPrefix__.dictSource", "");
pref("__prefsPrefix__.sourceLanguage", "en-US");
pref("__prefsPrefix__.targetLanguage", "");
pref("__prefsPrefix__.fontSize", "12");
pref("__prefsPrefix__.lineHeight", "1.5");
pref("__prefsPrefix__.splitChar", "\ud83d\udd24");
pref("__prefsPrefix__.resultRegex", "");
pref("__prefsPrefix__.rawResultOrder", false);
pref("__prefsPrefix__.showItemMenuTitleTranslation", true);
pref("__prefsPrefix__.showItemMenuAbstractTranslation", true);
pref("__prefsPrefix__.showSidebarEngine", true);
pref("__prefsPrefix__.hideUnconfiguredServices", false);
pref("__prefsPrefix__.showSidebarSettings", true);
pref("__prefsPrefix__.showSidebarConcat", true);
pref("__prefsPrefix__.enableConcatKey", true);
pref("__prefsPrefix__.showSidebarLanguage", true);
pref("__prefsPrefix__.showSidebarRaw", true);
pref("__prefsPrefix__.showSidebarCopy", true);
pref("__prefsPrefix__.customRawRatio", "1");
pref("__prefsPrefix__.customResultRatio", "1");
pref("__prefsPrefix__.showItemBoxTitleTranslation", true);
pref("__prefsPrefix__.showItemBoxAbstractTranslation", false);
pref("__prefsPrefix__.keepWindowTop", false);
pref("__prefsPrefix__.keepPopupSize", false);
pref("__prefsPrefix__.popupWidth", 105);
pref("__prefsPrefix__.popupHeight", 30);
pref("__prefsPrefix__.niutransEndpoint", "https://niutrans.com/niuInterface");
pref("__prefsPrefix__.niutransUsername", "");
pref("__prefsPrefix__.niutransPassword", "");
pref("__prefsPrefix__.niutransDictNo", "");
pref("__prefsPrefix__.niutransMemoryNo", "");
pref("__prefsPrefix__.niutransDictLibList", "[]");
pref("__prefsPrefix__.niutransMemoryLibList", "[]");
pref("__prefsPrefix__.autoPlay", false);
pref("__prefsPrefix__.showPlayBtn", true);
pref("__prefsPrefix__.enableAutoDetectLanguage", true);
pref("__prefsPrefix__.disabledLanguages", "");
pref("__prefsPrefix__.extraEngines", "");
pref("__prefsPrefix__.titleColumnMode", "raw");
pref(
  "__prefsPrefix__.chatGPT.endPoint",
  "https://api.openai.com/v1/chat/completions",
);
pref("__prefsPrefix__.chatGPT.model", "gpt-4o-mini");
pref("__prefsPrefix__.chatGPT.temperature", "1.0");
pref(
  "__prefsPrefix__.chatGPT.prompt",
  "As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows:  🔤 ${sourceText} 🔤  Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.chatGPT.stream", true);
pref("__prefsPrefix__.chatGPT.customParams", "");
pref("__prefsPrefix__.azureGPT.endPoint", "");
pref("__prefsPrefix__.azureGPT.model", "");
pref("__prefsPrefix__.azureGPT.apiVersion", "2023-05-15");
pref("__prefsPrefix__.azureGPT.temperature", "1.0");
pref(
  "__prefsPrefix__.azureGPT.prompt",
  "As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows:  🔤 ${sourceText} 🔤  Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.azureGPT.stream", true);
pref("__prefsPrefix__.azureGPT.customParams", "");
pref(
  "__prefsPrefix__.gemini.endPoint",
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite",
);
pref(
  "__prefsPrefix__.gemini.prompt",
  "As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows:  🔤 ${sourceText} 🔤  Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.gemini.stream", true);
pref(
  "__prefsPrefix__.cnkiRegex",
  "(查看名企职位.+?https://dict.cnki.net[a-zA-Z./]+.html?)",
);
pref("__prefsPrefix__.cnkiSplitSecond", 1);
pref("__prefsPrefix__.cnkiUseSplit", true);
pref("__prefsPrefix__.deeplx.endpoint", "https://www2.deepl.com/jsonrpc");
pref("__prefsPrefix__.deeplcustom.endpoint", "");
pref("__prefsPrefix__.pot.port", 60828);
pref(
  "__prefsPrefix__.qwenmt.endPoint",
  "https://dashscope.aliyuncs.com/compatible-mode",
);
pref("__prefsPrefix__.qwenmt.model", "qwen-mt-plus");
pref("__prefsPrefix__.qwenmt.domains", "");
pref("__prefsPrefix__.aliyun.action", "TranslateGeneral");
pref("__prefsPrefix__.aliyun.scene", "general");

pref("__prefsPrefix__.enableMathRendering", false);
pref("__prefsPrefix__.stripEmptyLines", false);
pref("__prefsPrefix__.libretranslate.endpoint", "http://localhost:5000");
pref("__prefsPrefix__.mtranserver.endpoint", "http://localhost:8989/translate");
pref("__prefsPrefix__.mtranserver.versionlabel", false);
pref("__prefsPrefix__.claude.stream", true);
pref(
  "__prefsPrefix__.claude.endPoint",
  "https://api.anthropic.com/v1/messages",
);
pref("__prefsPrefix__.claude.model", "claude-3-7-sonnet-20250219");
pref("__prefsPrefix__.claude.temperature", "0.3");
pref(
  "__prefsPrefix__.claude.prompt",
  "As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows:  🔤 ${sourceText} 🔤  Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.claude.maxTokens", "4000");
pref("__prefsPrefix__.xftrans.engine", "xftrans");
pref("__prefsPrefix__.tencent.region", "ap-shanghai");
pref("__prefsPrefix__.tencent.projectId", "0");
pref("__prefsPrefix__.youdaozhiyun.domain", "general");
pref("__prefsPrefix__.youdaozhiyunllm.model", "0");
pref("__prefsPrefix__.youdaozhiyunllm.stream", true);
pref("__prefsPrefix__.nllb.model", "nllb-api");
pref("__prefsPrefix__.nllb.apiendpoint", "http://localhost:7860");
pref("__prefsPrefix__.nllb.apistream", true);
pref("__prefsPrefix__.nllb.serveendpoint", "http://localhost:6060");


================================================
FILE: eslint.config.mjs
================================================
// @ts-check Let TS check this config file

import eslint from "@eslint/js";
import tseslint from "typescript-eslint";

export default tseslint.config(
  {
    ignores: ["build/**", "dist/**", "node_modules/**", "scripts/"],
  },
  {
    files: ["**/*.ts"],
    extends: [eslint.configs.recommended, ...tseslint.configs.recommended],
    rules: {
      "no-restricted-globals": [
        "error",
        { message: "Use `Zotero.getMainWindow()` instead.", name: "window" },
        {
          message: "Use `Zotero.getMainWindow().document` instead.",
          name: "document",
        },
        {
          message: "Use `Zotero.getActiveZoteroPane()` instead.",
          name: "ZoteroPane",
        },
        "Zotero_Tabs",
      ],

      "@typescript-eslint/ban-ts-comment": [
        "warn",
        {
          "ts-expect-error": "allow-with-description",
          "ts-ignore": "allow-with-description",
          "ts-nocheck": "allow-with-description",
          "ts-check": "allow-with-description",
        },
      ],
      "@typescript-eslint/no-unused-vars": "off",
      "@typescript-eslint/no-explicit-any": [
        "off",
        {
          ignoreRestArgs: true,
        },
      ],
      "@typescript-eslint/no-non-null-assertion": "off",
    },
  },
  {
    // allow to use the `document` and `window` globals directly in CEs
    files: ["src/elements/*.ts"],
    rules: {
      "no-restricted-globals": [
        "error",
        {
          message: "Use `Zotero.getActiveZoteroPane()` instead.",
          name: "ZoteroPane",
        },
        "Zotero_Tabs",
      ],
    },
  },
);


================================================
FILE: package.json
================================================
{
  "name": "zotero-pdf-translate",
  "version": "2.4.3",
  "description": "Translate PDF, EPub, webpage, metadata, annotations, notes to the target language. Support 20+ translate services.",
  "config": {
    "addonName": "Translate for Zotero",
    "addonID": "zoteropdftranslate@euclpts.com",
    "addonRef": "zoteropdftranslate",
    "prefsPrefix": "extensions.zotero.ZoteroPDFTranslate",
    "addonInstance": "PDFTranslate"
  },
  "main": "src/index.ts",
  "scripts": {
    "start": "zotero-plugin serve",
    "build": "tsc --noEmit && zotero-plugin build",
    "release": "zotero-plugin release",
    "lint": "prettier --write . && eslint . --fix",
    "test": "echo \"Error: no test specified\" && exit 1",
    "update-deps": "npm update --save"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/windingwind/zotero-pdf-translate.git"
  },
  "author": "windingwind",
  "license": "AGPL-3.0-or-later",
  "bugs": {
    "url": "https://github.com/windingwind/zotero-pdf-translate/issues"
  },
  "homepage": "https://github.com/windingwind/zotero-pdf-translate#readme",
  "dependencies": {
    "franc": "^6.2.0",
    "iso639-js": "^1.1.3",
    "jsencrypt": "^3.5.0",
    "katex": "^0.16.25",
    "zotero-plugin-toolkit": "^5.1.0-beta.8"
  },
  "devDependencies": {
    "@eslint/js": "^9.39.1",
    "@types/node": "^22.16.5",
    "chokidar-cli": "^3.0.0",
    "concurrently": "^9.2.0",
    "cross-env": "^10.1.0",
    "eslint": "^9.39.1",
    "husky": "^9.1.7",
    "lint-staged": "^16.2.7",
    "prettier": "^3.7.4",
    "typescript": "^5.9.3",
    "typescript-eslint": "^8.48.1",
    "zotero-plugin-scaffold": "^0.8.2",
    "zotero-types": "^4.1.0-beta.3"
  }
}


================================================
FILE: src/addon.ts
================================================
import api from "./api";
import hooks from "./hooks";
import { TranslateTask } from "./utils/task";
import { services, TranslationServices } from "./modules/services";
import { createZToolkit } from "./utils/ztoolkit";
import { config } from "../package.json";

class Addon {
  public data: {
    config: typeof config;
    alive: boolean;
    // Env type, see build.js
    env: "development" | "production";
    ztoolkit: ZToolkit;
    locale: {
      current?: any;
    };
    prefs: {
      window: Window | null;
    };
    panel: {
      tabOptionId: string;
      activePanels: Record<string, (options: any) => void>;
      windowPanel: Window | null;
    };
    popup: {
      currentPopup: HTMLDivElement | null;
    };
    translate: {
      selectedText: string;
      concatKey: boolean;
      concatCheckbox: boolean;
      queue: TranslateTask[];
      maximumQueueLength: number;
      batchTaskDelay: number;
      services: TranslationServices;
      cachedSourceLanguage: Record<number, string>;
      refreshTick: string;
    };
  };
  // Lifecycle hooks
  public hooks: typeof hooks;
  // APIs
  public api: typeof api;

  constructor() {
    this.data = {
      config,
      alive: true,
      env: __env__,
      ztoolkit: createZToolkit(),
      locale: {},
      prefs: { window: null },
      panel: { tabOptionId: "", activePanels: {}, windowPanel: null },
      popup: { currentPopup: null },
      translate: {
        selectedText: "",
        concatKey: false,
        concatCheckbox: false,
        queue: [],
        maximumQueueLength: 100,
        batchTaskDelay: 1000,
        services,
        cachedSourceLanguage: {},
        refreshTick: "",
      },
    };
    this.hooks = hooks;
    this.api = api;
  }
}

export default Addon;


================================================
FILE: src/api.ts
================================================
import { getPref } from "./utils/prefs";
import { TranslateTask } from "./utils/task";
import { version } from "../package.json";

/**
 * To plugin developers: Please use this API to translate your custom text.
 *
 * @param raw raw text for translation.
 * @param options options.
 * @returns TranslateTask object.
 */
async function translate(
  raw: string,
  options: {
    /**
     * The caller identifier.
     * This is for translate service provider to identify the caller.
     * If not provided, the call will fail.
     */
    pluginID: string;
    /**
     * Service id. See src/utils/config.ts > SERVICES
     * If not provided, the default service will be used.
     * If you want to use multiple services, please provide an array of service ids.
     * The first service in the array will be used as the default service.
     * Others will be used as fallback services.
     */
    service?: string | string[];
    /**
     * Zotero item id.
     *
     * For language auto-detect check.
     * If not set, use the default value.
     */
    itemID?: number;
    /**
     * From language
     *
     * If not set, generate at task runtime.
     */
    langfrom?: string;
    /**
     * To language.
     *
     * If not set, generate at task runtime.
     */
    langto?: string;
  },
): Promise<TranslateTask>;
/**
 * @deprecated The implementation of call with second parameter `services` will be removed in the future. Please use `translate(raw, options)` instead.
 *
 * @param raw raw text for translation.
 * @param service service id. See src/utils/config.ts > SERVICES
 * If not provided, the default service will be used.
 * If you want to use multiple services, please provide an array of service ids.
 * The first service in the array will be used as the default service.
 * Others will be used as fallback services.
 * @returns TranslateTask object.
 */
async function translate(
  raw: string,
  service?: string | string[],
): Promise<TranslateTask>;
async function translate(
  raw: string,
  serviceOrOptions?: string | string[] | any,
) {
  let currentService: string;
  let candidateServices: string[] = [];
  let service;
  let isDeprecatedCall = false;

  if (
    !serviceOrOptions ||
    typeof serviceOrOptions === "string" ||
    Array.isArray(serviceOrOptions)
  ) {
    service = serviceOrOptions;
    isDeprecatedCall = true;
  } else if (typeof serviceOrOptions === "object") {
    service = serviceOrOptions.service;
  }
  serviceOrOptions = serviceOrOptions || {};

  if (!isDeprecatedCall && !(serviceOrOptions as any).pluginID) {
    throw `[Translate for Zotero:api.translate] pluginID is required since 1.1.0-23. Please contact the plugin developer for more information.`;
  }

  if (isDeprecatedCall) {
    Zotero.warn(
      new Error(
        "[Translate for Zotero:api.translate] This call is deprecated. Please use `translate(raw, options)` instead.",
      ),
    );
  }

  if (typeof service === "string") {
    currentService = service;
  } else if (Array.isArray(service)) {
    currentService = service[0];
    candidateServices = service.slice(1);
  } else {
    currentService = getPref("translateSource") as string;
  }

  const data: TranslateTask = {
    id: `${Zotero.Utilities.randomString()}-${new Date().getTime()}`,
    type: "custom",
    raw,
    result: "",
    audio: [],
    service: currentService,
    candidateServices,
    itemId: isDeprecatedCall ? -1 : (serviceOrOptions as any).itemID || -1,
    status: "waiting",
    extraTasks: [],
    silent: true,
    langfrom: isDeprecatedCall ? undefined : (serviceOrOptions as any).langfrom,
    langto: isDeprecatedCall ? undefined : (serviceOrOptions as any).langto,
    callerID: isDeprecatedCall
      ? "unknown caller with translate for zotero api"
      : (serviceOrOptions as any).pluginID,
  };
  await addon.data.translate.services.runTranslationTask(data, {
    noDisplay: true,
  });
  return data;
}

/**
 * Get a temporary refresh handler.
 * This handler will refresh the reader popup and item pane section.
 * This handler is temporary and will be invalid after another call.
 * @returns A temporary refresh handler.
 */
function getTemporaryRefreshHandler(options?: { task?: TranslateTask }) {
  const translateTask = options?.task;
  if (translateTask && translateTask.type !== "text") {
    return () => {};
  }
  const newTick = `${Zotero.Utilities.randomString()}-${Date.now()}`;
  addon.data.translate.refreshTick = newTick;
  return () => {
    if (addon.data.translate.refreshTick === newTick) {
      addon.hooks.onReaderPopupRefresh();
      addon.hooks.onReaderTabPanelRefresh();
    }
  };
}

/**
 * Get all available services.
 * @returns Array of services.
 */
function getServices() {
  return addon.data.translate.services
    .getAllServices()
    .map((service) => Object.assign({}, service));
}

/**
 * Get version of the plugin.
 * @returns Version of the plugin.
 */
function getVersion() {
  return version;
}

export default {
  translate,
  getServices,
  getVersion,
  getTemporaryRefreshHandler,
};


================================================
FILE: src/elements/base.ts
================================================
import { config } from "../../package.json";

export class PluginCEBase extends XULElementBase {
  _addon!: typeof addon;
  useShadowRoot = false;

  connectedCallback(): void {
    // @ts-ignore - Plugin instance is not typed
    this._addon = Zotero[config.addonInstance];
    Zotero.UIProperties.registerRoot(this);
    if (!this.useShadowRoot) {
      super.connectedCallback();
      return;
    }
    this.attachShadow({ mode: "open" });
    // Following the connectedCallback from XULElementBase
    let content: Node = this.content;
    if (content) {
      content = document.importNode(content, true);
      this.shadowRoot?.append(content);
    }

    MozXULElement.insertFTLIfNeeded("branding/brand.ftl");
    MozXULElement.insertFTLIfNeeded("zotero.ftl");
    if (document.l10n && this.shadowRoot) {
      document.l10n.connectRoot(this.shadowRoot);
    }

    window.addEventListener("unload", this._handleWindowUnload);

    this.initialized = true;
    this.init();
  }

  _wrapID(key: string) {
    if (key.startsWith(config.addonRef)) {
      return key;
    }
    return `${config.addonRef}-${key}`;
  }

  _unwrapID(id: string) {
    if (id.startsWith(config.addonRef)) {
      return id.slice(config.addonRef.length + 1);
    }
    return id;
  }

  _queryID(key: string) {
    const selector = `#${this._wrapID(key)}`;
    return (this.querySelector(selector) ||
      this.shadowRoot?.querySelector(selector)) as
      | XUL.Element
      | HTMLElement
      | null;
  }

  _parseContentID(dom: DocumentFragment) {
    dom.querySelectorAll("*[id]").forEach((elem) => {
      elem.id = this._wrapID(elem.id);
    });
    dom.querySelectorAll("*[data-l10n-id]").forEach((elem) => {
      elem.setAttribute(
        "data-l10n-id",
        this._wrapID(elem.getAttribute("data-l10n-id")!),
      );
    });
    return dom;
  }
}


================================================
FILE: src/elements/mathTextbox.ts
================================================
import { config } from "../../package.json";
import { renderMathInText, containsMath } from "../utils/mathRenderer";
import { getPref } from "../utils/prefs";

export class MathTextboxElement extends XULElementBase {
  private _textbox: XULTextBoxElement | null = null;
  private _overlay: HTMLElement | null = null;
  private _value: string = "";

  get content() {
    return MozXULElement.parseXULToFragment(`
      <editable-text id="inner-textbox" multiline="true" />
      <linkset>
        <html:link
          rel="stylesheet"
          href="chrome://${config.addonRef}/content/styles/mathTextbox.css"
        ></html:link>
        <html:link
          rel="stylesheet"
          href="chrome://${config.addonRef}/content/styles/katex.min.css"
        ></html:link>
      </linkset>
    `);
  }

  connectedCallback(): void {
    super.connectedCallback();
    this.init();
  }

  init(): void {
    this._textbox = this.querySelector("#inner-textbox") as XULTextBoxElement;
    if (!this._textbox) return;
    this._textbox.addEventListener("input", this._onInput);
    this._textbox.addEventListener("focus", this._onFocus);
    this._textbox.addEventListener("blur", this._onBlur);
  }

  set value(v: string) {
    this._value = v ?? "";
    if (this._textbox) this._textbox.value = this._value;
    this._updateOverlay();
  }
  get value() {
    return this._textbox?.value ?? this._value;
  }

  set placeholder(v: string) {
    if (this._textbox) this._textbox.placeholder = v;
  }

  focus(): void {
    this._textbox?.focus();
  }

  private _onInput = (e: Event) => {
    const val = (e.target as HTMLTextAreaElement).value;
    this._value = val;
    // do not redispatch input; bubble from inner editable-text already reaches panel listener
  };

  private _onFocus = () => {
    this._hideOverlay();
  };

  private _onBlur = () => {
    this._updateOverlay();
  };

  private _updateOverlay(): void {
    // Respect user preference gate
    const enabled = (getPref("enableMathRendering") as boolean) === true;
    if (!enabled || !this._value || !containsMath(this._value)) {
      this._hideOverlay();
      return;
    }
    this._showOverlay();
  }

  private _showOverlay(): void {
    if (this._overlay) this._overlay.remove();
    const HTML_NS = "http://www.w3.org/1999/xhtml";
    const overlay = document.createElementNS(
      HTML_NS,
      "div",
    ) as unknown as HTMLElement;
    overlay.className = "math-overlay";
    overlay.innerHTML = renderMathInText(document, this._value);
    overlay.addEventListener("click", () => {
      this._hideOverlay();
      this._textbox?.focus();
    });
    this._overlay = overlay;
    this.appendChild(overlay);
    this.toggleAttribute("overlay-visible", true);
  }

  private _hideOverlay(): void {
    if (this._overlay) {
      this._overlay.remove();
      this._overlay = null;
    }
    this.toggleAttribute("overlay-visible", false);
  }

  destroy(): void {
    this._hideOverlay();
    if (this._textbox) {
      this._textbox.removeEventListener("input", this._onInput);
      this._textbox.removeEventListener("focus", this._onFocus);
      this._textbox.removeEventListener("blur", this._onBlur);
    }
  }
}


================================================
FILE: src/elements/panel.ts
================================================
import { config } from "../../package.json";
import { PluginCEBase } from "./base";
import { getPref, setPref } from "../utils/prefs";
import { LANG_CODE } from "../utils/config";
import {
  addTranslateTask,
  autoDetectLanguage,
  getLastTranslateTask,
  putTranslateTaskAtHead,
} from "../utils/task";
import type { TranslationServices } from "../modules/services";

//@ts-expect-error addon instance not typed
const services = Zotero[config.addonInstance].data.translate
  .services as TranslationServices;

export class TranslatorPanel extends PluginCEBase {
  _item: Zotero.Item | null = null;

  _taskID = "";

  get item() {
    return this._item;
  }

  set item(val) {
    this._item = val;
  }

  get content() {
    return this._parseContentID(
      MozXULElement.parseXULToFragment(`
<linkset>
  <html:link rel="localization" href="${config.addonRef}-panel.ftl" />
  <html:link
    rel="stylesheet"
    href="chrome://${config.addonRef}/content/styles/panel.css"
  ></html:link>
</linkset>
<hbox id="engine" align="center">
  <menulist id="services" native="true">
    <menupopup>
      ${services
        .getAllServicesWithType("sentence")
        .map((service) => {
          const customName = services.getServiceNameByID(service.id);
          return `<menuitem label="${customName}" value="${service.id}" />`;
        })
        .join("\n")}
    </menupopup>
  </menulist>
  <button id="translate" data-l10n-id="translate" />
</hbox>
<hbox id="language" align="center">
  <menulist id="langfrom" class="lang-menulist" native="true">
    <menupopup>
      ${LANG_CODE.map((lang) => `<menuitem label="${lang.name}" value="${lang.code}" />`).join("\n")}
    </menupopup>
  </menulist>
  <toolbarbutton id="swap-language" class="icon-button" data-l10n-id="swapLanguage" />
  <menulist id="langto" class="lang-menulist" native="true">
    <menupopup>
      ${LANG_CODE.map((lang) => `<menuitem label="${lang.name}" value="${lang.code}" />`).join("\n")}
    </menupopup>
  </menulist>
</hbox>
<html:div class="separator"></html:div>
<html:div id="text-container" class="editor-container">
  ${
    (getPref("enableMathRendering") as boolean)
      ? `<math-textbox id="raw-text"></math-textbox>`
      : `<editable-text id="raw-text" multiline="true" />`
  }
  <html:div id="resizer" class="draggable-container">
    <html:div class="separator"></html:div>
  </html:div>
  ${
    (getPref("enableMathRendering") as boolean)
      ? `<math-textbox id="result-text"></math-textbox>`
      : `<editable-text id="result-text" multiline="true" />`
  }
</html:div>
<html:div class="separator"></html:div>
<html:div class="options-container">
  <html:div id="auto-container" class="options-grid">
    <html:label class="options-label" data-l10n-id="auto" />
    <html:div class="options-content">
      <checkbox id="auto-trans-selection" native="true" data-l10n-id="autoTranslateSelection" />
      <checkbox id="auto-trans-annotation" native="true" data-l10n-id="autoTranslateAnnotation" />
    </html:div>
  </html:div>
  <html:div id="concat-container" class="options-grid">
    <html:label class="options-label" data-l10n-id="selection" />
    <html:div class="options-content">
      <checkbox id="concat" native="true" data-l10n-id="enableConcat" />
      <button id="clear-concat" data-l10n-id="clearConcat" />
    </html:div>
  </html:div>
  <html:div id="copy-container" class="options-grid" >
    <html:label class="options-label" data-l10n-id="copy" />
    <html:div class="options-content">
      <button id="copy-raw" data-l10n-id="copyRaw" />
      <button id="copy-result" data-l10n-id="copyResult" />
      <button id="copy-both" data-l10n-id="copyBoth" />
    </html:div>
  </html:div>
</html:div>
`),
    );
  }

  init(): void {
    // Services
    this._queryID("services")?.addEventListener("command", (e) => {
      const newService = (e.target as XUL.MenuList).value;
      setPref("translateSource", newService);
      this._addon.hooks.onReaderTabPanelRefresh();
      const data = getLastTranslateTask();
      if (!data) {
        return;
      }
      data.service = newService;
      this._addon.hooks.onTranslate(undefined, {
        noCheckZoteroItemLanguage: true,
      });
    });

    // Translate
    this._queryID("translate")?.addEventListener("command", () => {
      if (!getLastTranslateTask()) {
        addTranslateTask(
          (
            this._queryID(
              getPref("rawResultOrder") ? "result-text" : "raw-text",
            ) as HTMLTextAreaElement
          )?.value,
        );
      }
      this._addon.hooks.onTranslate(undefined, {
        noCheckZoteroItemLanguage: true,
        noCache: true,
      });
    });

    // Language change
    this._queryID("langfrom")?.addEventListener("command", (e) => {
      const newValue = (e.target as XUL.MenuList).value;
      setPref("sourceLanguage", newValue);
      const itemID = this.item?.id;
      if (itemID) {
        this._addon.data.translate.cachedSourceLanguage[Number(itemID)] =
          newValue;
      }
      this._addon.hooks.onReaderTabPanelRefresh();
    });

    this._queryID("swap-language")?.addEventListener("command", () => {
      const langfrom = getPref("sourceLanguage") as string;
      const langto = getPref("targetLanguage") as string;
      setPref("targetLanguage", langfrom);
      setPref("sourceLanguage", langto);
      this._addon.hooks.onReaderTabPanelRefresh();
    });

    this._queryID("langto")?.addEventListener("command", (e) => {
      setPref("targetLanguage", (e.target as XUL.MenuList).value);
      this._addon.hooks.onReaderTabPanelRefresh();
    });

    // Text change
    this._queryID("raw-text")?.addEventListener("input", (e) => {
      let task = getLastTranslateTask({
        id: this._taskID,
      });
      if (!task) {
        task = addTranslateTask(
          (e.target as HTMLTextAreaElement).value,
          this.item?.id,
          "text",
        );
        if (task) this._taskID = task.id;
      }
      if (!task) {
        return;
      }
      const reverseRawResult = getPref("rawResultOrder");
      if (!reverseRawResult) {
        task.raw = (e.target as HTMLTextAreaElement).value;
      } else {
        task.result = (e.target as HTMLTextAreaElement).value;
      }
      putTranslateTaskAtHead(task.id);
    });

    this._queryID("result-text")?.addEventListener("input", (e) => {
      let task = getLastTranslateTask({
        id: this._taskID,
      });
      if (!task) {
        task = addTranslateTask(
          (e.target as HTMLTextAreaElement).value,
          this.item?.id,
          "text",
        );
        if (task) this._taskID = task.id;
      }
      if (!task) {
        return;
      }
      const reverseRawResult = getPref("rawResultOrder");
      if (!reverseRawResult) {
        task.result = (e.target as HTMLTextAreaElement).value;
      } else {
        task.raw = (e.target as HTMLTextAreaElement).value;
      }
      putTranslateTaskAtHead(task.id);
    });

    // Auto translate
    this._queryID("auto-trans-selection")?.addEventListener("command", (e) => {
      setPref("enableAuto", (e.target as XUL.Checkbox).checked);
      this._addon.hooks.onReaderTabPanelRefresh();
    });

    this._queryID("auto-trans-annotation")?.addEventListener("command", (e) => {
      setPref("enableComment", (e.target as XUL.Checkbox).checked);
      this._addon.hooks.onReaderTabPanelRefresh();
    });

    // Concat
    this._queryID("concat")?.addEventListener("command", (e) => {
      this._addon.data.translate.concatCheckbox = (
        e.target as XUL.Checkbox
      ).checked;
      this._addon.hooks.onReaderTabPanelRefresh();
    });

    this._queryID("clear-concat")?.addEventListener("command", () => {
      const task = getLastTranslateTask();
      if (task) {
        task.raw = "";
        task.result = "";
        task.extraTasks.forEach((t) => {
          t.result = "";
        });
        this._addon.hooks.onReaderTabPanelRefresh();
      }
    });

    // Copy
    this._queryID("copy-raw")?.addEventListener("command", () => {
      const task = getLastTranslateTask({
        id: this._taskID,
      });
      if (!task) {
        return;
      }
      new this._addon.data.ztoolkit.Clipboard()
        .addText(task.raw, "text/plain")
        .copy();
    });

    this._queryID("copy-result")?.addEventListener("command", () => {
      const task = getLastTranslateTask({
        id: this._taskID,
      });
      if (!task) {
        return;
      }
      new this._addon.data.ztoolkit.Clipboard()
        .addText(task.result, "text/plain")
        .copy();
    });

    this._queryID("copy-both")?.addEventListener("command", () => {
      const task = getLastTranslateTask({
        id: this._taskID,
      });
      if (!task) {
        return;
      }
      new this._addon.data.ztoolkit.Clipboard()
        .addText(`${task.raw}\n----\n${task.result}`, "text/plain")
        .copy();
    });

    // Draggable text area
    const resizer = this._queryID("resizer") as HTMLElement;
    const container = this._queryID("text-container") as HTMLElement;
    const rawArea = this._queryID("raw-text") as HTMLElement;
    const resultArea = this._queryID("result-text") as HTMLElement;

    rawArea.style.flex = `${getPref("customRawRatio")} 1 0%`;
    resultArea.style.flex = `${getPref("customResultRatio")} 1 0%`;

    let isDragging = false;
    let containerRect: DOMRect;
    resizer?.addEventListener("mousedown", (e: MouseEvent) => {
      if (e.button !== 0) {
        return;
      }
      isDragging = true;
      e.preventDefault();
      containerRect = container.getBoundingClientRect();
      window.document.addEventListener("mousemove", doDrag);
      window.document.addEventListener("mouseup", (e: MouseEvent) => {
        isDragging = false;
        window.document.removeEventListener("mousemove", doDrag);
      });
    });

    function doDrag(e: MouseEvent) {
      if (!isDragging) {
        return;
      }
      const newRawHeight = e.clientY - containerRect.top;
      const maxRawHeight = containerRect.height - 100 - 13;
      if (newRawHeight >= 100 && newRawHeight <= maxRawHeight) {
        const newResultHeight = containerRect.height - newRawHeight - 13;
        const newRawRatio = (
          newRawHeight / Math.min(newRawHeight, newResultHeight)
        ).toFixed(3);
        const newResultRatio = (
          newResultHeight / Math.min(newRawHeight, newResultHeight)
        ).toFixed(3);
        rawArea.style.flex = `${newRawRatio} 1 0%`;
        resultArea.style.flex = `${newResultRatio} 1 0%`;
        setPref("customRawRatio", newRawRatio);
        setPref("customResultRatio", newResultRatio);
      }
    }

    resizer?.addEventListener("dblclick", (e: MouseEvent) => {
      if (e.button !== 0) {
        return;
      }
      e.preventDefault();
      rawArea.style.flex = "1 1 0%";
      resultArea.style.flex = "1 1 0%";
      setPref("customRawRatio", "1");
      setPref("customResultRatio", "1");
    });
  }

  destroy(): void {}

  /**
   * Filter unconfigured services from the dropdown menu.
   * Hides services that require API keys but haven't been configured.
   */
  _filterUnconfiguredServices() {
    const menuPopup = this._queryID("services")?.querySelector("menupopup");
    if (!menuPopup) return;

    const menuItems = menuPopup.querySelectorAll("menuitem");
    const hideUnconfigured = getPref("hideUnconfiguredServices") as boolean;
    const unconfiguredIds = hideUnconfigured
      ? services.getUnconfiguredServiceIds()
      : null;

    menuItems.forEach((item) => {
      const serviceId = item.getAttribute("value");
      (item as HTMLElement).hidden = !!unconfiguredIds?.has(serviceId || "");
    });
  }

  render() {
    const updateHidden = (type: string, pref: string) => {
      const elem = this._queryID(type) as XUL.Box;
      const hidden = !getPref(pref) as boolean;
      elem.hidden = hidden;
      if (
        elem.nextElementSibling?.classList.contains("separator") ||
        elem.nextElementSibling?.classList.contains("draggable-container")
      ) {
        (elem.nextElementSibling as HTMLDivElement).hidden = hidden;
      }
    };
    const setCheckBox = (type: string, checked: boolean) => {
      const elem = this._queryID(type) as XUL.Checkbox;
      elem.checked = checked;
    };
    const setValue = (type: string, value: string) => {
      const elem = this._queryID(type) as XUL.Textbox;
      elem.value = value;
    };
    const setPalceHolder = (type: string, placeholder: string) => {
      const elem = this._queryID(type) as XUL.Textbox;
      elem.placeholder = placeholder;
    };
    const setTextBoxStyle = (type: string) => {
      const elem = this._queryID(type) as XUL.Textbox;
      elem.style.fontSize = `${getPref("fontSize")}px`;
      elem.style.lineHeight = getPref("lineHeight") as string;
    };

    updateHidden("engine", "showSidebarEngine");
    updateHidden("language", "showSidebarLanguage");
    updateHidden("raw-text", "showSidebarRaw");
    updateHidden("auto-container", "showSidebarSettings");
    updateHidden("concat-container", "showSidebarConcat");
    updateHidden("copy-container", "showSidebarCopy");

    // Filter unconfigured services from dropdown if preference is enabled
    this._filterUnconfiguredServices();

    setValue("services", getPref("translateSource") as string);

    const { fromLanguage, toLanguage } = autoDetectLanguage(this.item);
    setValue("langfrom", fromLanguage);
    setValue("langto", toLanguage);

    setCheckBox("auto-trans-selection", getPref("enableAuto") as boolean);
    setCheckBox("auto-trans-annotation", getPref("enableComment") as boolean);
    setCheckBox("concat", this._addon.data.translate.concatCheckbox);

    setTextBoxStyle("raw-text");
    setTextBoxStyle("result-text");
    const reverseRawResult = getPref("rawResultOrder");
    setPalceHolder(
      "raw-text",
      reverseRawResult ? "" : "Select or type to translate",
    );
    setPalceHolder(
      "result-text",
      reverseRawResult ? "Select or type to translate" : "",
    );

    const lastTask = getLastTranslateTask();
    if (!lastTask) {
      return;
    }
    // For manually update translation task
    this._taskID = lastTask.id;

    if (
      lastTask.type === "text" ||
      (lastTask.raw === "" && lastTask.result === "")
    ) {
      setValue("raw-text", reverseRawResult ? lastTask.result : lastTask.raw);
      setValue(
        "result-text",
        reverseRawResult ? lastTask.raw : lastTask.result,
      );
    }
  }
}


================================================
FILE: src/extras/customElements.ts
================================================
import { TranslatorPanel } from "../elements/panel";
import { MathTextboxElement } from "../elements/mathTextbox";

const elements = {
  "translator-plugin-panel": TranslatorPanel,
  "math-textbox": MathTextboxElement,
} as unknown as Record<string, CustomElementConstructor>;

for (const [key, constructor] of Object.entries(elements)) {
  if (!customElements.get(key)) {
    customElements.define(key, constructor);
  }
}


================================================
FILE: src/hooks.ts
================================================
import { config } from "../package.json";
import { initLocale } from "./utils/locale";
import {
  registerPrefsScripts,
  registerPrefsWindow,
} from "./modules/preferenceWindow";
import {
  registerReaderTabPanel,
  updateReaderTabPanels,
} from "./modules/tabpanel";
import { buildReaderPopup, updateReaderPopup } from "./modules/popup";
import { registerNotify } from "./modules/notify";
import { registerReaderInitializer } from "./modules/reader";
import { getPref } from "./utils/prefs";
import {
  addTranslateAnnotationTask,
  addTranslateTask,
  addTranslateTitleTask,
  getLastTranslateTask,
  TranslateTask,
} from "./utils/task";
import { setDefaultPrefSettings } from "./modules/defaultPrefs";
import Addon from "./addon";
import { registerMenu } from "./modules/menu";
import { registerExtraColumns } from "./modules/itemTree";
import { registerShortcuts } from "./modules/shortcuts";
import { registerItemPaneInfoRows } from "./modules/infoBox";
import { registerPrompt } from "./modules/prompt";
import { registerCustomFields } from "./modules/fields";

async function onStartup() {
  await Promise.all([
    Zotero.initializationPromise,
    Zotero.unlockPromise,
    Zotero.uiReadyPromise,
  ]);

  // TODO: Remove this after zotero#3387 is merged
  if (__env__ === "development") {
    // Keep in sync with the scripts/startup.mjs
    const loadDevToolWhen = `Plugin ${config.addonID} startup`;
    ztoolkit.log(loadDevToolWhen);
  }

  initLocale();

  setDefaultPrefSettings();

  registerCustomFields();

  registerReaderInitializer();

  registerShortcuts();

  registerNotify(["item"]);

  registerPrefsWindow();

  registerExtraColumns();

  registerItemPaneInfoRows();

  registerReaderTabPanel();

  await Promise.all(
    Zotero.getMainWindows().map((win) => onMainWindowLoad(win)),
  );
}

async function onMainWindowLoad(win: Window): Promise<void> {
  await new Promise((resolve) => {
    if (win.document.readyState !== "complete") {
      win.document.addEventListener("readystatechange", () => {
        if (win.document.readyState === "complete") {
          resolve(void 0);
        }
      });
    }
    resolve(void 0);
  });

  await Promise.all([
    Zotero.initializationPromise,
    Zotero.unlockPromise,
    Zotero.uiReadyPromise,
  ]);

  Services.scriptloader.loadSubScript(
    `chrome://${config.addonRef}/content/scripts/customElements.js`,
    win,
  );

  (win as any).MozXULElement.insertFTLIfNeeded(
    `${config.addonRef}-mainWindow.ftl`,
  );

  registerMenu();
  registerPrompt();

  win.document.addEventListener("focusout", (ev) => {
    if (ev.target !== win.document) {
      return;
    }
    addon.data.translate.concatKey = false;
  });
}

async function onMainWindowUnload(win: Window): Promise<void> {
  win.document
    .querySelector(`[href="${config.addonRef}-mainWindow.ftl"]`)
    ?.remove();
}

function onShutdown(): void {
  ztoolkit.unregisterAll();
  Zotero.getMainWindows().forEach((win) => {
    onMainWindowUnload(win);
  });
  // Remove addon object
  addon.data.alive = false;
  // @ts-ignore - Plugin instance is not typed
  delete Zotero[config.addonInstance];
}

/**
 * This function is just an example of dispatcher for Notify events.
 * Any operations should be placed in a function to keep this function clear.
 */
function onNotify(
  event: string,
  type: string,
  ids: Array<string | number>,
  extraData: { [key: string]: any },
) {
  if (event === "add" && type === "item") {
    if (
      !getPref("enableAnnotationFromSyncTranslation") &&
      extraData?.skipAutoSync
    )
      return;
    const annotationItems = Zotero.Items.get(ids as number[]).filter((item) =>
      item.isAnnotation(),
    );
    if (annotationItems.length === 0) {
      return;
    }
    if (getPref("enableComment")) {
      addon.hooks.onTranslateInBatch(
        annotationItems
          .map((item) => addTranslateAnnotationTask(item.id))
          .filter((task) => task) as TranslateTask[],
        { noDisplay: true },
      );
    }
  } else if (type === "tab" && ["select", "add", "close"].includes(event)) {
    addon.data.translate.concatKey = false;
  } else {
    return;
  }
}

function onPrefsLoad(event: Event) {
  registerPrefsScripts((event.target as any).ownerGlobal);
}

function onShortcuts(type: string) {
  switch (type) {
    case "library":
      {
        addon.hooks.onTranslateInBatch(
          Zotero.getActiveZoteroPane()
            .getSelectedItems(true)
            .map((id) => addTranslateTitleTask(id, true))
            .filter((task) => task) as TranslateTask[],
          { noDisplay: true, noCache: true },
        );
      }
      break;
    case "reader":
      {
        addon.hooks.onTranslate(undefined, {
          noCheckZoteroItemLanguage: true,
          noCache: true,
        });
      }
      break;
    default:
      break;
  }
}

async function onTranslate(): Promise<void>;
async function onTranslate(
  options: Parameters<
    Addon["data"]["translate"]["services"]["runTranslationTask"]
  >["1"],
): Promise<void>;
async function onTranslate(
  task: TranslateTask | undefined,
  options?: Parameters<
    Addon["data"]["translate"]["services"]["runTranslationTask"]
  >["1"],
): Promise<void>;
async function onTranslate(...data: any) {
  let task = undefined;
  let options = {};
  if (data.length === 1) {
    if (data[0].raw) {
      task = data[0];
    } else {
      options = data[0];
    }
  } else if (data.length === 2) {
    task = data[0];
    options = data[1];
  }
  await addon.data.translate.services.runTranslationTask(task, options);
}

async function onTranslateInBatch(
  tasks: TranslateTask[],
  options: Parameters<
    Addon["data"]["translate"]["services"]["runTranslationTask"]
  >["1"] = {},
) {
  for (const task of tasks) {
    await addon.hooks.onTranslate(task, options);
    await Zotero.Promise.delay(addon.data.translate.batchTaskDelay);
  }
}

function onReaderPopupShow(
  event: _ZoteroTypes.Reader.EventParams<"renderTextSelectionPopup">,
) {
  const selection = addon.data.translate.selectedText;
  const task = getLastTranslateTask();
  if (task?.raw === selection) {
    buildReaderPopup(event);
    addon.hooks.onReaderPopupRefresh();
    return;
  }
  addTranslateTask(selection, event.reader.itemID);
  buildReaderPopup(event);
  addon.hooks.onReaderPopupRefresh();
  if (getPref("enableAuto")) {
    addon.hooks.onTranslate();
  }
}

function onReaderPopupRefresh() {
  updateReaderPopup();
}

function onReaderTabPanelRefresh() {
  updateReaderTabPanels();
}

// Add your hooks here. For element click, etc.
// Keep in mind hooks only do dispatch. Don't add code that does real jobs in hooks.
// Otherwise the code would be hard to read and maintain.

export default {
  onStartup,
  onMainWindowLoad,
  onMainWindowUnload,
  onShutdown,
  onNotify,
  onPrefsLoad,
  onShortcuts,
  onTranslate,
  onTranslateInBatch,
  onReaderPopupShow,
  onReaderPopupRefresh,
  onReaderTabPanelRefresh,
};


================================================
FILE: src/index.ts
================================================
import { BasicTool } from "zotero-plugin-toolkit";
import Addon from "./addon";
import { config } from "../package.json";

const basicTool = new BasicTool();

// @ts-ignore - Plugin instance is not typed
if (!basicTool.getGlobal("Zotero")[config.addonInstance]) {
  // Set global variables
  _globalThis.Zotero = basicTool.getGlobal("Zotero");
  defineGlobal("crypto");
  defineGlobal("TextEncoder");
  _globalThis.addon = new Addon();
  defineGlobal("ztoolkit", () => {
    return _globalThis.addon.data.ztoolkit;
  });
  // @ts-ignore - Plugin instance is not typed
  Zotero[config.addonInstance] = addon;
  // Trigger addon hook for initialization
  addon.hooks.onStartup();
}

function defineGlobal(name: Parameters<BasicTool["getGlobal"]>[0]): void;
function defineGlobal(name: string, getter: () => any): void;
function defineGlobal(name: string, getter?: () => any) {
  Object.defineProperty(_globalThis, name, {
    get() {
      return getter ? getter() : basicTool.getGlobal(name);
    },
  });
}


================================================
FILE: src/modules/defaultPrefs.ts
================================================
import { clearPref, getPref, getPrefJSON, setPref } from "../utils/prefs";
import { getServiceSecret, setServiceSecret } from "../utils/secret";
import { services } from "./services";

export function setDefaultPrefSettings() {
  const isZhCN = Zotero.locale === "zh-CN";
  const servicesIds = services.getAllServices().map((service) => service.id);
  if (!servicesIds.includes((getPref("translateSource") as string) || "")) {
    // Google Translate is not accessible in China mainland
    setPref("translateSource", isZhCN ? "cnki" : "googleapi");
  }
  if (!servicesIds.includes((getPref("dictSource") as string) || "")) {
    setPref("dictSource", isZhCN ? "bingdict" : "freedictionaryapi");
  }

  if (!getPref("targetLanguage")) {
    setPref("targetLanguage", Zotero.locale);
  }

  const secrets = getPrefJSON("secretObj");
  for (const serviceId of servicesIds) {
    if (typeof secrets[serviceId] === "undefined") {
      secrets[serviceId] =
        services.getServiceById(serviceId)!.defaultSecret || "";
    }
  }
  setPref("secretObj", JSON.stringify(secrets));

  // From v2.2.22, migrate previous settings in secrets to prefs
  const deeplxApiSecret = getServiceSecret("deeplcustom");
  if (deeplxApiSecret && !getPref("deeplcustom.endpoint")) {
    setPref("deeplcustom.endpoint", deeplxApiSecret);
  }

  if (isZhCN && !getPref("disabledLanguages")) {
    setPref("disabledLanguages", "zh,zh-CN,中文;");
  }

  const extraServices = getPref("extraEngines") as string;
  if (extraServices.startsWith(",")) {
    setPref("extraEngines", extraServices.slice(1));
  }

  // For NiuTrans login. niutransLog is deprecated.
  const niutransApiKey = getPref("niutransApikey") as string;
  if (niutransApiKey) {
    setServiceSecret("niutranspro", niutransApiKey);
    clearPref("niutransApikey");
  }
  if (getPref("translateSource") === "niutransLog") {
    setPref("translateSource", "niutranspro");
  }
  try {
    const oldDict = JSON.parse(
      (getPref("niutransDictLibList") as string) || "{}",
    );
    if (oldDict?.dlist) {
      setPref("niutransDictLibList", JSON.stringify(oldDict.dlist));
    } else {
      setPref("niutransDictLibList", "[]");
    }
    const oldMemory = JSON.parse(
      (getPref("niutransMemoryLibList") as string) || "{}",
    );
    if (oldMemory?.mlist) {
      setPref("niutransMemoryLibList", JSON.stringify(oldMemory?.mlist));
    } else {
      setPref("niutransMemoryLibList", "[]");
    }
  } catch (e) {
    setPref("niutransDictLibList", "[]");
    setPref("niutransMemoryLibList", "[]");
  }

  // For xftrans, xftrans.useNiutrans Pref is deprecated.
  const useNiutrans = getPref("xftrans.useNiutrans") as boolean;
  if (useNiutrans) {
    setPref("xftrans.engine", "niutrans");
  }
  clearPref("xftrans.useNiutrans");

  // From v2.3.1 to v2.3.7, Pref customGPTx.temperature has been set as number type
  // Change the type from number to string to be compatible with floating-point values
  const gptKeys = ["customGPT1", "customGPT2", "customGPT3"];

  gptKeys.forEach((key) => {
    const prefKey = `${key}.temperature`;
    const value = getPref(prefKey);

    if (value !== undefined && typeof value === "number") {
      clearPref(prefKey);
      setPref(prefKey, String(value));
    }
  });

  if (!getPref("annotationTagContent")) {
    setPref("annotationTagContent", isZhCN ? "翻译" : "Translation");
  }
}


================================================
FILE: src/modules/fields.ts
================================================
export { registerCustomFields };

function registerCustomFields() {
  ztoolkit.FieldHook.register(
    "getField",
    "titleTranslation",
    (
      field: string,
      unformatted: boolean,
      includeBaseMapped: boolean,
      item: Zotero.Item,
      // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
      original: Function,
    ) => {
      return ztoolkit.ExtraField.getExtraField(item, field) || "";
    },
  );

  ztoolkit.FieldHook.register(
    "getField",
    "abstractTranslation",
    (
      field: string,
      unformatted: boolean,
      includeBaseMapped: boolean,
      item: Zotero.Item,
      // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
      original: Function,
    ) => {
      return ztoolkit.ExtraField.getExtraField(item, field) || "";
    },
  );
}


================================================
FILE: src/modules/infoBox.ts
================================================
import { getPref } from "../utils/prefs";

export { registerItemPaneInfoRows };

function registerItemPaneInfoRows() {
  if (!Zotero.ItemPaneManager.registerInfoRow) {
    return;
  }

  if (getPref("showItemBoxTitleTranslation") !== false) {
    Zotero.ItemPaneManager.registerInfoRow({
      rowID: "titleTranslation",
      pluginID: addon.data.config.addonID,
      label: {
        l10nID: `${addon.data.config.addonRef}-field-titleTranslation`,
      },
      onGetData: (options) => {
        return (
          ztoolkit.ExtraField.getExtraField(options.item, "titleTranslation") ||
          ""
        );
      },
      onSetData: (options) => {
        ztoolkit.ExtraField.setExtraField(
          options.item,
          "titleTranslation",
          options.value,
        );
      },
      position: "start",
      editable: true,
    });
  }

  if (getPref("showItemBoxAbstractTranslation") !== false) {
    Zotero.ItemPaneManager.registerInfoRow({
      rowID: "abstractTranslation",
      pluginID: addon.data.config.addonID,
      label: {
        l10nID: `${addon.data.config.addonRef}-field-abstractTranslation`,
      },
      onGetData: (options) => {
        return (
          ztoolkit.ExtraField.getExtraField(
            options.item,
            "abstractTranslation",
          ) || ""
        );
      },
      onSetData: (options) => {
        ztoolkit.ExtraField.setExtraField(
          options.item,
          "abstractTranslation",
          options.value,
        );
      },
      position: "afterCreators",
      editable: true,
      multiline: true,
    });
  }
}


================================================
FILE: src/modules/itemTree.ts
================================================
import { config } from "../../package.json";
import { getString } from "../utils/locale";

export function registerExtraColumns() {
  // TEMP: Remove after Zotero 7.0.10
  const registerColumn =
    Zotero.ItemTreeManager.registerColumn ||
    Zotero.ItemTreeManager.registerColumns;
  registerColumn.apply(Zotero.ItemTreeManager, [
    {
      dataKey: "titleTranslation",
      label: getString("field-titleTranslation"),
      dataProvider: (item, dataKey) =>
        ztoolkit.ExtraField.getExtraField(item, "titleTranslation") || "",
      pluginID: config.addonID,
      zoteroPersist: ["width", "hidden", "sortDirection"],
    },
  ]);
}


================================================
FILE: src/modules/menu.ts
================================================
import { config } from "../../package.json";
import { getPref } from "../utils/prefs";
import {
  addTranslateAbstractTask,
  addTranslateTitleTask,
  TranslateTask,
} from "../utils/task";

export function registerMenu() {
  const menuIcon = `chrome://${config.addonRef}/content/icons/favicon.png`;

  Zotero.MenuManager.registerMenu({
    menuID: `${config.addonRef}-translate-title`,
    pluginID: config.addonID,
    target: "main/library/item",
    menus: [
      {
        menuType: "menuitem",
        l10nID: `${config.addonRef}-itemmenu-translateTitle`,
        icon: menuIcon,
        onCommand: (event, context) => {
          if (!context.items?.length) {
            return;
          }
          addon.hooks.onTranslateInBatch(
            context.items
              .map((item) => addTranslateTitleTask(item.id, true))
              .filter((task) => task) as TranslateTask[],
            { noDisplay: true, noCache: true },
          );
        },
        onShowing: (event, context) => {
          context.setVisible(
            !!(
              getPref("showItemMenuTitleTranslation") &&
              context.items?.every((item) => item.isRegularItem())
            ),
          );
        },
      },
      {
        menuType: "menuitem",
        l10nID: `${config.addonRef}-itemmenu-translateAbstract`,
        icon: menuIcon,
        onCommand: (event, context) => {
          if (!context.items?.length) {
            return;
          }
          addon.hooks.onTranslateInBatch(
            context.items
              .map((item) => addTranslateAbstractTask(item.id, true))
              .filter((task) => task) as TranslateTask[],
            { noDisplay: true, noCache: true },
          );
        },
        onShowing: (event, context) => {
          context.setVisible(
            !!(
              getPref("showItemMenuTitleTranslation") &&
              context.items?.every((item) => item.isRegularItem())
            ),
          );
        },
      },
    ],
  });
}


================================================
FILE: src/modules/notify.ts
================================================
export function registerNotify(types: _ZoteroTypes.Notifier.Type[]) {
  const callback = {
    notify: async (...data: Parameters<_ZoteroTypes.Notifier.Notify>) => {
      if (!addon?.data.alive) {
        unregisterNotify(notifyID);
        return;
      }
      addon.hooks.onNotify(...data);
    },
  };

  // Register the callback in Zotero as an item observer
  const notifyID = Zotero.Notifier.registerObserver(callback, types);
}

function unregisterNotify(notifyID: string) {
  Zotero.Notifier.unregisterObserver(notifyID);
}


================================================
FILE: src/modules/popup.ts
================================================
import { SVGIcon } from "../utils/config";
import { config } from "../../package.json";
import { getString } from "../utils/locale";
import { getPref, setPref } from "../utils/prefs";
import { addTranslateTask, getLastTranslateTask } from "../utils/task";
import { slice } from "../utils/str";

export function updateReaderPopup() {
  const popup = addon.data.popup.currentPopup;
  if (!popup) {
    return;
  }
  const enablePopup = getPref("enablePopup");
  const hidePopupTextarea = getPref("enableHidePopupTextarea") as boolean;
  Array.from(popup.querySelectorAll(`.${config.addonRef}-readerpopup`)).forEach(
    (elem) => ((elem as HTMLElement).hidden = !enablePopup),
  );

  const idPrefix = popup?.getAttribute(`${config.addonRef}-prefix`);
  const makeId = (type: string) => `${idPrefix}-${type}`;
  const audiobox = popup?.querySelector(
    `#${makeId("audiobox")}`,
  ) as HTMLDivElement;
  const translateButton = popup?.querySelector(
    `#${makeId("translate")}`,
  ) as HTMLDivElement;
  const textarea = popup?.querySelector(
    `#${makeId("text")}`,
  ) as HTMLTextAreaElement;
  const addToNoteButton = popup?.querySelector(
    `#${makeId("addtonote")}`,
  ) as HTMLDivElement;

  const updateHidden = (elem: HTMLElement, hidden: boolean) => {
    if (hidden) {
      elem.style.display = "none";
    } else {
      elem.style.removeProperty("display");
    }
  };

  if (!enablePopup) {
    updateHidden(audiobox, true);
    updateHidden(translateButton, true);
    updateHidden(textarea, true);
    updateHidden(addToNoteButton, true);
    return;
  }
  const task = getLastTranslateTask({ type: "text" });
  if (!task) {
    return;
  }
  popup.setAttribute("translate-task-id", task.id);

  if (task.audio.length > 0 && getPref("showPlayBtn")) {
    audiobox.innerHTML = "";
    updateHidden(audiobox, false);
    ztoolkit.UI.appendElement(
      {
        tag: "fragment",
        children: task.audio.map((audioData) => ({
          tag: "button",
          namespace: "html",
          classList: ["toolbar-button", "wide-button"],
          attributes: {
            tabindex: "-1",
            title: audioData.text,
          },
          properties: {
            innerHTML: `🔊 ${audioData.text}`,
            onclick: () => {
              new (ztoolkit.getGlobal("Audio"))(audioData.url).play();
            },
          },
          styles: { whiteSpace: "nowrap", flexGrow: "1" },
        })),
      },
      audiobox,
    );
  }

  if (task.audio.length > 0 && getPref("showPlayBtn") && getPref("autoPlay")) {
    const firstAudio = task.audio[0];
    const audio = new (ztoolkit.getGlobal("Audio"))(firstAudio.url);
    audio.play();
  }

  const hideTranslateButton = task.status !== "waiting";
  updateHidden(translateButton, hideTranslateButton);

  switch (task.langto?.split("-")[0]) {
    case "ar":
    case "fa":
    case "he":
      textarea.style.direction = "rtl";
      break;
    default:
      textarea.style.direction = "ltr";
  }

  textarea.hidden = hidePopupTextarea || !hideTranslateButton;
  textarea.value = task.result || task.raw;
  textarea.style.fontSize = `${getPref("fontSize")}px`;
  textarea.style.lineHeight = `${
    Number(getPref("lineHeight")) * Number(getPref("fontSize"))
  }px`;

  const enableAddToNote = getPref("enableNote") as boolean;
  if (
    !Zotero.getMainWindow().ZoteroContextPane.activeEditor ||
    !enableAddToNote
  ) {
    updateHidden(addToNoteButton, true);
  }

  updatePopupSize(popup, textarea);
}

export function buildReaderPopup(
  event: _ZoteroTypes.Reader.EventParams<"renderTextSelectionPopup">,
) {
  const { reader, doc, append } = event;
  const annotation = event.params.annotation;
  const popup = doc.querySelector(".selection-popup") as HTMLDivElement;
  addon.data.popup.currentPopup = popup;
  popup.style.maxWidth = "none";
  popup.setAttribute(
    `${config.addonRef}-prefix`,
    `${config.addonRef}-${reader._instanceID}`,
  );

  const ZoteroContextPane = Zotero.getMainWindow().ZoteroContextPane;

  const colors = popup.querySelector(".colors") as HTMLDivElement;
  colors.style.width = "100%";
  colors.style.justifyContent = "space-evenly";

  const keepSize = getPref("keepPopupSize") as boolean;

  const makeId = (type: string) =>
    `${config.addonRef}-${reader._instanceID}-${type}`;

  const hidePopupTextarea = getPref("enableHidePopupTextarea") as boolean;
  append(
    ztoolkit.UI.createElement(doc, "fragment", {
      children: [
        {
          tag: "div",
          id: makeId("audiobox"),
          classList: [`${config.addonRef}-readerpopup`],
          styles: {
            display: "flex",
            width: "calc(100% - 4px)",
            marginLeft: "2px",
            justifyContent: "space-evenly",
          },
          ignoreIfExists: true,
        },
        {
          tag: "button",
          namespace: "html",
          id: makeId("translate"),
          classList: [
            "toolbar-button",
            "wide-button",
            `${config.addonRef}-readerpopup`,
          ],
          properties: {
            innerHTML: `${SVGIcon}${getString("readerpopup-translate-label")}`,
            hidden: getPref("enableAuto"),
          },
          listeners: [
            {
              type: "click",
              listener: (ev: Event) => {
                addon.hooks.onTranslate({
                  noCheckZoteroItemLanguage: true,
                  noCache: true,
                });
                const button = ev.target as HTMLDivElement;
                button.hidden = true;
                (
                  button.ownerDocument.querySelector(
                    `#${makeId("text")}`,
                  ) as HTMLTextAreaElement
                ).hidden = hidePopupTextarea;
              },
            },
          ],
          ignoreIfExists: true,
        },
        {
          tag: "textarea",
          id: makeId("text"),
          attributes: {
            rows: "3",
            columns: "10",
          },
          classList: [
            `${config.addonRef}-popup-textarea`,
            `${config.addonRef}-readerpopup`,
          ],
          styles: {
            fontSize: `${getPref("fontSize")}px`,
            fontFamily: "inherit",
            lineHeight: `${
              Number(getPref("lineHeight")) * Number(getPref("fontSize"))
            }px`,
            width: keepSize ? `${getPref("popupWidth")}px` : "-moz-available",
            // Minimum width to prevent the textarea from being smaller than the popup
            minWidth: "184px",
            height: `${Math.max(
              keepSize ? Number(getPref("popupHeight")) : 30,
            )}px`,
            marginInline: "2px",
            border: "none",
            background: "var(--color-sidepane)",
            borderRadius: "6px",
            padding: "5px",
          },
          properties: {
            onpointerup: (e: Event) => e.stopPropagation(),
            ondragstart: (e: Event) => e.stopPropagation(),
            spellcheck: false,
            value: addon.data.translate.selectedText,
          },
          ignoreIfExists: true,
          listeners: [
            {
              type: "mousedown",
              listener: (_ev) => {
                _ev.target?.addEventListener(
                  "mousemove",
                  onTextAreaResize as (ev: Event) => void,
                );
              },
            },
            {
              type: "mouseup",
              listener: (_ev) => {
                _ev.target?.removeEventListener(
                  "mousemove",
                  onTextAreaResize as (ev: Event) => void,
                );
              },
            },
            {
              type: "dblclick",
              listener: (_ev) => {
                const textarea = popup.querySelector(
                  `#${makeId("text")}`,
                ) as HTMLTextAreaElement;
                textarea.selectionStart = 0;
                textarea.selectionEnd = textarea.value.length;
                const text = textarea.value.slice(
                  textarea.selectionStart,
                  textarea.selectionEnd,
                );
                new ztoolkit.Clipboard().addText(text, "text/plain").copy();
                new ztoolkit.ProgressWindow("Copied to Clipboard")
                  .createLine({
                    text: slice(text, 50),
                    progress: 100,
                    type: "default",
                  })
                  .show();
              },
            },
          ],
        },
        {
          tag: "button",
          namespace: "html",
          id: makeId("addtonote"),
          classList: [
            "toolbar-button",
            "wide-button",
            `${config.addonRef}-readerpopup`,
          ],
          styles: {
            marginTop: "8px",
          },
          properties: {
            innerHTML: `${SVGIcon}${getString("readerpopup-addToNote-label")}`,
          },
          ignoreIfExists: true,
          listeners: [
            {
              type: "click",
              listener: async (ev) => {
                const noteEditor =
                  ZoteroContextPane && ZoteroContextPane.activeEditor;
                if (!noteEditor) {
                  return;
                }
                const editorInstance = noteEditor.getCurrentInstance();
                if (!editorInstance) {
                  return;
                }
                const task = addTranslateTask(
                  addon.data.translate.selectedText,
                  reader.itemID,
                  "addtonote",
                );
                if (!task) {
                  return;
                }
                await addon.hooks.onTranslate(task, {
                  noCheckZoteroItemLanguage: true,
                  noDisplay: true,
                });
                if (task.status !== "success") {
                  return;
                }
                const replaceMode = getPref("enableNoteReplaceMode") as boolean;
                if (replaceMode) {
                  annotation.text = task.result;
                } else {
                  annotation.comment = task.result;
                }
                // @ts-ignore should be fixed in the zotero-types
                reader._addToNote([annotation]);
              },
            },
          ],
        },
      ],
    }),
  );
}

function onTextAreaResize(ev: MouseEvent) {
  if (getPref("keepPopupSize")) {
    const textarea = ev.target as HTMLTextAreaElement;
    setPref("popupWidth", textarea.offsetWidth);
    setPref("popupHeight", textarea.offsetHeight);
  }
}

function getOnTextAreaCopy(selectionMenu: HTMLElement, targetId: string) {
  return (ev: KeyboardEvent) => {
    const textarea = selectionMenu.querySelector(
      `#${targetId}`,
    ) as HTMLTextAreaElement;
    const isMod = ev.ctrlKey || ev.metaKey;
    if (ev.key === "c" && isMod) {
      ztoolkit.getGlobal("setTimeout")(() => {
        new ztoolkit.Clipboard()
          .addText(
            textarea.value.slice(
              textarea.selectionStart,
              textarea.selectionEnd,
            ),
            "text/plain",
          )
          .copy();
      }, 10);
      ev.stopPropagation();
    } else if (ev.key === "a" && isMod) {
      textarea.selectionStart = 0;
      textarea.selectionEnd = textarea.value.length;
      ev.stopPropagation();
    } else if (ev.key === "x" && isMod) {
      new ztoolkit.Clipboard()
        .addText(
          textarea.value.slice(textarea.selectionStart, textarea.selectionEnd),
          "text/plain",
        )
        .copy();
      textarea.value = `${textarea.value.slice(
        0,
        textarea.selectionStart,
      )}${textarea.value.slice(textarea.selectionEnd)}`;
      ev.stopPropagation();
    }
  };
}

function updatePopupSize(
  selectionMenu: HTMLDivElement,
  textarea: HTMLTextAreaElement,
  resetSize: boolean = true,
): void {
  const keepSize = getPref("keepPopupSize") as boolean;
  if (keepSize) {
    return;
  }
  if (resetSize) {
    textarea.style.width = "-moz-available";
    textarea.style.height = "30px";
  }
  const viewer = selectionMenu.ownerDocument.body;
  // Get current H & W
  const textHeight = textarea.scrollHeight;
  const textWidth = textarea.scrollWidth;
  const newWidth = textWidth + 20;
  // Check until H/W<0.75 and don't overflow viewer border
  if (
    textHeight / textWidth > 0.75 &&
    selectionMenu.offsetLeft + newWidth < viewer.offsetWidth
  ) {
    // Update width
    textarea.style.width = `${newWidth}px`;
    updatePopupSize(selectionMenu, textarea, false);
    return;
  }
  // Update height
  textarea.style.height = `${textHeight + 3}px`;
}


================================================
FILE: src/modules/preferenceWindow.ts
================================================
import { config, homepage } from "../../package.json";
import { LANG_CODE } from "../utils/config";
import { getString } from "../utils/locale";
import { getPref, setPref } from "../utils/prefs";
import { setServiceSecret, validateServiceSecret } from "../utils/secret";
import { createServiceSettingsDialog } from "../utils";
import { services } from "./services";

export function registerPrefsWindow() {
  Zotero.PreferencePanes.register({
    pluginID: config.addonID,
    src: rootURI + "chrome/content/preferences.xhtml",
    label: getString("pref-title"),
    image: `chrome://${config.addonRef}/content/icons/favicon.png`,
    helpURL: homepage,
  });
}

export function registerPrefsScripts(_window: Window) {
  // This function is called when the prefs window is opened
  addon.data.prefs.w
Download .txt
gitextract_bhxnv728/

├── .gitattributes
├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   ├── dependabot.yml
│   └── workflows/
│       ├── issuebot.yml
│       ├── prbot.yml
│       └── release.yml
├── .gitignore
├── .husky/
│   └── pre-commit
├── .prettierignore
├── .prettierrc.json
├── .vscode/
│   ├── extensions.json
│   ├── launch.json
│   ├── settings.json
│   └── toolkit.code-snippets
├── LICENSE
├── README.md
├── addon/
│   ├── bootstrap.js
│   ├── chrome/
│   │   └── content/
│   │       ├── preferences.xhtml
│   │       ├── standalone.xhtml
│   │       └── styles/
│   │           ├── mathTextbox.css
│   │           ├── panel.css
│   │           └── standalone.css
│   ├── locale/
│   │   ├── en-US/
│   │   │   ├── addon.ftl
│   │   │   ├── mainWindow.ftl
│   │   │   ├── panel.ftl
│   │   │   ├── preferences.ftl
│   │   │   └── standalone.ftl
│   │   ├── it-IT/
│   │   │   ├── addon.ftl
│   │   │   ├── mainWindow.ftl
│   │   │   ├── panel.ftl
│   │   │   ├── preferences.ftl
│   │   │   └── standalone.ftl
│   │   └── zh-CN/
│   │       ├── addon.ftl
│   │       ├── mainWindow.ftl
│   │       ├── panel.ftl
│   │       ├── preferences.ftl
│   │       └── standalone.ftl
│   ├── manifest.json
│   └── prefs.js
├── eslint.config.mjs
├── package.json
├── src/
│   ├── addon.ts
│   ├── api.ts
│   ├── elements/
│   │   ├── base.ts
│   │   ├── mathTextbox.ts
│   │   └── panel.ts
│   ├── extras/
│   │   └── customElements.ts
│   ├── hooks.ts
│   ├── index.ts
│   ├── modules/
│   │   ├── defaultPrefs.ts
│   │   ├── fields.ts
│   │   ├── infoBox.ts
│   │   ├── itemTree.ts
│   │   ├── menu.ts
│   │   ├── notify.ts
│   │   ├── popup.ts
│   │   ├── preferenceWindow.ts
│   │   ├── prompt.ts
│   │   ├── reader.ts
│   │   ├── services/
│   │   │   ├── _template.ts
│   │   │   ├── aliyun.ts
│   │   │   ├── baidu.ts
│   │   │   ├── baidufield.ts
│   │   │   ├── base.ts
│   │   │   ├── bing.ts
│   │   │   ├── bingdict.ts
│   │   │   ├── caiyun.ts
│   │   │   ├── cambridgedict.ts
│   │   │   ├── claude.ts
│   │   │   ├── cnki.ts
│   │   │   ├── collinsdict.ts
│   │   │   ├── deepl.ts
│   │   │   ├── deeplcustom.ts
│   │   │   ├── deeplx.ts
│   │   │   ├── freedictionaryapi.ts
│   │   │   ├── gemini.ts
│   │   │   ├── google.ts
│   │   │   ├── gpt.ts
│   │   │   ├── haici.ts
│   │   │   ├── haicidict.ts
│   │   │   ├── huoshan.ts
│   │   │   ├── huoshanweb.ts
│   │   │   ├── index.ts
│   │   │   ├── libretranslate.ts
│   │   │   ├── microsoft.ts
│   │   │   ├── mtranserver.ts
│   │   │   ├── niutrans.ts
│   │   │   ├── nllb.ts
│   │   │   ├── openl.ts
│   │   │   ├── pot.ts
│   │   │   ├── qwenmt.ts
│   │   │   ├── tencent.ts
│   │   │   ├── tencenttransmart.ts
│   │   │   ├── webliodict.ts
│   │   │   ├── xftrans.ts
│   │   │   ├── youdao.ts
│   │   │   ├── youdaodict.ts
│   │   │   ├── youdaozhiyun.ts
│   │   │   └── youdaozhiyunllm.ts
│   │   ├── settings/
│   │   │   ├── manageKeys.ts
│   │   │   └── renameServices.ts
│   │   ├── shortcuts.ts
│   │   └── tabpanel.ts
│   └── utils/
│       ├── config.ts
│       ├── crypto.ts
│       ├── index.ts
│       ├── llmPrompt.ts
│       ├── locale.ts
│       ├── mathRenderer.ts
│       ├── prefs.ts
│       ├── secret.ts
│       ├── settingsDialog.ts
│       ├── str.ts
│       ├── task.ts
│       ├── wait.ts
│       ├── window.ts
│       └── ztoolkit.ts
├── tsconfig.json
├── typings/
│   ├── global.d.ts
│   ├── i10n.d.ts
│   └── prefs.d.ts
├── update-beta.json
├── update.json
├── update.rdf
└── zotero-plugin.config.ts
Download .txt
SYMBOL INDEX (286 symbols across 69 files)

FILE: addon/bootstrap.js
  function install (line 10) | function install(data, reason) {}
  function startup (line 12) | async function startup({ id, version, resourceURI, rootURI }, reason) {
  function onMainWindowLoad (line 45) | async function onMainWindowLoad({ window }, reason) {
  function onMainWindowUnload (line 49) | async function onMainWindowUnload({ window }, reason) {
  function shutdown (line 53) | function shutdown({ id, version, resourceURI, rootURI }, reason) {
  function uninstall (line 70) | function uninstall(data, reason) {}

FILE: src/addon.ts
  class Addon (line 8) | class Addon {
    method constructor (line 46) | constructor() {

FILE: src/api.ts
  function translate (line 65) | async function translate(
  function getTemporaryRefreshHandler (line 137) | function getTemporaryRefreshHandler(options?: { task?: TranslateTask }) {
  function getServices (line 156) | function getServices() {
  function getVersion (line 166) | function getVersion() {

FILE: src/elements/base.ts
  class PluginCEBase (line 3) | class PluginCEBase extends XULElementBase {
    method connectedCallback (line 7) | connectedCallback(): void {
    method _wrapID (line 35) | _wrapID(key: string) {
    method _unwrapID (line 42) | _unwrapID(id: string) {
    method _queryID (line 49) | _queryID(key: string) {
    method _parseContentID (line 58) | _parseContentID(dom: DocumentFragment) {

FILE: src/elements/mathTextbox.ts
  class MathTextboxElement (line 5) | class MathTextboxElement extends XULElementBase {
    method content (line 10) | get content() {
    method connectedCallback (line 26) | connectedCallback(): void {
    method init (line 31) | init(): void {
    method value (line 39) | set value(v: string) {
    method value (line 44) | get value() {
    method placeholder (line 48) | set placeholder(v: string) {
    method focus (line 52) | focus(): void {
    method _updateOverlay (line 70) | private _updateOverlay(): void {
    method _showOverlay (line 80) | private _showOverlay(): void {
    method _hideOverlay (line 98) | private _hideOverlay(): void {
    method destroy (line 106) | destroy(): void {

FILE: src/elements/panel.ts
  class TranslatorPanel (line 17) | class TranslatorPanel extends PluginCEBase {
    method item (line 22) | get item() {
    method item (line 26) | set item(val) {
    method content (line 30) | get content() {
    method init (line 112) | init(): void {
    method destroy (line 345) | destroy(): void {}
    method _filterUnconfiguredServices (line 351) | _filterUnconfiguredServices() {
    method render (line 367) | render() {

FILE: src/hooks.ts
  function onStartup (line 31) | async function onStartup() {
  function onMainWindowLoad (line 70) | async function onMainWindowLoad(win: Window): Promise<void> {
  function onMainWindowUnload (line 108) | async function onMainWindowUnload(win: Window): Promise<void> {
  function onShutdown (line 114) | function onShutdown(): void {
  function onNotify (line 129) | function onNotify(
  function onPrefsLoad (line 162) | function onPrefsLoad(event: Event) {
  function onShortcuts (line 166) | function onShortcuts(type: string) {
  function onTranslate (line 204) | async function onTranslate(...data: any) {
  function onTranslateInBatch (line 220) | async function onTranslateInBatch(
  function onReaderPopupShow (line 232) | function onReaderPopupShow(
  function onReaderPopupRefresh (line 250) | function onReaderPopupRefresh() {
  function onReaderTabPanelRefresh (line 254) | function onReaderTabPanelRefresh() {

FILE: src/index.ts
  function defineGlobal (line 25) | function defineGlobal(name: string, getter?: () => any) {

FILE: src/modules/defaultPrefs.ts
  function setDefaultPrefSettings (line 5) | function setDefaultPrefSettings() {

FILE: src/modules/fields.ts
  function registerCustomFields (line 3) | function registerCustomFields() {

FILE: src/modules/infoBox.ts
  function registerItemPaneInfoRows (line 5) | function registerItemPaneInfoRows() {

FILE: src/modules/itemTree.ts
  function registerExtraColumns (line 4) | function registerExtraColumns() {

FILE: src/modules/menu.ts
  function registerMenu (line 9) | function registerMenu() {

FILE: src/modules/notify.ts
  function registerNotify (line 1) | function registerNotify(types: _ZoteroTypes.Notifier.Type[]) {
  function unregisterNotify (line 16) | function unregisterNotify(notifyID: string) {

FILE: src/modules/popup.ts
  function updateReaderPopup (line 8) | function updateReaderPopup() {
  function buildReaderPopup (line 119) | function buildReaderPopup(
  function onTextAreaResize (line 332) | function onTextAreaResize(ev: MouseEvent) {
  function getOnTextAreaCopy (line 340) | function getOnTextAreaCopy(selectionMenu: HTMLElement, targetId: string) {
  function updatePopupSize (line 379) | function updatePopupSize(

FILE: src/modules/preferenceWindow.ts
  function registerPrefsWindow (line 9) | function registerPrefsWindow() {
  function registerPrefsScripts (line 19) | function registerPrefsScripts(_window: Window) {
  function buildPrefsPane (line 26) | function buildPrefsPane() {
  function updatePrefsPaneDefault (line 274) | function updatePrefsPaneDefault() {
  function onPrefsEvents (line 284) | function onPrefsEvents(type: string, fromElement: boolean = true) {
  function makeId (line 519) | function makeId(type: string) {

FILE: src/modules/prompt.ts
  function registerPrompt (line 3) | function registerPrompt() {

FILE: src/modules/reader.ts
  function registerReaderInitializer (line 6) | function registerReaderInitializer() {
  function createTranslateAnnotationButton (line 67) | function createTranslateAnnotationButton(

FILE: src/modules/services/_template.ts
  method translate (line 101) | async translate(data) {

FILE: src/modules/services/aliyun.ts
  function languageCode (line 44) | function languageCode(str: string) {
  function encodeRFC3986URIComponent (line 52) | function encodeRFC3986URIComponent(str: string) {
  method secretValidator (line 66) | secretValidator(secret) {
  method config (line 84) | config(settings) {

FILE: src/modules/services/baidu.ts
  method secretValidator (line 48) | secretValidator(secret: string) {

FILE: src/modules/services/baidufield.ts
  method secretValidator (line 43) | secretValidator(secret: string) {

FILE: src/modules/services/base.ts
  type TranslateService (line 7) | interface TranslateService {

FILE: src/modules/services/bing.ts
  function getToken (line 47) | async function getToken(forceRefresh: boolean = false) {

FILE: src/modules/services/caiyun.ts
  function transLang (line 23) | function transLang(inlang: string = "") {
  method secretValidator (line 43) | secretValidator(secret: string) {

FILE: src/modules/services/cambridgedict.ts
  function getDictionaryCode (line 80) | function getDictionaryCode(fromCode: string, toCode: string) {
  function parser1 (line 100) | function parser1(doc: Document) {
  function parser2 (line 131) | function parser2(doc: Document) {
  function parseBody (line 144) | function parseBody(block: Element): string {

FILE: src/modules/services/claude.ts
  function transformContent (line 5) | function transformContent(
  method secretValidator (line 160) | secretValidator(secret: string) {
  method config (line 176) | config(settings) {

FILE: src/modules/services/cnki.ts
  function getToken (line 80) | async function getToken(forceRefresh: boolean = false) {
  function getWord (line 119) | async function getWord(text: string) {
  method config (line 131) | config(settings) {

FILE: src/modules/services/deepl.ts
  type ID (line 4) | type ID = "deeplfree" | "deeplpro";
  function createDeepl (line 6) | function createDeepl(id: ID): TranslateService {
  function mapLang (line 58) | function mapLang(lang: string) {
  constant LANG_MAP (line 65) | const LANG_MAP = {

FILE: src/modules/services/deeplcustom.ts
  method config (line 32) | config(settings) {

FILE: src/modules/services/deeplx.ts
  function mapLang (line 74) | function mapLang(lang: string) {
  constant LANG_MAP (line 81) | const LANG_MAP = {
  method config (line 97) | config(setting) {

FILE: src/modules/services/gemini.ts
  function transformContent (line 8) | function transformContent(
  function getGenContentAPI (line 22) | function getGenContentAPI(data: Required<TranslateTask>) {
  method secretValidator (line 88) | secretValidator(secret: string) {
  method config (line 99) | config(settings) {

FILE: src/modules/services/google.ts
  function _google (line 4) | async function _google(url: string, data: Required<TranslateTask>) {
  constant LANG_MAP (line 88) | const LANG_MAP = {
  type ID (line 93) | type ID = "google" | "googleapi";
  function createGoogle (line 95) | function createGoogle(id: ID): TranslateService {

FILE: src/modules/services/gpt.ts
  type ID (line 4) | type ID = "chatgpt" | "customgpt1" | "customgpt2" | "customgpt3" | "azur...
  function getCustomParams (line 6) | function getCustomParams(prefix: string): Record<string, any> {
  type ParsedResponse (line 29) | interface ParsedResponse {
  function isResponsesApiEndpoint (line 37) | function isResponsesApiEndpoint(url: string): boolean {
  function parseResponsesApiStreamResponse (line 45) | function parseResponsesApiStreamResponse(obj: any): ParsedResponse {
  function parseResponsesApiNonStreamResponse (line 80) | function parseResponsesApiNonStreamResponse(obj: any): string {
  function parseStreamResponse (line 95) | function parseStreamResponse(obj: any): ParsedResponse {
  function parseNonStreamResponse (line 115) | function parseNonStreamResponse(obj: any): string {
  function transformContent (line 135) | function transformContent(
  function createGPTService (line 305) | function createGPTService(id: ID): TranslateService {

FILE: src/modules/services/haici.ts
  function getAppId (line 29) | async function getAppId(forceRefresh: boolean = false) {

FILE: src/modules/services/huoshan.ts
  function getDateTimeNow (line 9) | function getDateTimeNow() {
  function getSigningKey (line 13) | async function getSigningKey(sk: any, metaData: any) {
  function getStringHeaders (line 20) | function getStringHeaders(header: any) {
  function getSignedHeaders (line 29) | function getSignedHeaders(header: any) {
  method secretValidator (line 113) | secretValidator(secret: string) {

FILE: src/modules/services/index.ts
  class TranslationServices (line 95) | class TranslationServices {
    method sortServices (line 107) | private sortServices<T extends TranslateService>(services: T[]) {
    method getServiceById (line 146) | public getServiceById(id: string): TranslateService | undefined {
    method getAllServices (line 150) | public getAllServices(): TranslateService[] {
    method getAllServicesWithType (line 154) | public getAllServicesWithType(type: string): TranslateService[] {
    method getServiceNameByID (line 158) | public getServiceNameByID(id: string): string {
    method getAllServiceNames (line 175) | public getAllServiceNames(): string[] {
    method getAllServiceNamesWithType (line 181) | public getAllServiceNamesWithType(type: string): string[] {
    method getUnconfiguredServiceIds (line 192) | public getUnconfiguredServiceIds(): Set<string> {
    method runTranslationTask (line 230) | public async runTranslationTask(

FILE: src/modules/services/libretranslate.ts
  method config (line 48) | config(settings) {

FILE: src/modules/services/microsoft.ts
  method secretValidator (line 42) | secretValidator(secret: string) {

FILE: src/modules/services/mtranserver.ts
  function mapLang (line 31) | function mapLang(lang: string) {
  constant LANG_MAP (line 39) | const LANG_MAP = {
  method config (line 56) | config(settings) {

FILE: src/modules/services/niutrans.ts
  method secretValidator (line 73) | secretValidator(secret: string) {
  method config (line 86) | config(settings) {

FILE: src/modules/services/nllb.ts
  function mapLang (line 114) | function mapLang(lang: string) {
  constant LANG_MAP (line 124) | const LANG_MAP = {
  method config (line 163) | config(settings) {

FILE: src/modules/services/openl.ts
  method secretValidator (line 60) | secretValidator(secret: string) {

FILE: src/modules/services/pot.ts
  method config (line 31) | config(settings) {

FILE: src/modules/services/qwenmt.ts
  function mapLang (line 63) | function mapLang(lang: string) {
  constant LANG_MAP (line 70) | const LANG_MAP = {
  method secretValidator (line 117) | secretValidator(secret: string) {
  method config (line 127) | config(settings) {

FILE: src/modules/services/tencent.ts
  function MigrateSecret (line 31) | function MigrateSecret(parsedStr: string, str: string, prefKey: string) {
  function encodeRFC5987ValueChars (line 48) | function encodeRFC5987ValueChars(str: string) {
  method secretValidator (line 127) | secretValidator(secret: string) {
  method config (line 149) | config(settings) {

FILE: src/modules/services/xftrans.ts
  function transLang (line 27) | function transLang(inlang: string = "") {
  function getPostBody (line 73) | function getPostBody(text: string, from: string, to: string) {
  function getDigest (line 88) | async function getDigest(body: any) {
  function getAuthStr (line 91) | async function getAuthStr(date: string, digest: string) {
  method secretValidator (line 120) | secretValidator(secret: string) {
  method config (line 138) | config(settings) {

FILE: src/modules/services/youdaozhiyun.ts
  function encodeRFC5987ValueChars (line 6) | function encodeRFC5987ValueChars(str: string) {
  function truncate (line 16) | function truncate(q: string) {
  method secretValidator (line 62) | secretValidator(secret: string) {
  method config (line 82) | config(settings) {

FILE: src/modules/services/youdaozhiyunllm.ts
  function truncate (line 7) | function truncate(q: string) {
  function transLang (line 13) | function transLang(inlang: string = "") {
  function grepErrorParagraphs (line 161) | function grepErrorParagraphs(input: string): string[] {
  method secretValidator (line 173) | secretValidator(secret: string) {
  method config (line 191) | config(settings) {

FILE: src/modules/settings/manageKeys.ts
  function manageKeysDialog (line 4) | async function manageKeysDialog() {

FILE: src/modules/settings/renameServices.ts
  function renameServicesDialog (line 4) | async function renameServicesDialog() {

FILE: src/modules/shortcuts.ts
  function registerShortcuts (line 3) | function registerShortcuts() {

FILE: src/modules/tabpanel.ts
  function registerReaderTabPanel (line 11) | function registerReaderTabPanel() {
  function openWindowPanel (line 62) | async function openWindowPanel() {
  function updateReaderTabPanels (line 83) | function updateReaderTabPanels() {
  function onInit (line 93) | function onInit({ body, refresh }: { body: HTMLElement; refresh: () => v...
  function buildExtraPanel (line 99) | function buildExtraPanel(doc: Document) {
  function onItemChange (line 242) | function onItemChange({
  function updateExtraPanel (line 260) | function updateExtraPanel(container: HTMLElement | Document) {
  function onDestroy (line 281) | function onDestroy(options: any) {
  function onUpdateHeight (line 287) | function onUpdateHeight({ body }: { body: HTMLElement }) {

FILE: src/utils/config.ts
  function inferLanguage (line 5) | function inferLanguage(str: string) {
  function matchLanguage (line 16) | function matchLanguage(str: string) {
  constant LANG_CODE (line 27) | const LANG_CODE = <const>[
  constant MACRO_LANG_MAP (line 335) | const MACRO_LANG_MAP = Object.entries(ISO6393_MACRO_LANGS).reduce(
  constant LANG_CODE_INDEX_MAP (line 347) | const LANG_CODE_INDEX_MAP = LANG_CODE.reduce(
  function mapISO6393to6391 (line 359) | function mapISO6393to6391(code: string) {

FILE: src/utils/crypto.ts
  function base64 (line 1) | function base64(buffer: ArrayBuffer) {
  function randomString (line 6) | function randomString(length: number) {
  function hex (line 12) | function hex(buffer: ArrayBuffer) {
  function hmacSha1Digest (line 17) | async function hmacSha1Digest(
  function hmacSha256Digest (line 41) | async function hmacSha256Digest(
  function sha256Digest (line 65) | async function sha256Digest(message: string): Promise<ArrayBuffer> {
  function pkcs7Pad (line 70) | function pkcs7Pad(block: Uint8Array | Array<number>) {
  function aesEcbEncrypt (line 78) | async function aesEcbEncrypt(message: string, secret: string) {

FILE: src/utils/llmPrompt.ts
  function transformPromptWithContext (line 4) | function transformPromptWithContext(

FILE: src/utils/locale.ts
  function initLocale (line 9) | function initLocale() {
  function getString (line 50) | function getString(...inputs: any[]) {
  function _getString (line 64) | function _getString(
  function getLocaleID (line 88) | function getLocaleID(id: FluentMessageId) {

FILE: src/utils/mathRenderer.ts
  constant MATH_REGEX (line 6) | const MATH_REGEX =
  constant DEFAULT_KATEX_OPTIONS (line 8) | const DEFAULT_KATEX_OPTIONS = {
  function containsMath (line 14) | function containsMath(text: string): boolean {
  function escapeHtml (line 21) | function escapeHtml(doc: Document, text: string): string {
  function renderMathInText (line 27) | function renderMathInText(doc: Document, text: string): string {
  function renderMathInElement (line 88) | function renderMathInElement(element: HTMLElement, text: string): void {

FILE: src/utils/prefs.ts
  type KeysWithStringValue (line 12) | type KeysWithStringValue<T> = {
  type KeysWithNumberValue (line 16) | type KeysWithNumberValue<T> = {
  type KeysWithBooleanValue (line 20) | type KeysWithBooleanValue<T> = {
  type _PluginPrefsMap (line 24) | type _PluginPrefsMap = _ZoteroTypes.Prefs["PluginPrefsMap"];
  type PrefKeys (line 25) | type PrefKeys = keyof _PluginPrefsMap;
  type PrefKeysWithStringValue (line 26) | type PrefKeysWithStringValue = KeysWithStringValue<_PluginPrefsMap>;
  type PrefKeysWithNumberValue (line 27) | type PrefKeysWithNumberValue = KeysWithNumberValue<_PluginPrefsMap>;
  type PrefKeysWithBooleanValue (line 28) | type PrefKeysWithBooleanValue = KeysWithBooleanValue<_PluginPrefsMap>;
  function getPref (line 32) | function getPref(key: string): string | number | boolean {
  function setPref (line 41) | function setPref(key: string, value: string | number | boolean) {
  function clearPref (line 47) | function clearPref(key: string) {
  function getPrefJSON (line 51) | function getPrefJSON(key: string) {
  function registerPrefObserver (line 68) | function registerPrefObserver(key: string, callback: (value: any) => voi...
  function unregisterPrefObserver (line 76) | function unregisterPrefObserver(observerID: symbol) {

FILE: src/utils/secret.ts
  type SecretValidateResult (line 3) | interface SecretValidateResult {
  function getServiceSecret (line 9) | function getServiceSecret(serviceId: string) {
  function setServiceSecret (line 18) | function setServiceSecret(serviceId: string, secret: string) {
  function validateServiceSecret (line 29) | function validateServiceSecret(

FILE: src/utils/settingsDialog.ts
  type ConfigField (line 14) | type ConfigField =
  type DialogFieldBase (line 22) | type DialogFieldBase = {
  type InputField (line 49) | type InputField = InputFieldBase | InputFieldText | InputFieldNumber;
  type InputFieldBase (line 51) | type InputFieldBase = DialogFieldBase & {
  type InputFieldText (line 56) | type InputFieldText = InputFieldBase & {
  type InputFieldNumber (line 60) | type InputFieldNumber = InputFieldBase & {
  type TextareaField (line 68) | type TextareaField = DialogFieldBase & {
  type CheckboxField (line 73) | type CheckboxField = DialogFieldBase & {
  type SelectField (line 77) | type SelectField = DialogFieldBase & {
  type ButtonField (line 85) | type ButtonField = DialogFieldBase & {
  type ParamsField (line 89) | type ParamsField = DialogFieldBase & {
  type Validater (line 93) | type Validater = (
  type AllowedSettingsMethods (line 103) | type AllowedSettingsMethods = Pick<
  class ServiceSettingsDialog (line 118) | class ServiceSettingsDialog extends SettingsDialogHelper {
    method constructor (line 119) | constructor() {
    method addTextSetting (line 124) | addTextSetting(field: InputFieldText): AllowedSettingsMethods {
    method addPasswordSetting (line 137) | addPasswordSetting(field: InputFieldText): AllowedSettingsMethods {
    method addNumberSetting (line 149) | addNumberSetting(field: InputFieldNumber): AllowedSettingsMethods {
    method addCheckboxSetting (line 164) | addCheckboxSetting(field: CheckboxField): AllowedSettingsMethods {
    method addSelectSetting (line 183) | addSelectSetting(field: SelectField): AllowedSettingsMethods {
    method addTextAreaSetting (line 201) | addTextAreaSetting(field: TextareaField): AllowedSettingsMethods {
    method addCustomParamsSetting (line 214) | addCustomParamsSetting(field: ParamsField): AllowedSettingsMethods {
    method onSave (line 225) | onSave(validate?: Validater) {
  function createServiceSettingsDialog (line 231) | async function createServiceSettingsDialog(
  constant CUSTOM_PARAMS_INPUT_STYLES (line 268) | const CUSTOM_PARAMS_INPUT_STYLES = {
  function createParamInputCell (line 278) | function createParamInputCell(
  function openCustomRequestDialog (line 299) | async function openCustomRequestDialog(prefKey: string) {

FILE: src/utils/str.ts
  function slice (line 3) | function slice(str: string, len: number) {
  function fill (line 7) | function fill(
  function stripEmptyLines (line 30) | function stripEmptyLines(text: string, enabled: boolean): string {

FILE: src/utils/task.ts
  type TranslateTask (line 8) | interface TranslateTask {
  type TranslateTaskProcessor (line 95) | type TranslateTaskProcessor = (
  class TranslateTaskRunner (line 99) | class TranslateTaskRunner {
    method constructor (line 101) | constructor(processor: TranslateTaskProcessor) {
    method run (line 105) | public async run(data: TranslateTask) {
    method makeErrorInfo (line 141) | protected makeErrorInfo(serviceId: string, detail: string) {
  function addTranslateTask (line 148) | function addTranslateTask(
  function addTranslateAnnotationTask (line 235) | function addTranslateAnnotationTask(
  function addTranslateTitleTask (line 254) | function addTranslateTitleTask(
  function addTranslateAbstractTask (line 273) | function addTranslateAbstractTask(
  function setDefaultService (line 296) | function setDefaultService(task: TranslateTask) {
  function cleanTasks (line 313) | function cleanTasks() {
  function getTranslateTasks (line 327) | function getTranslateTasks(count: number) {
  function getLastTranslateTask (line 334) | function getLastTranslateTask<
  function updateTranslateTaskLang (line 359) | function updateTranslateTaskLang(task: TranslateTask) {
  function putTranslateTaskAtHead (line 366) | function putTranslateTaskAtHead(taskId: string) {
  function autoDetectLanguage (line 378) | function autoDetectLanguage(item: Zotero.Item | null) {

FILE: src/utils/wait.ts
  function waitUntil (line 1) | function waitUntil(
  function waitUtilAsync (line 18) | function waitUtilAsync(

FILE: src/utils/window.ts
  function isWindowAlive (line 3) | function isWindowAlive(win?: Window) {
  function getFocusedWindow (line 7) | function getFocusedWindow() {

FILE: src/utils/ztoolkit.ts
  function createZToolkit (line 20) | function createZToolkit() {
  function initZToolkit (line 31) | function initZToolkit(_ztoolkit: ReturnType<typeof createZToolkit>) {
  class MyToolkit (line 46) | class MyToolkit extends BasicTool {
    method constructor (line 58) | constructor() {
    method unregisterAll (line 72) | unregisterAll() {

FILE: typings/global.d.ts
  type ZToolkit (line 10) | type ZToolkit = ReturnType<
  class XULElementBase (line 22) | class XULElementBase extends HTMLElement {
  class MozXULElement (line 38) | class MozXULElement {

FILE: typings/i10n.d.ts
  type FluentMessageId (line 5) | type FluentMessageId =

FILE: typings/prefs.d.ts
  type Prefs (line 8) | interface Prefs {
Condensed preview — 128 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (486K chars).
[
  {
    "path": ".gitattributes",
    "chars": 18,
    "preview": "* text=auto eol=lf"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 701,
    "preview": "# These are supported funding model platforms\n\ngithub: [windingwind]\npatreon: # Replace with a single Patreon username\no"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "chars": 2557,
    "preview": "name: Bug report\ndescription: File a bug / issue\ntitle: \"[Bug] \"\nlabels:\n  - bug\n  # - Needs Triage\nassignees: windingwi"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 187,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Documentation in Chinese (中文文档)\n    url: https://zotero.yuque.com/s"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "chars": 1980,
    "preview": "name: Feature request\ndescription: Suggest an idea for this project\ntitle: \"[Feature] \"\nlabels:\n  - enhancement\nassignee"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 597,
    "preview": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where "
  },
  {
    "path": ".github/workflows/issuebot.yml",
    "chars": 1899,
    "preview": "name: Close inactive issues\non:\n  schedule:\n    - cron: \"30 1 * * *\"\n  issues:\n    types:\n      - labeled\n\njobs:\n  close"
  },
  {
    "path": ".github/workflows/prbot.yml",
    "chars": 1908,
    "preview": "name: Pull Request\n\non:\n  pull_request_target:\n    types: [opened, synchronize, reopened]\n\npermissions:\n  contents: writ"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 1225,
    "preview": "name: Release\n\non:\n  push:\n    tags:\n      - v**\n\npermissions:\n  contents: write\n  issues: write\n  pull-requests: write\n"
  },
  {
    "path": ".gitignore",
    "chars": 110,
    "preview": "build\nlogs\nnode_modules\npnpm-lock.yaml\nyarn.lock\ntsconfig.tsbuildinfo\nzotero-cmd.json\n.DS_Store\n.env\n.scaffold"
  },
  {
    "path": ".husky/pre-commit",
    "chars": 58,
    "preview": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\n\nnpx lint-staged\n"
  },
  {
    "path": ".prettierignore",
    "chars": 93,
    "preview": ".vscode\nbuild\nlogs\nnode_modules\npackage-lock.json\nyarn.lock\npnpm-lock.yaml\n# zotero-cmd.json\n"
  },
  {
    "path": ".prettierrc.json",
    "chars": 193,
    "preview": "{\n  \"printWidth\": 80,\n  \"tabWidth\": 2,\n  \"endOfLine\": \"lf\",\n  \"overrides\": [\n    {\n      \"files\": [\"*.xhtml\"],\n      \"op"
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 120,
    "preview": "{\n  \"recommendations\": [\n    \"dbaeumer.vscode-eslint\",\n    \"esbenp.prettier-vscode\",\n    \"macabeus.vscode-fluent\"\n  ]\n}\n"
  },
  {
    "path": ".vscode/launch.json",
    "chars": 508,
    "preview": "{\n  // 使用 IntelliSense 了解相关属性。\n  // 悬停以查看现有属性的描述。\n  // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387\n  \"ve"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 194,
    "preview": "{\n  \"editor.formatOnType\": false,\n  \"editor.formatOnSave\": true,\n  \"editor.codeActionsOnSave\": {\n    \"source.fixAll.esli"
  },
  {
    "path": ".vscode/toolkit.code-snippets",
    "chars": 1293,
    "preview": "{\n  \"appendElement - full\": {\n    \"scope\": \"javascript,typescript\",\n    \"prefix\": \"appendElement\",\n    \"body\": [\n      \""
  },
  {
    "path": "LICENSE",
    "chars": 34520,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 23458,
    "preview": "# ![Translate for Zotero](addon/chrome/content/icons/favicon.png)Translate for Zotero\n\n[![zotero target version](https:/"
  },
  {
    "path": "addon/bootstrap.js",
    "chars": 1904,
    "preview": "/**\n * Most of this code is from Zotero team's official Make It Red example[1]\n * or the Zotero 7 documentation[2].\n * ["
  },
  {
    "path": "addon/chrome/content/preferences.xhtml",
    "chars": 11441,
    "preview": "<linkset>\n  <html:link rel=\"localization\" href=\"__addonRef__-preferences.ftl\" />\n</linkset>\n<vbox\n  id=\"zotero-prefpane-"
  },
  {
    "path": "addon/chrome/content/standalone.xhtml",
    "chars": 2081,
    "preview": "<?xml version=\"1.0\"?>\n<!-- prettier-ignore -->\n<!DOCTYPE window>\n<!-- prettier-ignore -->\n<?xml-stylesheet href=\"chrome:"
  },
  {
    "path": "addon/chrome/content/styles/mathTextbox.css",
    "chars": 42,
    "preview": "math-textbox[hidden] {\n  display: none;\n}\n"
  },
  {
    "path": "addon/chrome/content/styles/panel.css",
    "chars": 2360,
    "preview": "translator-plugin-panel {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  height: var(--details-height, 450px);"
  },
  {
    "path": "addon/chrome/content/styles/standalone.css",
    "chars": 510,
    "preview": "window {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  padding: 20px;\n}\n\nlinkset {\n  display: none;\n}\n\n.separ"
  },
  {
    "path": "addon/locale/en-US/addon.ftl",
    "chars": 5798,
    "preview": "service-huoshanweb=Volcengine Web\nservice-tencenttransmart=Tencent Transmart\nservice-huoshan=Huoshan\nservice-googleapi=G"
  },
  {
    "path": "addon/locale/en-US/mainWindow.ftl",
    "chars": 451,
    "preview": "itemPaneSection-header =\n    .label = Translate\nitemPaneSection-sidenav =\n    .tooltiptext = Translate\nitemPaneSection-f"
  },
  {
    "path": "addon/locale/en-US/panel.ftl",
    "chars": 486,
    "preview": "translate =\n    .label = Translate\n    .tooltiptext = { PLATFORM() ->\n        [macos] ⌘\n       *[other] Ctrl\n    } + T\n\n"
  },
  {
    "path": "addon/locale/en-US/preferences.ftl",
    "chars": 4954,
    "preview": "pref-general = General\n\npref-basic-enableAuto =\n    .label = Automatically Translate Selection\npref-basic-enableComment "
  },
  {
    "path": "addon/locale/en-US/standalone.ftl",
    "chars": 162,
    "preview": "add-source =\n    .label = Add Source\nremove-source =\n    .label = Remove\npin-window =\n    .label = { $mode ->\n        [p"
  },
  {
    "path": "addon/locale/it-IT/addon.ftl",
    "chars": 6027,
    "preview": "service-huoshanweb=Volcengine Web\nservice-tencenttransmart=Tencent Transmart\nservice-huoshan=Huoshan\nservice-googleapi=G"
  },
  {
    "path": "addon/locale/it-IT/mainWindow.ftl",
    "chars": 447,
    "preview": "itemPaneSection-header =\n    .label = Translate\nitemPaneSection-sidenav =\n    .tooltiptext = Translate\nitemPaneSection-f"
  },
  {
    "path": "addon/locale/it-IT/panel.ftl",
    "chars": 486,
    "preview": "translate =\n    .label = Translate\n    .tooltiptext = { PLATFORM() ->\n        [macos] ⌘\n       *[other] Ctrl\n    } + T\n\n"
  },
  {
    "path": "addon/locale/it-IT/preferences.ftl",
    "chars": 5640,
    "preview": "pref-general = Generale\n\npref-basic-enableAuto =\n    .label = Traduci automaticamente la selezione\npref-basic-enableComm"
  },
  {
    "path": "addon/locale/it-IT/standalone.ftl",
    "chars": 188,
    "preview": "add-source =\n    .label = Aggiungi servizio di traduzione\nremove-source =\n    .label = Rimuovi\npin-window =\n    .label ="
  },
  {
    "path": "addon/locale/zh-CN/addon.ftl",
    "chars": 4769,
    "preview": "service-huoshanweb=火山网页翻译\nservice-tencenttransmart=腾讯TranSmart\nservice-huoshan=火山翻译\nservice-googleapi=Google(API)\nservic"
  },
  {
    "path": "addon/locale/zh-CN/mainWindow.ftl",
    "chars": 360,
    "preview": "itemPaneSection-header =\n    .label = 翻译\nitemPaneSection-sidenav =\n    .tooltiptext = 翻译\nitemPaneSection-fullHeight =\n  "
  },
  {
    "path": "addon/locale/zh-CN/panel.ftl",
    "chars": 429,
    "preview": "translate =\n    .label = 翻译\n    .tooltiptext = { PLATFORM() ->\n        [macos] ⌘\n       *[other] Ctrl\n    } + T\n\nswapLan"
  },
  {
    "path": "addon/locale/zh-CN/preferences.ftl",
    "chars": 3538,
    "preview": "pref-general = 通用\n\npref-basic-enableAuto =\n    .label = 自动翻译选择内容\npref-basic-enableComment =\n    .label = 自动翻译注释\npref-bas"
  },
  {
    "path": "addon/locale/zh-CN/standalone.ftl",
    "chars": 149,
    "preview": "add-source =\n    .label = 添加源\nremove-source =\n    .label = 移除\npin-window =\n    .label = { $mode ->\n        [pinned] 📌取消置"
  },
  {
    "path": "addon/manifest.json",
    "chars": 480,
    "preview": "{\n  \"manifest_version\": 2,\n  \"name\": \"__addonName__\",\n  \"version\": \"__buildVersion__\",\n  \"description\": \"__description__"
  },
  {
    "path": "addon/prefs.js",
    "chars": 7053,
    "preview": "pref(\"__prefsPrefix__.enableAuto\", true);\npref(\"__prefsPrefix__.enableDict\", true);\npref(\"__prefsPrefix__.attachPaperCon"
  },
  {
    "path": "eslint.config.mjs",
    "chars": 1615,
    "preview": "// @ts-check Let TS check this config file\n\nimport eslint from \"@eslint/js\";\nimport tseslint from \"typescript-eslint\";\n\n"
  },
  {
    "path": "package.json",
    "chars": 1693,
    "preview": "{\n  \"name\": \"zotero-pdf-translate\",\n  \"version\": \"2.4.3\",\n  \"description\": \"Translate PDF, EPub, webpage, metadata, anno"
  },
  {
    "path": "src/addon.ts",
    "chars": 1770,
    "preview": "import api from \"./api\";\nimport hooks from \"./hooks\";\nimport { TranslateTask } from \"./utils/task\";\nimport { services, T"
  },
  {
    "path": "src/api.ts",
    "chars": 5062,
    "preview": "import { getPref } from \"./utils/prefs\";\nimport { TranslateTask } from \"./utils/task\";\nimport { version } from \"../packa"
  },
  {
    "path": "src/elements/base.ts",
    "chars": 1849,
    "preview": "import { config } from \"../../package.json\";\n\nexport class PluginCEBase extends XULElementBase {\n  _addon!: typeof addon"
  },
  {
    "path": "src/elements/mathTextbox.ts",
    "chars": 3202,
    "preview": "import { config } from \"../../package.json\";\nimport { renderMathInText, containsMath } from \"../utils/mathRenderer\";\nimp"
  },
  {
    "path": "src/elements/panel.ts",
    "chars": 14583,
    "preview": "import { config } from \"../../package.json\";\nimport { PluginCEBase } from \"./base\";\nimport { getPref, setPref } from \".."
  },
  {
    "path": "src/extras/customElements.ts",
    "chars": 424,
    "preview": "import { TranslatorPanel } from \"../elements/panel\";\nimport { MathTextboxElement } from \"../elements/mathTextbox\";\n\ncons"
  },
  {
    "path": "src/hooks.ts",
    "chars": 6974,
    "preview": "import { config } from \"../package.json\";\nimport { initLocale } from \"./utils/locale\";\nimport {\n  registerPrefsScripts,\n"
  },
  {
    "path": "src/index.ts",
    "chars": 1007,
    "preview": "import { BasicTool } from \"zotero-plugin-toolkit\";\nimport Addon from \"./addon\";\nimport { config } from \"../package.json\""
  },
  {
    "path": "src/modules/defaultPrefs.ts",
    "chars": 3377,
    "preview": "import { clearPref, getPref, getPrefJSON, setPref } from \"../utils/prefs\";\nimport { getServiceSecret, setServiceSecret }"
  },
  {
    "path": "src/modules/fields.ts",
    "chars": 830,
    "preview": "export { registerCustomFields };\n\nfunction registerCustomFields() {\n  ztoolkit.FieldHook.register(\n    \"getField\",\n    \""
  },
  {
    "path": "src/modules/infoBox.ts",
    "chars": 1603,
    "preview": "import { getPref } from \"../utils/prefs\";\n\nexport { registerItemPaneInfoRows };\n\nfunction registerItemPaneInfoRows() {\n "
  },
  {
    "path": "src/modules/itemTree.ts",
    "chars": 644,
    "preview": "import { config } from \"../../package.json\";\nimport { getString } from \"../utils/locale\";\n\nexport function registerExtra"
  },
  {
    "path": "src/modules/menu.ts",
    "chars": 2006,
    "preview": "import { config } from \"../../package.json\";\nimport { getPref } from \"../utils/prefs\";\nimport {\n  addTranslateAbstractTa"
  },
  {
    "path": "src/modules/notify.ts",
    "chars": 534,
    "preview": "export function registerNotify(types: _ZoteroTypes.Notifier.Type[]) {\n  const callback = {\n    notify: async (...data: P"
  },
  {
    "path": "src/modules/popup.ts",
    "chars": 12744,
    "preview": "import { SVGIcon } from \"../utils/config\";\nimport { config } from \"../../package.json\";\nimport { getString } from \"../ut"
  },
  {
    "path": "src/modules/preferenceWindow.ts",
    "chars": 14296,
    "preview": "import { config, homepage } from \"../../package.json\";\nimport { LANG_CODE } from \"../utils/config\";\nimport { getString }"
  },
  {
    "path": "src/modules/prompt.ts",
    "chars": 10205,
    "preview": "import { config } from \"../../package.json\";\n\nexport function registerPrompt() {\n  ztoolkit.Prompt.register([\n    {\n    "
  },
  {
    "path": "src/modules/reader.ts",
    "chars": 3656,
    "preview": "import { config } from \"../../package.json\";\nimport { SVGIcon } from \"../utils/config\";\nimport { addTranslateAnnotationT"
  },
  {
    "path": "src/modules/services/_template.ts",
    "chars": 5325,
    "preview": "/**\n * Example Translation Service Template\n *\n * This file is a template for adding a new translation service.\n * Follo"
  },
  {
    "path": "src/modules/services/aliyun.ts",
    "chars": 3014,
    "preview": "import { TranslateService } from \"./base\";\nimport { getPref } from \"../../utils/prefs\";\nimport { base64, hmacSha1Digest,"
  },
  {
    "path": "src/modules/services/baidu.ts",
    "chars": 1905,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async (data) => {\n  const p"
  },
  {
    "path": "src/modules/services/baidufield.ts",
    "chars": 1826,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async (data) => {\n  const p"
  },
  {
    "path": "src/modules/services/base.ts",
    "chars": 1586,
    "preview": "import {\n  SecretValidateResult,\n  AllowedSettingsMethods,\n  TranslateTaskProcessor,\n} from \"../../utils\";\n\nexport inter"
  },
  {
    "path": "src/modules/services/bing.ts",
    "chars": 2768,
    "preview": "import { getPrefJSON, setPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate: T"
  },
  {
    "path": "src/modules/services/bingdict.ts",
    "chars": 1285,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/caiyun.ts",
    "chars": 1524,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/cambridgedict.ts",
    "chars": 5696,
    "preview": "import { TranslateService } from \"./base\";\n\nconst cambridgeLangCode = <const>[\n  { name: \"arabic\", code: \"ar\", parser: p"
  },
  {
    "path": "src/modules/services/claude.ts",
    "chars": 6203,
    "preview": "import { getPref, getString, transformPromptWithContext } from \"../../utils\";\nimport { TranslateService } from \"./base\";"
  },
  {
    "path": "src/modules/services/cnki.ts",
    "chars": 4170,
    "preview": "import { aesEcbEncrypt, base64 } from \"../../utils/crypto\";\nimport { getPref, getPrefJSON, setPref } from \"../../utils/p"
  },
  {
    "path": "src/modules/services/collinsdict.ts",
    "chars": 1259,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/deepl.ts",
    "chars": 2108,
    "preview": "import { version } from \"../../../package.json\";\nimport { TranslateService } from \"./base\";\n\ntype ID = \"deeplfree\" | \"de"
  },
  {
    "path": "src/modules/services/deeplcustom.ts",
    "chars": 1079,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate = <TranslateSer"
  },
  {
    "path": "src/modules/services/deeplx.ts",
    "chars": 2837,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate = <TranslateSer"
  },
  {
    "path": "src/modules/services/freedictionaryapi.ts",
    "chars": 1072,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate = <TranslateService[\"translate\"]>async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/gemini.ts",
    "chars": 2927,
    "preview": "import { getPref, transformPromptWithContext } from \"../../utils\";\nimport { TranslateService } from \"./base\";\nimport typ"
  },
  {
    "path": "src/modules/services/google.ts",
    "chars": 3151,
    "preview": "import { TranslateTask } from \"../../utils/task\";\nimport { TranslateService } from \"./base\";\n\nasync function _google(url"
  },
  {
    "path": "src/modules/services/gpt.ts",
    "chars": 13917,
    "preview": "import { getPref, getString, transformPromptWithContext } from \"../../utils\";\nimport { TranslateService } from \"./base\";"
  },
  {
    "path": "src/modules/services/haici.ts",
    "chars": 1796,
    "preview": "import { getPrefJSON, setPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate = "
  },
  {
    "path": "src/modules/services/haicidict.ts",
    "chars": 1477,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate = <TranslateService[\"translate\"]>async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/huoshan.ts",
    "chars": 3763,
    "preview": "import { hex, hmacSha256Digest, sha256Digest } from \"../../utils/crypto\";\nimport { TranslateService } from \"./base\";\n\nco"
  },
  {
    "path": "src/modules/services/huoshanweb.ts",
    "chars": 1056,
    "preview": "import type { TranslateService } from \"./base\";\n\n// https://github.com/TechDecryptor/pot-app-translate-plugin-volcengine"
  },
  {
    "path": "src/modules/services/index.ts",
    "chars": 13165,
    "preview": "import { TranslateService } from \"./base\";\nimport {\n  getString,\n  getPref,\n  getLastTranslateTask,\n  TranslateTask,\n  T"
  },
  {
    "path": "src/modules/services/libretranslate.ts",
    "chars": 1426,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate = <TranslateSer"
  },
  {
    "path": "src/modules/services/microsoft.ts",
    "chars": 1748,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate = <TranslateService[\"translate\"]>async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/mtranserver.ts",
    "chars": 1718,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate = <TranslateSer"
  },
  {
    "path": "src/modules/services/niutrans.ts",
    "chars": 12955,
    "preview": "import JSEncrypt from \"jsencrypt\";\nimport {\n  createServiceSettingsDialog,\n  getString,\n  ServiceSettingsDialog,\n  setSe"
  },
  {
    "path": "src/modules/services/nllb.ts",
    "chars": 5585,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { getString } from \"../../utils/locale\";\nimport { TranslateService }"
  },
  {
    "path": "src/modules/services/openl.ts",
    "chars": 2098,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async (data) => {\n  const ["
  },
  {
    "path": "src/modules/services/pot.ts",
    "chars": 964,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { TranslateService } from \"./base\";\n\nconst translate: TranslateServi"
  },
  {
    "path": "src/modules/services/qwenmt.ts",
    "chars": 3397,
    "preview": "import { getPref } from \"../../utils/prefs\";\nimport { getString } from \"../../utils/locale\";\nimport { TranslateService }"
  },
  {
    "path": "src/modules/services/tencent.ts",
    "chars": 8914,
    "preview": "import { base64, hmacSha1Digest } from \"../../utils/crypto\";\nimport { TranslateService } from \"./base\";\nimport { getPref"
  },
  {
    "path": "src/modules/services/tencenttransmart.ts",
    "chars": 1570,
    "preview": "import type { TranslateService } from \"./base\";\n\nexport const TencentTransmart: TranslateService = {\n  id: \"tencenttrans"
  },
  {
    "path": "src/modules/services/webliodict.ts",
    "chars": 1387,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/xftrans.ts",
    "chars": 4459,
    "preview": "import { getString } from \"../../utils\";\nimport { base64, hmacSha256Digest, sha256Digest } from \"../../utils/crypto\";\nim"
  },
  {
    "path": "src/modules/services/youdao.ts",
    "chars": 796,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/youdaodict.ts",
    "chars": 1498,
    "preview": "import { TranslateService } from \"./base\";\n\nconst translate: TranslateService[\"translate\"] = async function (data) {\n  c"
  },
  {
    "path": "src/modules/services/youdaozhiyun.ts",
    "chars": 3159,
    "preview": "import { hex, sha256Digest } from \"../../utils/crypto\";\nimport { getPref } from \"../../utils/prefs\";\nimport { TranslateS"
  },
  {
    "path": "src/modules/services/youdaozhiyunllm.ts",
    "chars": 6658,
    "preview": "import { hex, sha256Digest } from \"../../utils/crypto\";\nimport { getPref } from \"../../utils/prefs\";\nimport { getString "
  },
  {
    "path": "src/modules/settings/manageKeys.ts",
    "chars": 2394,
    "preview": "import { getPrefJSON, setPref } from \"../../utils/prefs\";\nimport { getString } from \"../../utils/locale\";\n\nexport async "
  },
  {
    "path": "src/modules/settings/renameServices.ts",
    "chars": 3643,
    "preview": "import { getPref, setPref } from \"../../utils/prefs\";\nimport { getString } from \"../../utils/locale\";\n\nexport async func"
  },
  {
    "path": "src/modules/shortcuts.ts",
    "chars": 760,
    "preview": "const concatKey = Zotero.isMac ? \"Meta\" : \"Control\";\n\nexport function registerShortcuts() {\n  ztoolkit.Keyboard.register"
  },
  {
    "path": "src/modules/tabpanel.ts",
    "chars": 9425,
    "preview": "import { getLocaleID } from \"../utils/locale\";\nimport { config } from \"../../package.json\";\nimport { getPref, setPref } "
  },
  {
    "path": "src/utils/config.ts",
    "chars": 16398,
    "preview": "import { franc } from \"franc\";\nimport ISO6393_3_TO_2 from \"iso639-js/alpha3to2mapping.json\";\nimport ISO6393_MACRO_LANGS "
  },
  {
    "path": "src/utils/crypto.ts",
    "chars": 3376,
    "preview": "function base64(buffer: ArrayBuffer) {\n  const str = String.fromCharCode(...new Uint8Array(buffer));\n  return ztoolkit.g"
  },
  {
    "path": "src/utils/index.ts",
    "chars": 317,
    "preview": "export * from \"./config\";\nexport * from \"./crypto\";\nexport * from \"./llmPrompt\";\nexport * from \"./locale\";\nexport * from"
  },
  {
    "path": "src/utils/llmPrompt.ts",
    "chars": 1212,
    "preview": "import { getPref } from \"./prefs\";\nimport { TranslateTask } from \"./task\";\n\nexport function transformPromptWithContext(\n"
  },
  {
    "path": "src/utils/locale.ts",
    "chars": 2783,
    "preview": "import { config } from \"../../package.json\";\nimport { FluentMessageId } from \"../../typings/i10n\";\n\nexport { initLocale,"
  },
  {
    "path": "src/utils/mathRenderer.ts",
    "chars": 2656,
    "preview": "import katex from \"katex\";\n\n// Unified, robust math rendering helpers\n// Avoid lookbehind for broader engine compatibili"
  },
  {
    "path": "src/utils/prefs.ts",
    "chars": 2256,
    "preview": "import { config } from \"../../package.json\";\n\nexport {\n  getPref,\n  setPref,\n  clearPref,\n  getPrefJSON,\n  registerPrefO"
  },
  {
    "path": "src/utils/secret.ts",
    "chars": 1243,
    "preview": "import { getPrefJSON, setPref } from \"./prefs\";\n\nexport interface SecretValidateResult {\n  secret: string;\n  status: boo"
  },
  {
    "path": "src/utils/settingsDialog.ts",
    "chars": 14411,
    "preview": "import {\n  getPref,\n  PrefKeys,\n  PrefKeysWithBooleanValue,\n  PrefKeysWithNumberValue,\n  PrefKeysWithStringValue,\n  setP"
  },
  {
    "path": "src/utils/str.ts",
    "chars": 1376,
    "preview": "import { getString } from \"./locale\";\n\nexport function slice(str: string, len: number) {\n  return str.length > len ? `${"
  },
  {
    "path": "src/utils/task.ts",
    "chars": 11825,
    "preview": "import { inferLanguage, matchLanguage } from \"./config\";\nimport { getString } from \"./locale\";\nimport { getPref } from \""
  },
  {
    "path": "src/utils/wait.ts",
    "chars": 806,
    "preview": "export function waitUntil(\n  condition: () => boolean,\n  callback: () => void,\n  interval = 100,\n  timeout = 10000,\n) {\n"
  },
  {
    "path": "src/utils/window.ts",
    "chars": 349,
    "preview": "export { isWindowAlive, getFocusedWindow };\n\nfunction isWindowAlive(win?: Window) {\n  return win && !Components.utils.is"
  },
  {
    "path": "src/utils/ztoolkit.ts",
    "chars": 2295,
    "preview": "import {\n  BasicTool,\n  UITool,\n  ExtraFieldTool,\n  FieldHookManager,\n  KeyboardManager,\n  MenuManager,\n  PromptManager,"
  },
  {
    "path": "tsconfig.json",
    "chars": 143,
    "preview": "{\n  \"extends\": \"zotero-types/entries/sandbox\",\n  \"include\": [\"src\", \"typings\", \"node_modules/zotero-types\"],\n  \"exclude\""
  },
  {
    "path": "typings/global.d.ts",
    "chars": 1064,
    "preview": "declare const _globalThis: {\n  [key: string]: any;\n  Zotero: _ZoteroTypes.Zotero;\n  crypto: Crypto;\n  TextEncoder: typeo"
  },
  {
    "path": "typings/i10n.d.ts",
    "chars": 7213,
    "preview": "// Generated by zotero-plugin-scaffold\n/* prettier-ignore */\n/* eslint-disable */\n// @ts-nocheck\nexport type FluentMessa"
  },
  {
    "path": "typings/prefs.d.ts",
    "chars": 3624,
    "preview": "// Generated by zotero-plugin-scaffold\n/* prettier-ignore */\n/* eslint-disable */\n// @ts-nocheck\n\n// prettier-ignore\ndec"
  },
  {
    "path": "update-beta.json",
    "chars": 724,
    "preview": "{\n  \"addons\": {\n    \"zoteropdftranslate@euclpts.com\": {\n      \"updates\": [\n        {\n          \"version\": \"1.0.25\",\n    "
  },
  {
    "path": "update.json",
    "chars": 614,
    "preview": "{\n  \"addons\": {\n    \"zoteropdftranslate@euclpts.com\": {\n      \"updates\": [\n        {\n          \"version\": \"2.0.0\",\n     "
  },
  {
    "path": "update.rdf",
    "chars": 614,
    "preview": "{\n  \"addons\": {\n    \"zoteropdftranslate@euclpts.com\": {\n      \"updates\": [\n        {\n          \"version\": \"2.0.0\",\n     "
  },
  {
    "path": "zotero-plugin.config.ts",
    "chars": 1770,
    "preview": "import { defineConfig } from \"zotero-plugin-scaffold\";\nimport pkg from \"./package.json\";\nimport { copyFileSync } from \"f"
  }
]

About this extraction

This page contains the full source code of the windingwind/zotero-pdf-translate GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 128 files (445.3 KB), approximately 119.3k tokens, and a symbol index with 286 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!