Skip to content

Keep string constants when importing BibTeX into an existing library - #17957

Open
AnishKmSingh wants to merge 3 commits into
JabRef:mainfrom
AnishKmSingh:fix-17895-string-import-conflict
Open

AnishKmSingh wants to merge 3 commits into
JabRef:mainfrom
AnishKmSingh:fix-17895-string-import-conflict

Conversation

@AnishKmSingh

Copy link
Copy Markdown
Contributor

Summary

When importing a BibTeX file into an existing library, the @String constants of the imported file were dropped, because ImportResultsMerger only copied the entries. References such as journal = venue then resolved to the library's own venue, so the imported entry silently showed a different journal.

ImportResultsMerger now keeps the string constants of BibTeX imports. If a string with the same name but different content already exists, DatabaseMerger adds the imported one with a new name (e.g., venue_1, as before) and now also updates the references in the imported entries to that name.

The dialog to choose between the existing and the imported definition (suggested in the issue) will follow in a separate PR.

Follow-up PR: as suggested in the issue, I'd like to add a dialog in a separate PR so the user can decide what happens when a string name clashes, similar to "Import customized entry types". For each conflicting string, it would show the existing and the imported value and offer:

  • Keep both: add the imported string with a new name (the behaviour of this PR, used as the default),
  • Keep existing: ignore the imported definition, so imported entries use the library's one,
  • Use imported: replace the library's definition with the imported one.

Renaming only appends a suffix (e.g., aKopp → aKopp_1), so the string type prefix is kept. I kept this PR small so the data issue can be fixed first, and the dialog can be reviewed on its own.

Steps to test

  1. Create target.bib:

@string{venue = {Journal of Biology}}
@Article{Existing2025, title = {Existing biology paper}, journal = venue, year = {2025}}

  1. Create incoming.bib:

@string{venue = {Journal of Computer Science}}
@Article{Incoming2026, title = {Imported computer science paper}, journal = venue, year = {2026}}

  1. Open target.bib, then File → Import → Import into current library → incoming.bib → Import entries.
  2. The imported article shows "Journal of Computer Science" (journal = venue_1); the existing article still shows "Journal of Biology".

Before fix:

before_incoming bib before_incoming bib_02

After Fix:

after_journal_cs after_journal_cs02

Related issues and pull requests

Refs #17895

AI usage

Claude (Anthropic), Claude Opus 5.5 find the root cause (string constants dropped in ImportResultsMerger) and drafted the code, tests and CHANGELOG entry. I reproduced the bug, applied the changes, ran the tests locally, verified the fix manually in JabRef (screenshots above), and reviewed and understood all changes. I take full ownership of the code.

Checklist

  • I own the copyright of the code submitted and I license it under the MIT license
  • If AI tools were used, I disclosed them in the "AI usage" section and reviewed, understood, and take full ownership of all AI-generated code
  • I manually tested my changes in running JabRef (always required)
  • I added JUnit tests for changes (if applicable)
  • I added screenshots in the PR description (if change is visible to the user)
  • I added one sentence (max 20 words) to CHANGELOG.md describing the change from the user's point of view (if the change is visible to the user)
  • [/] I checked the user documentation for up to dateness and submitted a pull request to our user documentation repository

@github-actions github-actions Bot added size: medium component: import-load good second issue Issues that involve a tour of two or three interweaved components in JabRef labels Nov 28, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Preserve BibTeX string definitions and references during import

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Preserve BibTeX string constants when importing entries into an existing library.
• Rename conflicting definitions and update imported entries to retain their intended values.
• Add regression tests and document the user-visible fix.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The GUI import path and multi-file import aggregation both produce the same end-to-end outcome: imported entries and string definitions must resolve to the imported file's intended constants.
  • DatabaseMerger performs the shared transformation, while BibDatabase resolution and export consume the resulting entries and definitions.
  • These are implementation hops within one bounded BibTeX import integration, not independent capabilities.
Behavioral complexity 🟡 Medium 🧩 Coordinated invariants, Data transformation

  • Before: conflicting string definitions were renamed, but imported references were not consistently redirected.
  • After: the merger maintains a mapping from renamed string names and applies a regex transformation to every imported entry field and newly added string content.
  • New correctness condition: every reference to a renamed imported definition must be redirected while references to equal-content or unrelated definitions remain unchanged, including references nested inside imported string definitions and downstream consumers.
  • This is a coordinated invariant across stored entries and string definitions, plus a nontrivial text transformation; the existing database resolution and export mechanisms are reused rather than contributing their full complexity.
Potential damage 🟡 Medium 🩹 Incorrect results

  • Conditionally, if the changed rename-and-rewrite behavior produces an incorrect mapping or fails to preserve an imported definition, imported fields can resolve to the wrong journal, publisher, or other string value.
  • The affected behavior is the BibTeX import integration and its downstream resolution/export use, not unrelated database functionality.
  • Reverting code prevents new incorrect imports, but already imported and saved fields or renamed definitions may require locating affected records and repairing or reimporting them.
  • Revert stops further incorrect transformations.
  • Existing persisted entry references and string definitions may require targeted repair or reimport; downstream generated outputs can be regenerated after the database is corrected.
Assessed commit eb16518
Diagram

graph TD
  A["BibTeX imports"] --> B["Import results merger"] --> C["Database merger"] --> D[("Staged library")] --> E["Import entries"] --> F[("Current library")]
  C -- "rename references" --> D
  E -- "merge staged strings" --> F
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Prompt users to resolve each string conflict
  • ➕ Allows users to choose whether to keep both definitions or prefer either value.
  • ➖ Adds UI and interaction complexity before the silent data issue is fixed.
  • ➖ Requires a default for unattended or multi-file imports.

Recommendation: Keep the existing suffix-based conflict policy and update references as this PR does; it fixes the silent value change without expanding the import UI. Consider interactive conflict choices separately, as proposed in the follow-up.

Files changed (5) +107 / -1

Bug fix (2) +35 / -1
DatabaseMerger.javaRetarget incoming references when string names conflict +30/-0

Retarget incoming references when string names conflict

• Records new names assigned to conflicting string constants and replaces matching references in incoming entry fields. Identical definitions remain unchanged.

jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java

ImportResultsMerger.javaRetain BibTeX strings in staged import results +5/-1

Retain BibTeX strings in staged import results

• Merges string constants from BibTeX parser results into the combined import database alongside entries and metadata. This makes the definitions available when entries are imported into an existing library.

jablib/src/main/java/org/jabref/logic/importer/util/ImportResultsMerger.java

Tests (2) +71 / -0
DatabaseMergerTest.javaTest reference handling for conflicting and identical strings +31/-0

Test reference handling for conflicting and identical strings

• Adds tests confirming that a conflicting definition redirects incoming references to its suffixed name and that an identical definition leaves references unchanged.

jablib/src/test/java/org/jabref/logic/database/DatabaseMergerTest.java

ImportResultsMergerTest.javaTest preservation of imported BibTeX strings +40/-0

Test preservation of imported BibTeX strings

• Adds a test confirming that a staged BibTeX import retains its string definition and the entry's reference to it.

jablib/src/test/java/org/jabref/logic/importer/util/ImportResultsMergerTest.java

Documentation (1) +1 / -0
CHANGELOG.mdDocument the BibTeX string import fix +1/-0

Document the BibTeX string import fix

• Adds a user-facing note explaining that imported string constants are no longer dropped.

CHANGELOG.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (4)

Grey Divider


Remediation recommended

1. Escaped hashes change in imported text 🐞 Bug ⭐ New
Description
replaceStringReferences treats an escaped opening hash in \#venue# as the start of a string
reference and rewrites the literal text. When an imported venue conflicts with the library’s
definition, importing a field containing that text changes it to \#venue_1# even though the field
does not reference the string.
Code

jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java[R152-155]

+        return STRING_REFERENCE.matcher(text).replaceAll(match -> {
+            String name = match.group(1);
+            String newName = renamedStrings.getOrDefault(name.toLowerCase(Locale.ROOT), name);
+            return Matcher.quoteReplacement("#" + newName + "#");
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new reference replacement rewrites literal text whose opening hash is escaped, such as `\#venue#`, when a string name collides.

## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java[34-35]
- jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java[151-156]

## Recommended Fix
Make reference matching skip escaped opening hashes, consistent with `FieldWriter`’s hash-delimiter handling. Add a regression test that merges a conflicting string and verifies an imported field containing `\#venue#` remains unchanged.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (3)
2. Crawl results gain broken references 🐞 Bug
Description
mergeStrings now changes fields on entries in its other database, and DatabaseMerger.merge
retains those same objects in the target. StudyRepository.persistResults merges a fetcher database
into its existing result and then reuses it for an aggregate; if the first merge renames a
conflicting string, the aggregate can receive the rewritten entry reference without the
correspondingly renamed definition.
Code

jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java[118]

+        updateStringReferences(other.getEntries(), renamedStrings);
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A string collision changes source entries during a merge, so later merges of the same source can carry references to definitions they do not contain.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java[47-59]
- jablib/src/main/java/org/jabref/logic/database/DatabaseMerger.java[118-138]
- jablib/src/main/java/org/jabref/logic/crawler/StudyRepository.java[397-416]
## Recommended Fix
Keep the merge source reusable: rewrite copies of entries inserted into the target, or otherwise isolate the rename from the source database. Test consecutive merges of one source after a collision in only the first target.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Unselected imports add string constants 🐞 Bug
Description
ImportResultsMerger now collects constants from every parsed BibTeX file, while
ImportEntriesViewModel.importEntries merges every collected constant before handing over only
entriesToImport. If the user deselects an entry or a duplicate is rejected, definitions belonging
solely to that discarded material are still added to the library.
Code

jablib/src/main/java/org/jabref/logic/importer/util/ImportResultsMerger.java[45]

+                databaseMerger.mergeStrings(resultDatabase, parserResult.getDatabase());
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The import dialog adds constants from the complete parsed result even when their entries are not imported.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/util/ImportResultsMerger.java[34-46]
- jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java[203-244]
## Recommended Fix
Merge only definitions needed by entries that will actually be imported, including their transitive string references, after selection and duplicate decisions. Test deselecting an entry whose file defines an otherwise unused string.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Undo leaves imported constants behind 🐞 Bug
Description
The new ImportResultsMerger.mergeStrings call makes BibTeX constants available for the dialog's
target merge, which adds them directly to the database outside the entry import's undo edit. Undoing
an import therefore removes its entries but leaves its newly added constants in the library.
Code

jablib/src/main/java/org/jabref/logic/importer/util/ImportResultsMerger.java[45]

+                databaseMerger.mergeStrings(resultDatabase, parserResult.getDatabase());
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Undoing imported entries does not undo the BibTeX constants added for those entries.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/util/ImportResultsMerger.java[40-46]
- jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java[213-244]
- jabgui/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java[441-450]
## Recommended Fix
Record string additions and renames in the same undoable import operation as entry insertion. Test undo and redo after importing a file with a new constant and one with a conflicting constant.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Resolved findings
1. Imported aliases use the wrong value ✓ Resolved High Bug
Description
mergeStrings skips an imported alias when its text matches an existing alias, even if another
string it references has been renamed. If both libraries define alias = #venue# but define venue
differently, an imported entry using #alias# resolves through the existing library's venue.

2. Indirect strings resolve to wrong values ✓ Resolved High Bug
Description
mergeStrings copies imported string contents unchanged and updateStringReferences rewrites only
entry fields, leaving references inside imported string definitions pointed at the old name. When an
imported definition is renamed after a collision, another imported definition that refers to it
resolves through the target library's definition instead.

3. Mixed-case references use wrong values ✓ Resolved High Bug
Description
updateStringReferences looks up reference labels in renamedStrings with exact-case
Map.getOrDefault, although string resolution compares labels case-insensitively. If an imported
venue is renamed after a collision but its entry refers to #VENUE#, that reference stays
unchanged and resolves to the target's venue.

4. Choosing another library misplaces strings ✓ Resolved High Bug
Description
The new mergeStrings call populates the combined import result with BibTeX constants, but
ImportEntriesViewModel.importEntries later merges those constants into its original
databaseContext rather than selectedDb. When the user chooses another library in the import
dialog, the entries go to that library while their constants go to the original one.

5. Case-only names can use the wrong value ✓ Resolved Medium Bug
Description
mergeStrings records rename keys without regard to case but checks collisions with
hasStringByName, which compares names case-sensitively. When two BibTeX files define Venue and
venue with different contents, the new combined-import path retains both, and resolving either
reference can select the other file's definition.

Grey Divider

Tip of the day
💡 Did you know, you can see how risky a PR is at a glance with blast radius labels

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@github-actions github-actions Bot added the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 28, 2026
@github-actions github-actions Bot added status: changes-required Pull requests that are not yet complete and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 30, 2026
@doraem-on

Copy link
Copy Markdown
Contributor

Nice work overall fix is fine , kindly check these

@github-actions github-actions Bot removed the status: changes-required Pull requests that are not yet complete label Dec 2, 2026
@AnishKmSingh

Copy link
Copy Markdown
Contributor Author

@doraem-on
Thanks for the review. I addressed all three points in 8abcc66.

@github-actions github-actions Bot added the status: changes-required Pull requests that are not yet complete label Dec 2, 2026
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: changes-required Pull requests that are not yet complete labels Dec 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: import-load good second issue Issues that involve a tour of two or three interweaved components in JabRef size: medium status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants