GNU TeXmacsUser manualReferenceAboutEnglish
Bibliographies

1.Introduction

This page follows a citation from the document to the typeset bibliography, and describes the BibTEX machinery which is involved: the parser and converters for .bib files, the external bibtex program, the internal style engine written in Scheme, and the bibliographic database. The user side is described in Compiling a bibliography and the markup in the documentation of std-automatic; the Scheme functions available to style writers are documented in Writing TeXmacs bibliography styles.

2.Markup

2.1.Citations

The citation macros are defined in

packages/standard/std-automatic.ts

. The central one is

<assign|cite-arg|<macro|key|<write|<value|bib-prefix>|<arg|key>><reference|<merge|<value|bib-prefix>|-|<arg|key>>>>>

Each key of cite, cite-detail and cite-raw therefore does two things: the primitive write appends the key to the auxiliary list named by the environment variable bib-prefix ("bib" by default), and reference refers to the label prefix-key. nocite only writes the keys; the special key * stands for all entries of the bibliography file. with-bib changes bib-prefix locally, which is how a document can contain several independent bibliographies. cite-TeXmacs (in

packages/header/title-base.ts

and

header-article.ts

) cites keys of the form TeXmacs:…, which are provided by $TEXMACS_PATH/misc/bib/texmacs.bib.

The typesetter implements write in concater_rep::typeset_write (

Typeset/Concat/concat_active.cpp

): during a complete typesetting pass it appends the evaluated second argument to env->local_aux[name], a document which is stored in the buffer as buf->data->aux and saved with the document (in the auxiliary part of the file). After typesetting, aux["bib"] is thus the list of cited keys, in order of appearance and with repetitions. For a project, the auxiliary data of the master document is used.

2.2.The bibliography

The bibliography itself is the tag (bibliography aux style file body) (or bibliography* with an extra title argument), defined in

packages/section/section-base.ts

: aux is the prefix ("bib"), style the name of a BibTEX style (plain) or of an internal style (tm-plain), file the .bib file (possibly empty) and body the generated content. It is inserted by make-bib, make-database-bib (

text/text-edit.scm

) or the dialogue open-bibliography-inserter (

bibtex/bib-widgets.scm

, used when the preference "gui:new bibliography dialogue" is set).

The generated body is a bib-list:

(bib-list largest (document (concat (bibitem* label) (label prefix-key) text) …))

where largest is used to compute the width of the labels. The label matches the reference of the citations.

3.The pipeline

3.1.Triggering the generation

Document\(\rightarrow\)Update\(\rightarrow\)Bibliography calls (update-document "bibliography") (

generic/document-edit.scm

). It first calls zotero-before-update, which refreshes a .bib file written from Zotero and syncs the entries of the database which come from Zotero (see Citations from Zotero), then runs generate-all-aux and retypesets the buffer (as many times as specified by the preference "document update times"). Notice that this regenerates all automatic content, not only bibliographies. (generate-aux "bibliography") regenerates only the bibliographies, but it still empties every other automatic section (tables of contents, indexes, …) without filling it again, because generate_aux_recursively clears each automatic body before testing which kind was requested; see automatic content.

edit_process_rep::generate_aux (

Edit/Process/edit_process.cpp

) walks through the document. For each automatic tag (is_aux) it replaces the body by an empty document, puts the cursor there and calls generate_bibliography (aux, style, file), which eventually inserts the result with insert_tree. If the result is a string starting with Error:, it is shown in the status bar instead.

3.2.Choice of the strategy

edit_process_rep::generate_bibliography first retrieves the list of keys bib_t= buf->data->aux[bib], uses tm-plain if the style is empty, copies a style.bst file found next to the document into $TEXMACS_HOME_PATH/system/bib (copy_bst_file), and looks for the bibliography file with find_bib_file (the name with suffix .bib, as given, relative to the document, or in one of its ancestor directories). Then:

  1. No .bib file was found.

    1. If a file with suffix .bbl exists instead, it is loaded with bibtex_load_bbl. This allows to ship a precompiled bibliography.

    2. Otherwise, with the database tool, the Scheme function bib-compile is called with texmacs.bib as the only file (entries then come from the database and the attachments, see below), followed by bib-attach.

    3. Without the database tool, the bibliography can only be produced if all keys start with TeXmacs:, in which case bib-compile is called in the same way; otherwise the error “Could not find bibliography file” is reported.

  2. A .bib file was found.

    1. If bibtex is not installed or the style is internal (tm-), keys * are replaced by all keys of the file (using parse_bib).

    2. If bibtex is not installed and the style is not internal, the style is replaced by its internal equivalent (tm-abbrv, tm-acm, tm-alpha, tm-elsart-num, tm-ieeetr, tm-siam, tm-unsrt) or by tm-plain.

    3. With the database tool, bib-compile is called with the absolute path of the file and, unless * was cited, texmacs.bib.

    4. Without the database tool and with an internal style, the file and texmacs.bib are parsed with parse_bib, bib_entries selects the cited entries (following crossref fields and warning about missing or duplicate keys), the style module (bibtex style) is loaded and the Scheme function bib-process formats the entries.

    5. Otherwise the external program is run by bibtex_run.

    6. With the database tool, bib-attach is called afterwards. If the result uses natbib-triple (produced by natbib-compatible BibTEX styles), the package cite-author-year is added to the style of the document.

In all cases the result goes through arrange_bib, which replaces -- by an en dash and empty documents by a document with an empty paragraph.

3.3.Running the external BibTEX

tree bibtex_run (string bib, string style, url bib_file, tree bib_t)
(run bibtex)

Defined in

Plugins/Bibtex/bibtex.cpp

(the variant taking an array<string> of keys is exported as bibtex-run). It checks that the program (by default bibtex, see the preference "bibtex command" and set-bibtex-command) is in the path (supports-bibtex?), and that neither the style nor the file name contain spaces. If some keys start with TeXmacs:, complete_bib_file creates a copy name-extended.bib of the bibliography file next to it, with texmacs.bib appended, and uses that copy instead. It then writes temp.aux with \bibstyle, \citation and \bibdata commands in $TEXMACS_HOME_PATH/system/bib, runs bibtex temp in that directory with BIBINPUTS and BSTINPUTS extended by the directory of the bibliography file, reports the lines containing Warning-- on the bibtex-warning debug channel, and loads temp.bbl.

tree bibtex_load_bbl (string bib, url bbl_file)
(import a .bbl file)

Converts the file to Cork encoding, parses it as a LaTeX snippet, collects the macro definitions it contains (which are put in a surrounding with), finds the thebibliography environment and rewrites its items into a bib-list: \bibitem{key} becomes (bibitem* n) with a running number, \bibitem[l]{key} keeps its label, and a label bib-key is added.

3.4.The internal style engine

The internal styles are ordinary Scheme modules (bibtex name) in

progs/bibtex/

, and are selected by the style name tm-name. The entry point is:

(bib-process prefix style doc)
(format a list of entries)

Defined in

bibtex/bib-utils.scm

. doc is a (document (bib-entry type key (document (bib-field name value) …)) …), as produced by parse_bib or db->bib. The function sets the globals bib-current-prefix and bib-style, calls bib-preprocessing on the entries (the alpha style uses it to compute the labels), sorts them with bib-sorted-entries (a stable sort on bib-sort-key; unsrt redefines it as the identity), formats each entry with (bib-format-entry n entry), and returns the simplified (bib-list count (document …)).

A style is declared with (bib-define-style name fallback), which defines a Scheme mode bib-name? that implies the mode of the fallback style.

plain.scm

defines the generic formatting functions (bib-format-entry, bib-format-article, …, bib-format-names, bib-sort-key) without mode, and every other style overrides some of them with (:mode bib-name?). The mode bib-name? holds when bib-style is the name of the style. Since the dispatch uses modes, the most specific definition wins, exactly as for other context dependent Scheme functions.

The field values are TeXmacs trees, with authors and editors structured as (bib-names (bib-name first von last jr) …) and pages as (bib-pages from to). The BibTEX built-in string functions are implemented in C++ (

Plugins/Bibtex/bibtex_functions.cpp

) and exported to Scheme:

bib-field, bib-empty?

access to a field of a bib-entry.

bib-purify, bib-text-length, bib-prefix

the analogues of purify$, text.length$ and text.prefix$.

bib-locase, bib-upcase, bib-locase-first, bib-upcase-first, bib-default-preserve-case, bib-default-upcase-first

changes of case in the style of change.case$, respecting keepcase (the TeXmacs equivalent of braces in BibTEX).

bib-add-period

the analogue of add.period$.

bib-abbreviate

abbreviation of first names.

The Scheme side (

bib-utils.scm

) adds helpers for building the output (bib-new-block, bib-new-sentence, bib-new-list, bib-emphasize, bib-translate, …) and for temporarily switching style (bib-with-style).

3.5.Compilation with the database tool

When the database tool is enabled, generate_bibliography delegates to

database/bib-manage.scm

:

(bib-compile prefix style names . bib-files)
(compile a bibliography)

names is the list of cited keys (a document tree is accepted). The entries are looked up in the following sources, in this order, the first source containing a key winning (bib-retrieve-entries):

  1. :local: the entries edited locally for this document (attachments whose name ends with -biblio);

  2. the given files of the user: a .tmdb file is used as a database, a .bib file is first converted into a cached database (see below);

  3. :default: the user's bibliographic database (bib-database); if several entries have the same name, those contributed by the default user are preferred;

  4. the given .bib files which were written from Zotero (they start with the line % Exported from Zotero by TeXmacs);

  5. :zotero: the library of Zotero, when Zotero runs (see Citations from Zotero);

  6. :attached: the entries that were attached to the document the last time its bibliography was compiled (attachments ending with -bibliography).

This order is computed by bib-sources, for bib-compile and bib-attach alike.

If the style is one of (bib-standard-styles), the entries are converted with db->bib and formatted by bib-generate, which loads the style module and calls bib-process. Otherwise the external program is used: the .bib files are concatenated with the BibTEX conversion of the entries found elsewhere into $TEXMACS_HOME_PATH/system/bib/auto.bib, on which bibtex-run is called. If bibtex is not installed, the style is replaced by tm-style when available and by tm-plain otherwise.

(bib-attach prefix names . bib-files)
(attach the entries to the document)

Retrieves the cited entries in the same way and stores them, as db-entry markup, in the attachment prefix-bibliography of the document. A document therefore carries the entries it cites, and its bibliography can be recompiled elsewhere without the original .bib file. When the preference "auto bib import" is on (the default), the redefinition of notify-set-attachment in

bib-manage.scm

imports the entries of such attachments into the user's database. This hook is called by edit_typeset_rep::set_data for every attachment when the data of a document are installed, typically when it is opened; since its default definition in

init-texmacs.scm

does nothing, the importation only happens once

bib-manage.scm

has been loaded.

Caching of .bib files.
The conversion of a .bib file into database entries is cached below $TEXMACS_HOME_PATH/system/database/. The database bib-master.tmdb maps the path of each source file (source) to its modification time (stamp) and to the converted document (target). bib-cache-bibtex creates the cache (bib-cache-create: the source is copied to bib/id.bib and converted to bib/id.tm) or updates it when the stamp changed (bib-cache-update, which uses the conservative importation described below, so that unchanged entries keep their identifiers). bib-cache-database then imports the cited entries into bib/id.tmdb and returns this database, in which the entries are looked up.
Local bibliographies.
open-biblio (
database/bib-local.scm

) opens tmfs://biblio/prefix/document, a virtual document showing the union of the attached and of the local entries. When it is saved (biblio-confirm), the entries which differ from the attached ones are stored in the attachment prefix-biblio, which takes precedence at the next compilation. This allows to correct an entry for one document without modifying the database. Only entries that already occur among the attached ones are taken into account.

4.BibTEX files as TeXmacs documents

4.1.Parsing

parse_bib (

Data/Convert/BibTeX/parsebib.cpp

, exported as parse-bib) parses a .bib file into a document containing bib-entry, bib-comment, bib-preamble and bib-string tags. It substitutes the @string abbreviations (and a few predefined journal names, see bib_strings_dict in

bibtex_functions.cpp

), and bib_parse_fields converts all field values at once from LaTeX to TeXmacs (by concatenating them with separators into a single LaTeX string, which is much faster than converting each field separately). Author and editor fields are split into names using the BibTEX rules (bib_names), pages becomes bib-pages and URLs become slink.

4.2.The tmbib format

progs/convert/bibtex/init-bibtex.scm

defines two formats. The hidden format bibtex (suffix rawbib) converts between .bib text and the parsed markup above, with the style bibliography. The format tmbib (name “BibTEX”, suffix bib) is the one used when opening or saving a .bib file. Its converters are in

database/bib-db.scm

:

bib->db and db->bib implement the mapping between the two representations of entries. BibTEX brace conventions are replaced by explicit markup: last names are marked with name (and name-von, name-jr, separated by name-sep), and titles are stored in normal case with keepcase only where needed; in the other direction the structured names become bib-names and titles are protected with keepcase. Entries of type conference are imported as inproceedings. Imported entries get the meta fields contributor (default user), modus ("imported") and date, and a fresh identifier from the user's bibliographic database.

4.3.Conservative conversions

Data/Convert/BibTeX/conservative_bib.cpp

implements the incremental conversions. Both split a .bib text into an alternation of inter-entry text and entries (bib_break) and index the entries by key.

(conservative-bib-import old-s old-t new-s)
(incremental import)

Given an old text, its old conversion and a new text, only the entries whose text changed are converted again (by calling the Scheme function zealous-bib-import); the others are taken from old-t. Falls back to a full conversion if the preference "bibtex->texmacs:conservative" is off, or if the @string/@preamble parts differ.

(conservative-bib-export old-t old-s new-t)
(incremental export)

The converse, controlled by the preference "texmacs->bibtex:conservative"; modified entries are serialized by zealous-bib-export.

4.4.Importing into and exporting from the database

bib-import-bibtex (Data\(\rightarrow\)Import) imports a .bib file into the user's database through the cache; bib-import-selection and bib-import-current-buffer import entries of a document with db-confirm-entries-in. bib-export-bibtex (Data\(\rightarrow\)Export) exports the selection, the current buffer, the whole database (bib-export-all, sorted by name) or the attached entries of the current document (bib-export-attachments); when the target file exists, the export is conservative with respect to it.

5.How to

5.1.Add an internal bibliography style

  1. Write a module progs/bibtex/name.scm as explained in Writing TeXmacs bibliography styles, starting with

    (texmacs-module (bibtex mystyle)
      (:use (bibtex bib-utils) (bibtex plain)))
    
    (bib-define-style "mystyle" "plain")
    
    (tm-define (bib-format-bibitem n x)
      (:mode bib-mystyle?)
      ‘(bibitem* ,(list-ref x 2)))

    Here the label of each item is its key.

  2. Add "tm-mystyle" to bib-standard-styles in

    bib-utils.scm

    . This list is used by the bibliography dialogue and, more importantly, by bib-compile: with the database tool enabled, a style which is not in this list is passed to the external bibtex program. Without the database tool, any style whose name starts with tm- is loaded as (bibtex name).

  3. Optionally, add a mapping from the corresponding BibTEX style in generate_bibliography, for the case when bibtex is not installed.

5.2.Add fields or entry types

The admissible types and fields of bibliographic entries used by the editor are declared in db-format-table in

database/bib-db.scm

; the internal styles format each type in bib-format-entry (

plain.scm

), falling back to bib-format-misc for unknown types. Fields which need special treatment when converting between BibTEX and database entries are handled in db-bib-sub-sub and bib-db-sub-sub.

6.Pitfalls

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".