Skip to content
Merged
Show file tree
Hide file tree
Changes from 50 commits
Commits
Show all changes
81 commits
Select commit Hold shift + click to select a range
7cdc3af
Refactor: extracted 3 methods from guiActionInsertEntry for file read…
sam-r914 Mar 20, 2026
48f8eb4
Refactor: extracted two methods from guiActionUpdateDocument() for re…
amanda-d-e Mar 20, 2026
5870f9d
Merge remote-tracking branch 'origin/fixes-for-issue-11829' into fixe…
amanda-d-e Mar 20, 2026
de7dd85
Refactor: fixed file formatting
amanda-d-e Mar 20, 2026
33689a4
Refactor: replaced magic strings with constants
amanda-d-e Mar 25, 2026
f518aac
Refactor: Replaced duplicated string content with associated variable
sam-r914 Mar 25, 2026
e5e218a
Refactor: replaced magic strings with constants
amanda-d-e Mar 25, 2026
3e5877c
Merge remote-tracking branch 'origin/fixes-for-issue-11829' into fixe…
amanda-d-e Mar 25, 2026
ca13ca0
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 25, 2026
93a78a6
Merge branch 'main' into fixes-for-issue-11829
anuv-bit Mar 26, 2026
1ab2595
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 27, 2026
16ba9e8
Refactor: replaced magic strings with constants
amanda-d-e Mar 27, 2026
13c7f4d
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 27, 2026
618a6b4
Merge remote-tracking branch 'origin/fixes-for-issue-11829' into fixe…
amanda-d-e Mar 27, 2026
f6b3709
Refactor: revert error titles
amanda-d-e Mar 27, 2026
d1cffb6
Refactor: revert error titles
amanda-d-e Mar 27, 2026
b857f68
Refactor: update helper function names, add documentation
amanda-d-e Mar 27, 2026
7b4ec49
Refactor: update helper function names, add documentation
amanda-d-e Mar 27, 2026
2e9cd37
Merge remote-tracking branch 'origin/fixes-for-issue-11829' into fixe…
amanda-d-e Mar 27, 2026
7f807e2
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 27, 2026
6b2de1f
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 28, 2026
d08ed3d
Refactor: revert missed errorTitle
amanda-d-e Mar 28, 2026
734bf9d
Refactor: extract additional method from guiActionUpdateDocument, ren…
amanda-d-e Mar 28, 2026
0751f17
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 28, 2026
c552f58
Refactor: revert runtime exception back to OOError statement
sam-r914 Mar 30, 2026
2d0e663
Merge branch 'JabRef:main' into fixes-for-issue-11829
anuv-bit Mar 31, 2026
ff016c5
Refactor: use streams and Optional chaining in OOBibBase and OpenOffi…
anuv-bit Mar 31, 2026
13f49ab
Refactor: adjust position of syncOptions statement into if block
sam-r914 Mar 31, 2026
59bc3ec
Merge branch 'JabRef:main' into fixes-for-issue-11829
anuv-bit Mar 31, 2026
ed2a2a2
Fix immutable list issue and fixed line space
anuv-bit Mar 31, 2026
6a4e06e
Use ArrayList::new to explicitly guarantee mutable list
anuv-bit Mar 31, 2026
272b074
Refactor: standardize usage of runtime error exception throwing to OO…
sam-r914 Mar 31, 2026
eb13470
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Mar 31, 2026
69c9671
Refactor: remove unused and duplicated method getXTextDocumentOrThrow…
sam-r914 Mar 31, 2026
dbdd05d
Merge branch 'fixes-for-issue-11829' of https://github.com/anuv-bit/j…
sam-r914 Mar 31, 2026
d3914c1
Merge branch 'main' into fixes-for-issue-11829
sam-r914 Mar 31, 2026
0b66b9f
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 1, 2026
cbb41e0
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 1, 2026
b260df5
Refactor: replace magic strings with constants in backend
amanda-d-e Apr 1, 2026
562cb7d
Refactor: fix documentation
amanda-d-e Apr 1, 2026
83a2429
Merge branch 'JabRef:main' into fixes-for-issue-11829
anuv-bit Apr 2, 2026
16b2939
Refactor: extract method refactoring, extract getStringForFillCursor …
sam-r914 Apr 2, 2026
bb13c26
Refactor:Remove FAIL constants and inline Optional.empty() in OOBibBase
anuv-bit Apr 2, 2026
85d38c7
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 3, 2026
57db384
Refactor: extract method
amanda-d-e Apr 3, 2026
e479a65
Refactor: remove unused methods
amanda-d-e Apr 3, 2026
17366a2
Refactor: extract method
amanda-d-e Apr 3, 2026
66768cf
Refactor: remove unused method parameter
amanda-d-e Apr 3, 2026
16ac73b
Refactor: extract method
amanda-d-e Apr 3, 2026
7e8f94d
Refactor: fix formatting
amanda-d-e Apr 3, 2026
ce2289a
Refactor: extract method
amanda-d-e Apr 3, 2026
7cb6768
Revert "Refactor: extract method"
amanda-d-e Apr 3, 2026
24b00f4
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 3, 2026
7d527d6
Refactor: revert extract method
amanda-d-e Apr 3, 2026
0c834b4
Merge branch 'JabRef:main' into fixes-for-issue-11829
anuv-bit Apr 3, 2026
c637726
Refactor: extract duplicate logic into method
amanda-d-e Apr 3, 2026
588b4c6
Merge remote-tracking branch 'origin/fixes-for-issue-11829' into fixe…
amanda-d-e Apr 3, 2026
b8c44c3
Revert: restore internalName.get() per reviewer feedback
anuv-bit Apr 3, 2026
0aa82de
Revert: Refactor: extract method refactoring, extract getStringForFil…
sam-r914 Apr 3, 2026
793d4dd
Revert: revert extracted method performPreInsertionChecks
sam-r914 Apr 4, 2026
3671985
Refactor: fix unlocalized OOError and code formatting
sam-r914 Apr 4, 2026
8bcab01
Fix: replace IllegalStateException throws with safe returns in EditMerge
anuv-bit Apr 4, 2026
8d965bb
Fix: formatting in EditMerge
anuv-bit Apr 4, 2026
4d74798
Revert: changes to revert NamedRangeReferenceMark.java back to origin…
sam-r914 Apr 4, 2026
f046095
Revert: format changes to revert NamedRangeReferenceMark.java back to…
sam-r914 Apr 4, 2026
f4c73d5
Refactor: fix CSLFormatUtils.changeToInText precondition violation
amanda-d-e Apr 4, 2026
9c871e0
Fix: fixing cosmetic and semantic issues
sam-r914 Apr 7, 2026
23b43b0
Merge branch 'main' into fixes-for-issue-11829
sam-r914 Apr 7, 2026
0d28a32
Fix: make generateCitation calls consistent format
anuv-bit Apr 8, 2026
3c7015b
Merge branch 'JabRef:main' into fixes-for-issue-11829
anuv-bit Apr 8, 2026
84fe9ad
Update jablib/src/main/java/org/jabref/logic/openoffice/oocsltext/CSL…
anuv-bit Apr 8, 2026
0179d92
Fix: improve javadoc comment for createCitation helper method
anuv-bit Apr 8, 2026
d363569
Merge branch 'JabRef:main' into fixes-for-issue-11829
anuv-bit Apr 9, 2026
72aa46d
Fix: rename helper methods and update javadoc comments
anuv-bit Apr 9, 2026
c87eee4
Fix: rename helper methods and update variable names
anuv-bit Apr 9, 2026
dfb0bac
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 11, 2026
27b9b6d
Revert 'performPreUpdateChecks()' method extraction
amanda-d-e Apr 11, 2026
62a666c
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 12, 2026
329c93f
Merge branch 'main' into fixes-for-issue-11829
sam-r914 Apr 13, 2026
8ad1e37
Merge branch 'JabRef:main' into fixes-for-issue-11829
amanda-d-e Apr 16, 2026
1484221
Merge branch 'main' into fixes-for-issue-11829
subhramit Apr 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
484 changes: 280 additions & 204 deletions jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBase.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -218,19 +218,10 @@ public boolean isDocumentConnectionMissing() {
return false;
}

/// Either return a valid XTextDocument or throw NoDocumentException.
public XTextDocument getXTextDocumentOrThrow()
throws
NoDocumentException {
if (isDocumentConnectionMissing()) {
throw new NoDocumentException("Not connected to document");
}
return this.xTextDocument;
}
Comment thread
subhramit marked this conversation as resolved.

/// Returns either a valid XTextDocument in OOResult or a NoDocumentException error
public OOResult<XTextDocument, OOError> getXTextDocument() {
if (isDocumentConnectionMissing()) {
return OOResult.error(OOError.from(new NoDocumentException()));
return OOResult.error(OOError.from(new NoDocumentException("Not connected to document")));
Copy link
Copy Markdown
Collaborator

@pluto-han pluto-han Apr 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to add error message. OOError.from() already handles it.

}
return OOResult.ok(this.xTextDocument);
}
Expand Down
67 changes: 36 additions & 31 deletions jabgui/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,8 @@ private void initPanel() {
ooBase.guiActionSelectDocument(false);
} catch (WrappedTargetException
| NoSuchElementException ex) {
throw new RuntimeException(ex);
LOGGER.warn("Unable to select document to work on", ex);
OOError.fromMisc(ex).setTitle("Unable to select document to work on").showErrorDialog(dialogService);
}
});

Expand Down Expand Up @@ -348,23 +349,23 @@ private void exportEntries() {
}

private List<BibDatabase> getBaseList() {
List<BibDatabase> databases = new ArrayList<>();
if (openOfficePreferences.getUseAllDatabases()) {
for (BibDatabaseContext database : stateManager.getOpenDatabases()) {
databases.add(database.getDatabase());
}
} else {
databases.add(stateManager.getActiveDatabase()
.map(BibDatabaseContext::getDatabase)
.orElse(new BibDatabase()));
return new ArrayList<>(stateManager.getOpenDatabases().stream()
.map(BibDatabaseContext::getDatabase)
.toList());
}

return databases;
return new ArrayList<>(List.of(
stateManager.getActiveDatabase()
.map(BibDatabaseContext::getDatabase)
.orElseGet(BibDatabase::new)));
}

private void connectAutomatically() {
DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(openOfficePreferences, dialogService);

final String errorTitle = Localization.lang("Autodetection failed");
final String progressMessage = Localization.lang("Autodetecting paths...");

if (officeInstallation.isExecutablePathDefined()) {
connect();
} else {
Expand All @@ -386,9 +387,9 @@ protected List<Path> call() {
}
});

taskConnectIfInstalled.setOnFailed(_ -> dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), taskConnectIfInstalled.getException()));
taskConnectIfInstalled.setOnFailed(_ -> dialogService.showErrorDialogAndWait(errorTitle, errorTitle, taskConnectIfInstalled.getException()));

dialogService.showProgressDialog(Localization.lang("Autodetecting paths..."), Localization.lang("Autodetecting paths..."), taskConnectIfInstalled);
dialogService.showProgressDialog(progressMessage, progressMessage, taskConnectIfInstalled);
taskExecutor.execute(taskConnectIfInstalled);
}
}
Expand All @@ -397,6 +398,9 @@ private void connectManually() {
DirectoryDialogConfiguration fileDialogConfiguration = new DirectoryDialogConfiguration.Builder().withInitialDirectory(System.getProperty("user.home")).build();
Optional<Path> selectedPath = dialogService.showDirectorySelectionDialog(fileDialogConfiguration);

final String errorTitle = Localization.lang("Could not connect to running OpenOffice/LibreOffice.");
final String extendedErrorTitle = Localization.lang("If connecting manually, please verify program and library paths.");

DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(openOfficePreferences, dialogService);

if (selectedPath.isPresent()) {
Expand All @@ -406,12 +410,12 @@ private void connectManually() {
if (value) {
connect();
} else {
dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("If connecting manually, please verify program and library paths."));
dialogService.showErrorDialogAndWait(errorTitle, extendedErrorTitle);
}
})
.executeWith(taskExecutor);
} else {
dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("If connecting manually, please verify program and library paths."));
dialogService.showErrorDialogAndWait(errorTitle, extendedErrorTitle);
}
}

Expand Down Expand Up @@ -440,6 +444,11 @@ private void updateButtonAvailability() {
}

private void connect() {
final String connectionError = Localization.lang("Could not connect to running OpenOffice/LibreOffice.");
final String autodetectionFailedError = Localization.lang("Autodetection failed");
final String progressMessage = Localization.lang("Autodetecting paths...");
final String loggerMessage = "Could not connect to running OpenOffice/LibreOffice";

Task<OOBibBase> connectTask = new Task<>() {
@Override
protected OOBibBase call() throws BootstrapException, CreationException, IOException, InterruptedException {
Expand All @@ -457,7 +466,9 @@ protected OOBibBase call() throws BootstrapException, CreationException, IOExcep
ooBase.guiActionSelectDocument(true);
} catch (WrappedTargetException
| NoSuchElementException e) {
throw new RuntimeException(e);
LOGGER.warn("Unable to connect to document", e);
OOError.fromMisc(e).setTitle("Unable to connect to document").showErrorDialog(dialogService);
return;
Comment thread
qodo-free-for-open-source-projects[bot] marked this conversation as resolved.
}

// Enable actions that depend on a connection
Expand All @@ -469,16 +480,16 @@ protected OOBibBase call() throws BootstrapException, CreationException, IOExcep
LOGGER.error("autodetect failed", ex);
switch (ex) {
case UnsatisfiedLinkError unsatisfiedLinkError -> {
LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", unsatisfiedLinkError);
LOGGER.warn(loggerMessage, unsatisfiedLinkError);

dialogService.showErrorDialogAndWait(Localization.lang("Unable to connect. One possible reason is that JabRef "
+ "and OpenOffice/LibreOffice are not both running in either 32 bit mode or 64 bit mode."));
}
case IOException ioException -> {
LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ioException);
LOGGER.warn(loggerMessage, ioException);

dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."),
Localization.lang("Could not connect to running OpenOffice/LibreOffice.")
dialogService.showErrorDialogAndWait(connectionError,
connectionError
+ "\n"
+ Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n"
+ Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"),
Expand All @@ -490,11 +501,11 @@ protected OOBibBase call() throws BootstrapException, CreationException, IOExcep
}
case null,
default ->
dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex);
dialogService.showErrorDialogAndWait(autodetectionFailedError, autodetectionFailedError, ex);
}
});

dialogService.showProgressDialog(Localization.lang("Autodetecting paths..."), Localization.lang("Autodetecting paths..."), connectTask);
dialogService.showProgressDialog(progressMessage, progressMessage, connectTask);
taskExecutor.execute(connectTask);
}

Expand Down Expand Up @@ -588,15 +599,9 @@ private void pushEntries(CitationType citationType, boolean addPageInfo) {
/// @return true if all entries have citation keys, if it so may be after generating them
private boolean checkThatEntriesHaveKeys(List<BibEntry> entries) {
// Check if there are empty keys
boolean emptyKeys = false;
for (BibEntry entry : entries) {
if (entry.getCitationKey().isEmpty()) {
// Found one, no need to look further for now
emptyKeys = true;
break;
}
}

// Found one, no need to look further for now
boolean emptyKeys = entries.stream()
Comment thread
anuv-bit marked this conversation as resolved.
.anyMatch(entry -> entry.getCitationKey().isEmpty());
// If no empty keys, return true
if (!emptyKeys) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe
return false;
}

final String exceptionTitle = "MergeCitationGroups failed";
final String loggerMessage = "MergeCitationGroups: cursorBetween.end != currentGroupCursor.end";

Objects.requireNonNull(state.currentGroupCursor);
Objects.requireNonNull(state.cursorBetween);
Objects.requireNonNull(state.prev);
Expand Down Expand Up @@ -187,14 +190,21 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe

// assume: currentGroupCursor.getEnd() == cursorBetween.getEnd()
if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {
LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end");
throw new IllegalStateException("MergeCitationGroups failed");
LOGGER.warn(loggerMessage);
throw new IllegalStateException(exceptionTitle);
Comment thread
qodo-free-for-open-source-projects[bot] marked this conversation as resolved.
Outdated
}

/*
* Try to expand state.currentGroupCursor and state.cursorBetween by going right to reach
* rangeStart.
*/
Comment on lines -194 to -197
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment should not be lost

return checkCouldExpand(state, currentRange, loggerMessage, exceptionTitle);
}

/// Helper method for checkAddToGroup. Tries to expand state.currentGroupCursor and state.cursorBetween by going right to reach rangeStart.
///
/// @param state The CitationGroup to test.
/// @param currentRange The XTextRange corresponding to group.
/// @param loggerMessage The failure message for the LOGGER.
/// @param exceptionTitle The custom exception message.
/// @return false if cannot expand, true if can.
private static boolean checkCouldExpand(ScanState state, XTextRange currentRange, String loggerMessage, String exceptionTitle) {
XTextRange rangeStart = currentRange.getStart();
boolean couldExpand = true;
XTextCursor thisCharCursor =
Expand All @@ -219,11 +229,10 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe

// These two should move in sync:
if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {
LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)");
throw new IllegalStateException("MergeCitationGroups failed");
LOGGER.warn(loggerMessage + " (during expand)");
throw new IllegalStateException(exceptionTitle);
}
}

return couldExpand;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,13 @@ public XTextCursor getFillCursor(XTextDocument doc)
if (fullText.length() < 2) {
throw new IllegalStateException("getFillCursor: fullText.length() < 2 (after loop)'%n");
}

// NamedRangeReferenceMark.checkFillCursor(beta);
return getStringForFillCursor(full, fullText, debugThisFun);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the point of this comment?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like its a statement that i happened to miss when extracting

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need this refactoring?

Reasons:

  1. This method is called only once.

  2. New method name is misleading. "getString" but return XTextCursor?

  3. Meaningless comment.

This feels like a refactoring for the sake of refactoring.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair enough. i am really bad at naming methods honestly. ill work on reverting this change

}

/// Helper method for getFillCursor
public XTextCursor getStringForFillCursor(XTextCursor full, String fullText, boolean debugThisFun) {
XTextCursor beta = full.getText().createTextCursorByRange(full);
beta.collapseToStart();
beta.goRight((short) 1, false);
Expand Down Expand Up @@ -311,8 +318,6 @@ public XTextCursor getFillCursor(XTextDocument doc)
LOGGER.debug("getFillCursor: omega(8) covers '{}', should be '{}'", omega.getString(), right);
}
}

// NamedRangeReferenceMark.checkFillCursor(beta);
return beta;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ public List<RangeForOverlapCheck<CitationGroupId>> viewCursorRanges(XTextDocumen
///
/// Note: Here we directly communicate to the document, not through the backend. This is because mapping ranges to footnote marks does not depend on how do we mark or structure those ranges.
public List<RangeForOverlapCheck<CitationGroupId>>
footnoteMarkRanges(XTextDocument doc, List<RangeForOverlapCheck<CitationGroupId>> citationRanges) {
footnoteMarkRanges(List<RangeForOverlapCheck<CitationGroupId>> citationRanges) {
Comment thread
subhramit marked this conversation as resolved.
// We partition by XText and use a single range from
// each partition to get at the corresponding footnotemark range.

Expand Down Expand Up @@ -402,7 +402,7 @@ static String rangeOverlapsToMessage(List<RangeOverlap<RangeForOverlapCheck<Cita
// ranges.addAll(userRanges);
ranges.addAll(bibliographyRanges(doc));
ranges.addAll(citationRanges);
ranges.addAll(footnoteMarkRanges(doc, citationRanges));
ranges.addAll(footnoteMarkRanges(citationRanges));

List<RangeOverlap<RangeForOverlapCheck<CitationGroupId>>> overlaps =
RangeOverlapBetween.findFirst(doc,
Expand Down Expand Up @@ -432,7 +432,7 @@ public OOVoidResult<JabRefException> checkRangeOverlaps(XTextDocument doc,
ranges.addAll(userRanges);
ranges.addAll(bibliographyRanges(doc));
ranges.addAll(citationRanges);
ranges.addAll(footnoteMarkRanges(doc, citationRanges));
ranges.addAll(footnoteMarkRanges(citationRanges));

List<RangeOverlap<RangeForOverlapCheck<CitationGroupId>>> overlaps =
RangeOverlapWithin.findOverlappingRanges(doc, ranges, requireSeparation, reportAtMost);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,34 +320,7 @@ private void updateAllCitationsWithNewStyle(CitationStyle style, CSLCitationType
StringBuilder finalText = new StringBuilder();
Iterator<BibEntry> iterator = entries.iterator();

while (iterator.hasNext()) {
BibEntry currentEntry = iterator.next();

// We re-generate the citation in the new style and update it in the document
String newCitation;

if (isAlphaNumericStyle) {
newCitation = CSLFormatUtils.generateAlphanumericInTextCitation(currentEntry, unifiedBibDatabaseContext);
} else {
newCitation = CitationStyleGenerator.generateCitation(List.of(currentEntry), style.getSource(), HTML_OUTPUT_FORMAT, unifiedBibDatabaseContext, bibEntryTypesManager);
}

String formattedCitation = CSLFormatUtils.transformHTML(newCitation);

if (isNumericStyle) {
formattedCitation = updateSingleOrMultipleCitationNumbers(formattedCitation, List.of(currentEntry));
String prefix = CSLFormatUtils.generateAuthorPrefix(currentEntry, unifiedBibDatabaseContext);
formattedCitation = prefix + formattedCitation;
} else if (!isAlphaNumericStyle) {
formattedCitation = CSLFormatUtils.changeToInText(formattedCitation);
}

finalText.append(formattedCitation);

if (iterator.hasNext()) {
finalText.append(",");
}
}
updateCitations(style, iterator, unifiedBibDatabaseContext, finalText);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about this, updateCitations is called only once.
My idea: insertCitation, insertInTextCitation and updateAllCitationsWithNewStyle share a bit of logic, you can extract those lines into a new method.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello, thank you for the suggestion. I have reverted the initial refactoring and extracted duplicate logic from those three methods in 'CSLCitationOOAdapter'.


markManager.updateMarkAndTextWithNewStyle(mark, finalText.toString(), CSLCitationType.IN_TEXT);
}
Expand Down Expand Up @@ -377,6 +350,46 @@ private void updateAllCitationsWithNewStyle(CitationStyle style, CSLCitationType
}
}

/// Helper method for updateAllCitationsWithNewStyle.
///
/// @param style The current style we are using.
/// @param iterator Used to iterate through entries.
/// @param unifiedBibDatabaseContext Used to generate citations.
/// @param finalText Resulting text for updated citations.
private void updateCitations(CitationStyle style, Iterator<BibEntry> iterator, BibDatabaseContext unifiedBibDatabaseContext, StringBuilder finalText) {
boolean isAlphaNumericStyle = style.isAlphanumericStyle();
boolean isNumericStyle = style.isNumericStyle();

while (iterator.hasNext()) {
BibEntry currentEntry = iterator.next();

// We re-generate the citation in the new style and update it in the document
String newCitation;

if (isAlphaNumericStyle) {
newCitation = CSLFormatUtils.generateAlphanumericInTextCitation(currentEntry, unifiedBibDatabaseContext);
} else {
newCitation = CitationStyleGenerator.generateCitation(List.of(currentEntry), style.getSource(), HTML_OUTPUT_FORMAT, unifiedBibDatabaseContext, bibEntryTypesManager);
}

String formattedCitation = CSLFormatUtils.transformHTML(newCitation);

if (isNumericStyle) {
formattedCitation = updateSingleOrMultipleCitationNumbers(formattedCitation, List.of(currentEntry));
String prefix = CSLFormatUtils.generateAuthorPrefix(currentEntry, unifiedBibDatabaseContext);
formattedCitation = prefix + formattedCitation;
} else if (!isAlphaNumericStyle) {
formattedCitation = CSLFormatUtils.changeToInText(formattedCitation);
}

finalText.append(formattedCitation);

if (iterator.hasNext()) {
finalText.append(",");
}
}
}

/// Checks if an entry has already been cited before in the document.
/// Required for consistent numbering of numeric citations - if present, the number is to be reused, else a new number is to be assigned.
public boolean isCitedEntry(BibEntry entry) {
Expand Down
Loading