Skip to content

API

Database

The BBDB database.

bbdb_file()

Return the pathname of your BBDB file.

This is the file referred to by the 'bbdb-file' variable in emacs. The most reliable way to get it is to ask emacs directly.

Source code in src/bbdb/database.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def bbdb_file() -> str:
    """Return the pathname of your BBDB file.

    This is the file referred to by the 'bbdb-file' variable in emacs.
    The most reliable way to get it is to ask emacs directly.
    """

    tag = "BBDB="
    cmd = "emacs --batch"
    cmd += " --eval '(load-file (expand-file-name \"~/.emacs\"))'"
    cmd += f" --eval '(message \"{tag}%s\" bbdb-file)' --kill"

    text = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)

    for line in text.decode("utf-8").split("\n"):
        if line.startswith(tag):
            path = line.replace(tag, "").strip()
            return str(Path(path).expanduser())

    raise RuntimeError("can't find BBDB file in emacs output")

readdb(path=None)

Read a BBDB database.

Source code in src/bbdb/database.py
11
12
13
14
def readdb(path: str | None = None) -> BBDB:
    """Read a BBDB database."""

    return BBDB.fromfile(path or bbdb_file())

Model

The BBDB model.

Address

Bases: BBDBModel

A BBDB address.

Source code in src/bbdb/model.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Address(BBDBModel):
    """A BBDB address."""

    location: list[str] = []
    city: str = ""
    state: str = ""
    zipcode: str = ""
    country: str = ""

    def set_location(self, *location: str) -> None:
        """Set list of location lines."""

        self.location = list(location)

    def outputs(self) -> Iterator[str]:
        """Yield lisp output for this item."""

        if self.location:
            yield "(" + " ".join(map(quote, self.location)) + ")"
        else:
            yield "nil"

        for attr in "city", "state", "zipcode", "country":
            yield quote(getattr(self, attr))

    def __str__(self) -> str:
        parts = list(self.location)

        for attr in "city", "state", "zipcode", "country":
            value = getattr(self, attr)
            if value:
                parts.append(value)

        return ", ".join(parts)

outputs()

Yield lisp output for this item.

Source code in src/bbdb/model.py
64
65
66
67
68
69
70
71
72
73
def outputs(self) -> Iterator[str]:
    """Yield lisp output for this item."""

    if self.location:
        yield "(" + " ".join(map(quote, self.location)) + ")"
    else:
        yield "nil"

    for attr in "city", "state", "zipcode", "country":
        yield quote(getattr(self, attr))

set_location(*location)

Set list of location lines.

Source code in src/bbdb/model.py
59
60
61
62
def set_location(self, *location: str) -> None:
    """Set list of location lines."""

    self.location = list(location)

BBDB

Bases: BBDBModel

A BBDB database.

Source code in src/bbdb/model.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
class BBDB(BBDBModel):
    """A BBDB database."""

    coding: str = "utf-8-emacs"
    fileversion: int = 9
    records: list[Record] = []

    def add_record(self, first: str = "", last: str = "", **kw) -> Record:
        rec = Record(firstname=first, lastname=last, **kw)

        self.records.append(rec)
        self.records.sort()

        return rec

    @property
    def userfields(self) -> list:
        fields = set()
        for rec in self.records:
            for tag in rec.notes:
                fields.add(tag)

        return list(sorted(fields))

    @staticmethod
    def fromfile(path: str) -> BBDB:
        """Read and return BBDB from a file."""

        db = BBDB()
        db.read_file(path)
        return db

    @staticmethod
    def frombuffer(buf: IO) -> BBDB:
        """Read and return BBDB from a text stream."""

        db = BBDB()
        db.read(buf)
        return db

    @staticmethod
    def fromdict(d: dict) -> BBDB:
        """Parse and return BBDB from a dict."""

        return BBDB.model_validate(d)

    def read(self, f: IO = sys.stdin) -> None:
        """Read and append BBDB records from a stream."""

        text = f.read()
        data = parse(text)
        recdata = data["records"]
        records = [Record(**rec) for rec in recdata]
        self.records.extend(records)

    def read_file(self, path: str) -> None:
        """Read and append BBDB records from a file."""

        with open(path) as f:
            self.read(f)

    def write(self, f: IO = sys.stdout) -> None:
        """Write database to a text stream."""

        f.write(self.lisp())

    def write_file(self, path: str) -> None:
        """Write database to a file."""

        with open(path, "w") as f:
            self.write(f)

    def lisp(self) -> str:
        """Return emacs-lisp representation of the database."""

        return "".join(self.outputs())

    def outputs(self) -> Iterator[str]:
        """Yield lisp output for this item."""

        yield f";; -*-coding: {self.coding};-*-\n"
        yield ";;; file-version: %d\n" % self.fileversion

        if self.userfields:
            yield ";;; user-fields: ({})\n".format(" ".join(self.userfields))

        for rec in sorted(self.records):
            yield "["
            yield " ".join(list(rec.outputs()))
            yield "]\n"

    def __repr__(self) -> str:
        return "<BBDB: %d records>" % len(self.records)

frombuffer(buf) staticmethod

Read and return BBDB from a text stream.

Source code in src/bbdb/model.py
263
264
265
266
267
268
269
@staticmethod
def frombuffer(buf: IO) -> BBDB:
    """Read and return BBDB from a text stream."""

    db = BBDB()
    db.read(buf)
    return db

fromdict(d) staticmethod

Parse and return BBDB from a dict.

Source code in src/bbdb/model.py
271
272
273
274
275
@staticmethod
def fromdict(d: dict) -> BBDB:
    """Parse and return BBDB from a dict."""

    return BBDB.model_validate(d)

fromfile(path) staticmethod

Read and return BBDB from a file.

Source code in src/bbdb/model.py
255
256
257
258
259
260
261
@staticmethod
def fromfile(path: str) -> BBDB:
    """Read and return BBDB from a file."""

    db = BBDB()
    db.read_file(path)
    return db

lisp()

Return emacs-lisp representation of the database.

Source code in src/bbdb/model.py
303
304
305
306
def lisp(self) -> str:
    """Return emacs-lisp representation of the database."""

    return "".join(self.outputs())

outputs()

Yield lisp output for this item.

Source code in src/bbdb/model.py
308
309
310
311
312
313
314
315
316
317
318
319
320
def outputs(self) -> Iterator[str]:
    """Yield lisp output for this item."""

    yield f";; -*-coding: {self.coding};-*-\n"
    yield ";;; file-version: %d\n" % self.fileversion

    if self.userfields:
        yield ";;; user-fields: ({})\n".format(" ".join(self.userfields))

    for rec in sorted(self.records):
        yield "["
        yield " ".join(list(rec.outputs()))
        yield "]\n"

read(f=sys.stdin)

Read and append BBDB records from a stream.

Source code in src/bbdb/model.py
277
278
279
280
281
282
283
284
def read(self, f: IO = sys.stdin) -> None:
    """Read and append BBDB records from a stream."""

    text = f.read()
    data = parse(text)
    recdata = data["records"]
    records = [Record(**rec) for rec in recdata]
    self.records.extend(records)

read_file(path)

Read and append BBDB records from a file.

Source code in src/bbdb/model.py
286
287
288
289
290
def read_file(self, path: str) -> None:
    """Read and append BBDB records from a file."""

    with open(path) as f:
        self.read(f)

write(f=sys.stdout)

Write database to a text stream.

Source code in src/bbdb/model.py
292
293
294
295
def write(self, f: IO = sys.stdout) -> None:
    """Write database to a text stream."""

    f.write(self.lisp())

write_file(path)

Write database to a file.

Source code in src/bbdb/model.py
297
298
299
300
301
def write_file(self, path: str) -> None:
    """Write database to a file."""

    with open(path, "w") as f:
        self.write(f)

BBDBModel

Bases: BaseModel

Base BBDB data model.

Source code in src/bbdb/model.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class BBDBModel(BaseModel):
    """Base BBDB data model."""

    def check(self) -> None:
        """Check object is valid, or raise ValueError."""

        try:
            d = self.model_dump()
            self.__class__(**d)
        except ValidationError as exc:
            raise ValueError from exc

    def dict(self) -> dict:
        """Return a dict representation of the data."""

        return self.model_dump()

    def json(self, **kwargs) -> str:
        """Return a JSON representation of the data."""

        return self.model_dump_json(**kwargs)

check()

Check object is valid, or raise ValueError.

Source code in src/bbdb/model.py
30
31
32
33
34
35
36
37
def check(self) -> None:
    """Check object is valid, or raise ValueError."""

    try:
        d = self.model_dump()
        self.__class__(**d)
    except ValidationError as exc:
        raise ValueError from exc

dict()

Return a dict representation of the data.

Source code in src/bbdb/model.py
39
40
41
42
def dict(self) -> dict:
    """Return a dict representation of the data."""

    return self.model_dump()

json(**kwargs)

Return a JSON representation of the data.

Source code in src/bbdb/model.py
44
45
46
47
def json(self, **kwargs) -> str:
    """Return a JSON representation of the data."""

    return self.model_dump_json(**kwargs)

Record

Bases: BBDBModel

A BBDB record.

Source code in src/bbdb/model.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@total_ordering
class Record(BBDBModel):
    """A BBDB record."""

    firstname: str = ""
    lastname: str = ""
    affix: list[str] = []
    aka: list[str] = []
    company: list[str] = []
    phone: dict[str, PhoneNumber] = {}
    address: dict[str, Address] = {}
    net: list[str] = []
    notes: dict[str, str] = {}
    uuid: UUID = Field(default_factory=uuid4)
    creation: datetime = Field(default_factory=now)
    timestamp: datetime = Field(default_factory=now)

    @field_validator("uuid", mode="before")
    @classmethod
    def convert_uuid(cls, v: str | UUID) -> UUID:
        if isinstance(v, str):
            return UUID(v)
        else:
            return v

    @field_validator("creation", "timestamp", mode="before")
    @classmethod
    def convert_datetime(cls, v: str | datetime) -> datetime:
        if isinstance(v, str):
            return from_datestamp(v)
        else:
            return v

    @property
    def name(self) -> str:
        """Composite name property."""

        parts = [self.firstname or "", self.lastname or ""]
        parts = [p for p in parts if p]
        return " ".join(parts)

    def set_name(self, first: str = "", last: str = "") -> None:
        """Set the first and last names."""

        self.firstname = first or ""
        self.lastname = last or ""

    def add_aka(self, *names: str) -> None:
        """Add AKA entries."""

        self.aka.extend(names)

    def add_company(self, *names: str) -> None:
        """Add company entries."""

        self.company.extend(names)

    def add_affix(self, *names: str) -> None:
        """Add affix entries."""

        self.affix.extend(names)

    def add_phone(self, tag: str, number: PhoneNumber) -> None:
        """Add a phone number entry."""

        self.phone[tag] = number

    def add_address(self, tag: str, *location: str, **kw) -> Address:
        """Add an address entry."""

        address = Address(location=list(location), **kw)
        self.address[tag] = address
        return address

    def add_net(self, *names: str) -> None:
        """Add network address entries."""

        self.net.extend(names)

    def add_note(self, tag: str, text: str) -> None:
        """Add a notes entry."""

        self.notes[tag] = text.replace("\n", r"\n")

    def outputs(self) -> Iterator[str]:
        """Yield lisp output for this item."""

        for attr in "firstname", "lastname":
            value = getattr(self, attr)
            if value:
                yield quote(value)
            else:
                yield "nil"

        for attr in "affix", "aka", "company":
            value = getattr(self, attr)
            if value:
                yield "(" + " ".join(map(quote, sorted(value))) + ")"
            else:
                yield "nil"

        if self.phone:
            rec = []
            for tag, number in sorted(self.phone.items()):
                if isinstance(number, str):
                    number = quote(number)
                else:
                    number = " ".join(map(str, number))
                rec.append("[" + quote(tag) + " " + number + "]")
            yield "(" + " ".join(rec) + ")"
        else:
            yield "nil"

        if self.address:
            rec = []
            for tag, address in sorted(self.address.items()):
                addr = " ".join(list(address.outputs()))
                rec.append("[" + quote(tag) + " " + addr + "]")
            yield "(" + " ".join(rec) + ")"
        else:
            yield "nil"

        if self.net:
            yield "(" + " ".join(map(quote, sorted(self.net))) + ")"
        else:
            yield "nil"

        if self.notes:
            rec = []
            for tag, text in sorted(self.notes.items()):
                rec.append("(" + tag + " . " + quote(text) + ")")
            yield "(" + " ".join(rec) + ")"
        else:
            yield "nil"

        yield quote(str(self.uuid))
        yield quote(to_datestamp(self.creation))
        yield quote(to_datestamp(self.timestamp, time=True))

        yield "nil"

    def __lt__(self, other) -> bool:
        return list(self) < list(other)

name: str property

Composite name property.

add_address(tag, *location, **kw)

Add an address entry.

Source code in src/bbdb/model.py
153
154
155
156
157
158
def add_address(self, tag: str, *location: str, **kw) -> Address:
    """Add an address entry."""

    address = Address(location=list(location), **kw)
    self.address[tag] = address
    return address

add_affix(*names)

Add affix entries.

Source code in src/bbdb/model.py
143
144
145
146
def add_affix(self, *names: str) -> None:
    """Add affix entries."""

    self.affix.extend(names)

add_aka(*names)

Add AKA entries.

Source code in src/bbdb/model.py
133
134
135
136
def add_aka(self, *names: str) -> None:
    """Add AKA entries."""

    self.aka.extend(names)

add_company(*names)

Add company entries.

Source code in src/bbdb/model.py
138
139
140
141
def add_company(self, *names: str) -> None:
    """Add company entries."""

    self.company.extend(names)

add_net(*names)

Add network address entries.

Source code in src/bbdb/model.py
160
161
162
163
def add_net(self, *names: str) -> None:
    """Add network address entries."""

    self.net.extend(names)

add_note(tag, text)

Add a notes entry.

Source code in src/bbdb/model.py
165
166
167
168
def add_note(self, tag: str, text: str) -> None:
    """Add a notes entry."""

    self.notes[tag] = text.replace("\n", r"\n")

add_phone(tag, number)

Add a phone number entry.

Source code in src/bbdb/model.py
148
149
150
151
def add_phone(self, tag: str, number: PhoneNumber) -> None:
    """Add a phone number entry."""

    self.phone[tag] = number

outputs()

Yield lisp output for this item.

Source code in src/bbdb/model.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def outputs(self) -> Iterator[str]:
    """Yield lisp output for this item."""

    for attr in "firstname", "lastname":
        value = getattr(self, attr)
        if value:
            yield quote(value)
        else:
            yield "nil"

    for attr in "affix", "aka", "company":
        value = getattr(self, attr)
        if value:
            yield "(" + " ".join(map(quote, sorted(value))) + ")"
        else:
            yield "nil"

    if self.phone:
        rec = []
        for tag, number in sorted(self.phone.items()):
            if isinstance(number, str):
                number = quote(number)
            else:
                number = " ".join(map(str, number))
            rec.append("[" + quote(tag) + " " + number + "]")
        yield "(" + " ".join(rec) + ")"
    else:
        yield "nil"

    if self.address:
        rec = []
        for tag, address in sorted(self.address.items()):
            addr = " ".join(list(address.outputs()))
            rec.append("[" + quote(tag) + " " + addr + "]")
        yield "(" + " ".join(rec) + ")"
    else:
        yield "nil"

    if self.net:
        yield "(" + " ".join(map(quote, sorted(self.net))) + ")"
    else:
        yield "nil"

    if self.notes:
        rec = []
        for tag, text in sorted(self.notes.items()):
            rec.append("(" + tag + " . " + quote(text) + ")")
        yield "(" + " ".join(rec) + ")"
    else:
        yield "nil"

    yield quote(str(self.uuid))
    yield quote(to_datestamp(self.creation))
    yield quote(to_datestamp(self.timestamp, time=True))

    yield "nil"

set_name(first='', last='')

Set the first and last names.

Source code in src/bbdb/model.py
127
128
129
130
131
def set_name(self, first: str = "", last: str = "") -> None:
    """Set the first and last names."""

    self.firstname = first or ""
    self.lastname = last or ""

Parser

The BBDB parser.

BBDBTransformer

Bases: Transformer

Transform parsed tree into a dictionary.

Source code in src/bbdb/parser.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class BBDBTransformer(Transformer):
    """Transform parsed tree into a dictionary."""

    _recfields = (
        "firstname",
        "lastname",
        "affix",
        "aka",
        "company",
        "phone",
        "address",
        "net",
        "notes",
        "uuid",
        "creation",
        "timestamp",
    )

    _addrfields = ("tag", "location", "city", "state", "zipcode", "country")

    def records(self, items):
        return {"records": items}

    def record(self, items):
        return map_fields(self._recfields, items)

    def address(self, items):
        data = {}
        if items[0]:
            for item in items:
                key = item.pop("tag")
                data[key] = item

        return data

    def address_record(self, items):
        return map_fields(self._addrfields, items)

    def pairs(self, items):
        data = {}
        if items[0]:
            for item in items:
                key, value = item.children
                data[key] = value

        return data

    def string(self, items):
        return items[0][1:-1].replace(r"\"", '"')

    strings = lambda self, elt: elt if elt[0] else []
    number = lambda self, elt: int(elt[0])
    atom = lambda self, elt: str(elt[0])
    none = lambda self, elt: ""

    affix = aka = company = net = strings
    notes = phone = pairs
    streets = phone_usa = list
    cache = none

make_parser(grammarfile='bbdb.lark')

Build a Lark parser using a grammar file.

Source code in src/bbdb/parser.py
17
18
19
20
21
22
23
24
def make_parser(grammarfile: str = "bbdb.lark") -> Lark:
    """Build a Lark parser using a grammar file."""

    dirname = Path(__file__).parent
    filename = dirname / grammarfile
    grammar = filename.read_text()

    return Lark(grammar, start="records", parser="lalr", transformer=BBDBTransformer())

parse(text, parser=None)

Parse some text using a Lark parser.

Source code in src/bbdb/parser.py
10
11
12
13
14
def parse(text: str, parser: Lark | None = None):
    """Parse some text using a Lark parser."""

    parser = parser or make_parser()
    return parser.parse(text)