1# Process html entity - {, ¯, ", ...
2import re
3
4from ..common.entities import entities
5from ..common.utils import isValidEntityCode, fromCodePoint
6from .state_inline import StateInline
7
8DIGITAL_RE = re.compile(r"^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));", re.IGNORECASE)
9NAMED_RE = re.compile(r"^&([a-z][a-z0-9]{1,31});", re.IGNORECASE)
10
11
12def entity(state: StateInline, silent: bool):
13
14    pos = state.pos
15    maximum = state.posMax
16
17    if state.srcCharCode[pos] != 0x26:  # /* & */
18        return False
19
20    if (pos + 1) < maximum:
21        ch = state.srcCharCode[pos + 1]
22
23        if ch == 0x23:  # /* # */
24            match = DIGITAL_RE.search(state.src[pos:])
25            if match:
26                if not silent:
27                    match1 = match.group(1)
28                    code = (
29                        int(match1[1:], 16)
30                        if match1[0].lower() == "x"
31                        else int(match1, 10)
32                    )
33                    state.pending += (
34                        fromCodePoint(code)
35                        if isValidEntityCode(code)
36                        else fromCodePoint(0xFFFD)
37                    )
38
39                state.pos += len(match.group(0))
40                return True
41
42        else:
43            match = NAMED_RE.search(state.src[pos:])
44            if match:
45                if match.group(1) in entities:
46                    if not silent:
47                        state.pending += entities[match.group(1)]
48                    state.pos += len(match.group(0))
49                    return True
50
51    if not silent:
52        state.pending += "&"
53    state.pos += 1
54    return True
55