Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
68 changes: 16 additions & 52 deletions bibtexparser/splitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from collections.abc import Iterator

from .exceptions import BlockAbortedException
from .exceptions import ParserStateException
from .library import Library
from .model import DuplicateFieldKeyBlock
from .model import Entry
Expand Down Expand Up @@ -200,52 +199,26 @@ def _move_to_closing_delimiter(self, track_quotes: bool) -> int:
end_index=m.start() - 1,
)

def _move_to_comma_or_closing_delimiter(
self, currently_quote_escaped: bool = False, num_open_curls: int = 0
) -> int:
"""Index of the end of the field, taking quote-escape into account."""

if num_open_curls > 0 and currently_quote_escaped:
raise ParserStateException(
message="Internal error in parser. "
"Found a field-value that is both quote-escaped and curly-escaped. "
"Please report this bug."
)
def _move_to_comma_or_closing_delimiter(self) -> int:
"""Index of the end of the field, outside quotes and brace groups."""
in_quotes = False
brace_depth = 0

def _is_escaped():
return currently_quote_escaped or num_open_curls > 0
return in_quotes or brace_depth > 0

# iterate over marks until we find end of field
while True:
next_mark = self._next_mark(accept_eof=False)

# Handle "escape" characters
if next_mark.group(0) == '"' and not num_open_curls > 0:
# Check for {"} escape sequence when inside quotes (issue #487).
# Per https://tug.ctan.org/info/bibtex/tamethebeast/ttb_en.pdf,
# {"} represents a literal quote in a quoted field.
# We verify this by checking:
# 1. We're inside quotes
# 2. The " is surrounded by { and }
# 3. There's more content after the } (i.e., pos+2 is in bounds)
# This distinguishes {"} escapes from cases like @article{"}
# where " closes the field and } closes the entry.
if currently_quote_escaped:
pos = next_mark.start()
if (
pos > 0
and pos + 2 < len(self.bibstr)
and self.bibstr[pos - 1] == "{"
and self.bibstr[pos + 1] == "}"
):
continue
currently_quote_escaped = not currently_quote_escaped
# A quote inside a brace group is literal, even in a quoted value.
if next_mark.group(0) == '"' and brace_depth == 0:
in_quotes = not in_quotes
continue
elif next_mark.group(0) == "{" and not currently_quote_escaped:
num_open_curls += 1
elif next_mark.group(0) == "{":
brace_depth += 1
continue
elif next_mark.group(0) == "}" and not currently_quote_escaped and num_open_curls > 0:
num_open_curls -= 1
elif next_mark.group(0) == "}" and brace_depth > 0:
brace_depth -= 1
continue

# Check for end of field
Expand All @@ -264,10 +237,10 @@ def _is_escaped():
elif next_mark.group(0).startswith("@") and self._is_at_line_start(next_mark.start()):
self._unaccepted_mark = next_mark

if currently_quote_escaped:
looking_for = '`"`'
elif num_open_curls > 0:
if brace_depth > 0:
looking_for = "`}`"
elif in_quotes:
looking_for = '`"`'
else:
looking_for = f"`,` or `{self._closing_delimiter}`"

Expand Down Expand Up @@ -310,9 +283,7 @@ def _move_to_end_of_entry(self, first_key_start: int) -> tuple[list[Field], int,
start_line = self._current_line
key_end = equals_mark.start()
value_start = equals_mark.end()
value_end = self._move_to_comma_or_closing_delimiter(
currently_quote_escaped=False, num_open_curls=0
)
value_end = self._move_to_comma_or_closing_delimiter()

key = self.bibstr[key_start:key_end].strip()
value = self.bibstr[value_start:value_end].strip()
Expand Down Expand Up @@ -397,13 +368,6 @@ def split(self) -> Library:
fail_on_duplicate_key=False,
)

except ParserStateException as e:
# This is a bug in the parser, not in the bibtex. We should not continue.
logger.error(
"python-bibtexparser detected an invalid state. Please report this bug."
)
logger.error(e.message)
raise
except Exception:
# For unknown exceptions, we want to fail hard and get the info in our issue tracker.
logger.error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
id="at_sign_followed_by_brace",
),
pytest.param(
'@article{test, title = "BibTeX entries start with @article{"}',
'@article{test, title = "BibTeX entries start with @article{}"}',
"test",
"title",
"@article{",
Expand Down
13 changes: 13 additions & 0 deletions tests/splitter_tests/test_splitter_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,3 +392,16 @@ def test_entry_without_dangling_key_is_not_aborted(entry: str):
assert len(library.entries) == 1
assert len(library.entries[0].fields) == 1
assert library.entries[0].fields[0].key == "title"


@pytest.mark.parametrize("opening, closing", [("{", "}"), ("(", ")")])
def test_a_quote_inside_a_brace_group_does_not_end_the_value(opening: str, closing: str):
title = '"A survey of {"a}-marked vowels"'
source = f"@article{opening}quoted, title = {title}, year = {{2024}}{closing}"

library = Splitter(source).split()

assert len(library.blocks) == 1
assert library.failed_blocks == []
assert library.entries[0]["title"] == title
assert library.entries[0]["year"] == "{2024}"