3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
10 * \author Jürgen Spitzmüller
12 * Full author contact details are available in file CREDITS.
17 #include "BiblioInfo.h"
19 #include "BufferParams.h"
20 #include "buffer_funcs.h"
23 #include "InsetIterator.h"
26 #include "Paragraph.h"
27 #include "TextClass.h"
28 #include "TocBackend.h"
30 #include "support/convert.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/gettext.h"
34 #include "support/lassert.h"
35 #include "support/lstrings.h"
36 #include "support/regex.h"
37 #include "support/textutils.h"
43 using namespace lyx::support;
50 // Remove placeholders from names
51 docstring renormalize(docstring const & input)
53 docstring res = subst(input, from_ascii("$$space!"), from_ascii(" "));
54 return subst(res, from_ascii("$$comma!"), from_ascii(","));
58 // Split the surname into prefix ("von-part") and family name
59 pair<docstring, docstring> parseSurname(docstring const & sname)
61 // Split the surname into its tokens
62 vector<docstring> pieces = getVectorFromString(sname, from_ascii(" "));
63 if (pieces.size() < 2)
64 return make_pair(docstring(), sname);
66 // Now we look for pieces that begin with a lower case letter.
67 // All except for the very last token constitute the "von-part".
69 vector<docstring>::const_iterator it = pieces.begin();
70 vector<docstring>::const_iterator const en = pieces.end();
72 for (; it != en; ++it) {
75 // If this is the last piece, then what we now have is
76 // the family name, notwithstanding the casing.
79 char_type const c = (*it)[0];
80 // If the piece starts with a upper case char, we assume
81 // this is part of the surname.
84 // Nothing of the former, so add this piece to the prename
92 // Reconstruct the family name.
93 // Note that if we left the loop with because it + 1 == en,
94 // then this will still do the right thing, i.e., make surname
95 // just be the last piece.
98 for (; it != en; ++it) {
105 return make_pair(prefix, surname);
117 // gets the name parts (prename, surname, prefix, suffix) from an author-type string
118 name_parts nameParts(docstring const & iname)
124 // First we check for goupings (via {...}) and replace blanks and
125 // commas inside groups with temporary placeholders
128 docstring::const_iterator p = iname.begin();
129 while (p != iname.end()) {
130 // count grouping level
135 // generate string with probable placeholders
136 if (*p == ' ' && gl > 0)
137 name += from_ascii("$$space!");
138 else if (*p == ',' && gl > 0)
139 name += from_ascii("$$comma!");
145 // Now we look for a comma, and take the last name to be everything
146 // preceding the right-most one, so that we also get the name suffix
148 vector<docstring> pieces = getVectorFromString(name);
149 if (pieces.size() > 1) {
150 // Whether we have a name suffix or not, the prename is
152 res.prename = renormalize(pieces.back());
153 // The family name, conversely, is always the first item.
154 // However, it might contain a prefix (aka "von" part)
155 docstring const sname = pieces.front();
156 res.prefix = renormalize(parseSurname(sname).first);
157 res.surname = renormalize(parseSurname(sname).second);
158 // If we have three pieces (the maximum allowed by BibTeX),
159 // the second one is the name suffix.
160 if (pieces.size() > 2)
161 res.suffix = renormalize(pieces.at(1));
165 // OK, so now we want to look for the last name.
166 // Split on spaces, to get various tokens.
167 pieces = getVectorFromString(name, from_ascii(" "));
168 // No space: Only a family name given
169 if (pieces.size() < 2) {
170 res.surname = renormalize(pieces.back());
173 // If we get two pieces, assume "prename surname"
174 if (pieces.size() == 2) {
175 res.prename = renormalize(pieces.front());
176 res.surname = renormalize(pieces.back());
180 // More than 3 pieces: A name prefix (aka "von" part) might be included.
181 // We look for the first piece that begins with a lower case letter
182 // (which is the name prefix, if it is not the last token) or the last token.
184 vector<docstring>::const_iterator it = pieces.begin();
185 vector<docstring>::const_iterator const en = pieces.end();
187 for (; it != en; ++it) {
190 char_type const c = (*it)[0];
191 // If the piece starts with a lower case char, we assume
192 // this is the name prefix and thus prename is complete.
195 // Same if this is the last piece, which is always the surname.
198 // Nothing of the former, so add this piece to the prename
206 // Now reconstruct the family name and strip the prefix.
207 // Note that if we left the loop because it + 1 == en,
208 // then this will still do the right thing, i.e., make surname
209 // just be the last piece.
212 for (; it != en; ++it) {
219 res.prename = renormalize(prename);
220 res.prefix = renormalize(parseSurname(surname).first);
221 res.surname = renormalize(parseSurname(surname).second);
226 docstring constructName(docstring const & name, string const & scheme)
228 // re-constructs a name from name parts according
230 docstring const prename = nameParts(name).prename;
231 docstring const surname = nameParts(name).surname;
232 docstring const prefix = nameParts(name).prefix;
233 docstring const suffix = nameParts(name).suffix;
235 static regex const reg1("(.*)(\\{%prename%\\[\\[)([^\\]]+)(\\]\\]\\})(.*)");
236 static regex const reg2("(.*)(\\{%suffix%\\[\\[)([^\\]]+)(\\]\\]\\})(.*)");
237 static regex const reg3("(.*)(\\{%prefix%\\[\\[)([^\\]]+)(\\]\\]\\})(.*)");
239 // Changing the first parameter of regex_match() may corrupt the
240 // second one. In this case we use the temporary string tmp.
241 if (regex_match(scheme, sub, reg1)) {
243 if (!prename.empty())
247 if (regex_match(res, sub, reg2)) {
248 string tmp = sub.str(1);
251 res = tmp + sub.str(5);
253 if (regex_match(res, sub, reg3)) {
254 string tmp = sub.str(1);
257 res = tmp + sub.str(5);
259 docstring result = from_ascii(res);
260 result = subst(result, from_ascii("%prename%"), prename);
261 result = subst(result, from_ascii("%surname%"), surname);
262 result = subst(result, from_ascii("%prefix%"), prefix);
263 result = subst(result, from_ascii("%suffix%"), suffix);
268 vector<docstring> const getAuthors(docstring const & author)
270 // We check for goupings (via {...}) and only consider " and "
271 // outside groups as author separator. This is to account
272 // for cases such as {{Barnes and Noble, Inc.}}, which
273 // need to be treated as one single family name.
274 // We use temporary placeholders in order to differentiate the
275 // diverse " and " cases.
277 // First, we temporarily replace all ampersands. It is rather unusual
278 // in author names, but can happen (consider cases such as "C \& A Corp.").
279 docstring iname = subst(author, from_ascii("&"), from_ascii("$$amp!"));
280 // Then, we temporarily make all " and " strings to ampersands in order
281 // to handle them later on a per-char level.
282 iname = subst(iname, from_ascii(" and "), from_ascii(" & "));
283 // Now we traverse through the string and replace the "&" by the proper
284 // output in- and outside groups
287 docstring::const_iterator p = iname.begin();
288 while (p != iname.end()) {
289 // count grouping level
294 // generate string with probable placeholders
297 // Inside groups, we output "and"
298 name += from_ascii("and");
300 // Outside groups, we output a separator
301 name += from_ascii("$$namesep!");
308 // re-insert the literal ampersands
309 name = subst(name, from_ascii("$$amp!"), from_ascii("&"));
311 // Now construct the actual vector
312 return getVectorFromString(name, from_ascii(" $$namesep! "));
316 bool multipleAuthors(docstring const & author)
318 return getAuthors(author).size() > 1;
322 // converts a string containing LaTeX commands into unicode
324 docstring convertLaTeXCommands(docstring const & str)
329 bool scanning_cmd = false;
330 bool scanning_math = false;
331 bool escaped = false; // used to catch \$, etc.
332 while (!val.empty()) {
333 char_type const ch = val[0];
335 // if we're scanning math, we output everything until we
336 // find an unescaped $, at which point we break out.
343 scanning_math = false;
349 // if we're scanning a command name, then we just
350 // discard characters until we hit something that
353 if (isAlphaASCII(ch)) {
358 // so we're done with this command.
359 // now we fall through and check this character.
360 scanning_cmd = false;
363 // was the last character a \? If so, then this is something like:
364 // \\ or \$, so we'll just output it. That's probably not always right...
366 // exception: output \, as THIN SPACE
368 ret.push_back(0x2009);
379 scanning_math = true;
383 // Change text mode accents in the form
384 // {\v a} to \v{a} (see #9340).
385 // FIXME: This is a sort of mini-tex2lyx.
386 // Use the real tex2lyx instead!
387 static lyx::regex const tma_reg("^\\{\\\\[bcCdfGhHkrtuUv]\\s\\w\\}");
388 if (lyx::regex_search(to_utf8(val), tma_reg)) {
390 val.replace(2, 1, from_ascii("{"));
394 // Apart from the above, we just ignore braces
395 if (ch == '{' || ch == '}') {
400 // we're going to check things that look like commands, so if
401 // this doesn't, just output it.
408 // ok, could be a command of some sort
409 // let's see if it corresponds to some unicode
410 // unicodesymbols has things in the form: \"{u},
411 // whereas we may see things like: \"u. So we'll
412 // look for that and change it, if necessary.
413 // FIXME: This is a sort of mini-tex2lyx.
414 // Use the real tex2lyx instead!
415 static lyx::regex const reg("^\\\\\\W\\w");
416 if (lyx::regex_search(to_utf8(val), reg)) {
417 val.insert(3, from_ascii("}"));
418 val.insert(2, from_ascii("{"));
422 docstring const cnvtd = Encodings::fromLaTeXCommand(val,
423 Encodings::TEXT_CMD, termination, rem);
424 if (!cnvtd.empty()) {
425 // it did, so we'll take that bit and proceed with what's left
430 // it's a command of some sort
439 // Escape '<' and '>' and remove richtext markers (e.g. {!this is richtext!}) from a string.
440 docstring processRichtext(docstring const & str, bool richtext)
445 bool scanning_rich = false;
446 while (!val.empty()) {
447 char_type const ch = val[0];
448 if (ch == '{' && val.size() > 1 && val[1] == '!') {
449 // beginning of rich text
450 scanning_rich = true;
454 if (scanning_rich && ch == '!' && val.size() > 1 && val[1] == '}') {
456 scanning_rich = false;
464 // we need to escape '<' and '>'
472 } else if (!scanning_rich /* && !richtext */)
474 // else the character is discarded, which will happen only if
475 // richtext == false and we are scanning rich text
484 //////////////////////////////////////////////////////////////////////
488 //////////////////////////////////////////////////////////////////////
490 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
491 : is_bibtex_(true), bib_key_(key), num_bib_key_(0), entry_type_(type), info_(),
497 docstring const BibTeXInfo::getAuthorOrEditorList(Buffer const * buf,
498 bool full, bool forceshort) const
500 docstring author = operator[]("author");
502 author = operator[]("editor");
504 return getAuthorList(buf, author, full, forceshort);
508 docstring const BibTeXInfo::getAuthorList(Buffer const * buf,
509 docstring const & author, bool const full, bool const forceshort,
510 bool const allnames, bool const beginning) const
512 // Maxnames treshold depend on engine
513 size_t maxnames = buf ?
514 buf->params().documentClass().max_citenames() : 2;
517 docstring const opt = label();
522 docstring const remainder = trim(split(opt, authors, '('));
523 if (remainder.empty())
524 // in this case, we didn't find a "(",
525 // so we don't have author (year)
528 // Natbib syntax is "Jones et al.(1990)Jones, Baker, and Williams"
529 docstring const fullauthors = trim(rsplit(remainder, ')'));
530 if (!fullauthors.empty())
539 // OK, we've got some names. Let's format them.
540 // Try to split the author list
541 vector<docstring> const authors = getAuthors(author);
545 CiteEngineType const engine_type = buf ? buf->params().citeEngineType()
546 : ENGINE_TYPE_DEFAULT;
548 // These are defined in the styles
550 buf ? buf->params().documentClass().getCiteMacro(engine_type, "B_etal")
552 string const namesep =
553 buf ? buf->params().documentClass().getCiteMacro(engine_type, "B_namesep")
555 string const lastnamesep =
556 buf ? buf->params().documentClass().getCiteMacro(engine_type, "B_lastnamesep")
558 string const pairnamesep =
559 buf ? buf->params().documentClass().getCiteMacro(engine_type, "B_pairnamesep")
561 string firstnameform =
562 buf ? buf->params().documentClass().getCiteMacro(engine_type, "!firstnameform")
563 : "{%prefix%[[%prefix% ]]}%surname%{%suffix%[[, %suffix%]]}{%prename%[[, %prename%]]}";
565 firstnameform = buf ? buf->params().documentClass().getCiteMacro(engine_type, "!firstbynameform")
566 : "%prename% {%prefix%[[%prefix% ]]}%surname%{%suffix%[[, %suffix%]]}";
567 string othernameform = buf ? buf->params().documentClass().getCiteMacro(engine_type, "!othernameform")
568 : "{%prefix%[[%prefix% ]]}%surname%{%suffix%[[, %suffix%]]}{%prename%[[, %prename%]]}";
570 othernameform = buf ? buf->params().documentClass().getCiteMacro(engine_type, "!otherbynameform")
571 : "%prename% {%prefix%[[%prefix% ]]}%surname%{%suffix%[[, %suffix%]]}";
572 string citenameform = buf ? buf->params().documentClass().getCiteMacro(engine_type, "!citenameform")
573 : "{%prefix%[[%prefix% ]]}%surname%";
575 // Shorten the list (with et al.) if forceshort is set
576 // and the list can actually be shortened, else if maxcitenames
577 // is passed and full is not set.
578 bool shorten = forceshort && authors.size() > 1;
579 vector<docstring>::const_iterator it = authors.begin();
580 vector<docstring>::const_iterator en = authors.end();
581 for (size_t i = 0; it != en; ++it, ++i) {
582 if (i >= maxnames && !full) {
586 if (*it == "others") {
587 retval += buf ? buf->B_(etal) : from_ascii(etal);
590 if (i > 0 && i == authors.size() - 1) {
591 if (authors.size() == 2)
592 retval += buf ? buf->B_(pairnamesep) : from_ascii(pairnamesep);
594 retval += buf ? buf->B_(lastnamesep) : from_ascii(lastnamesep);
596 retval += buf ? buf->B_(namesep) : from_ascii(namesep);
598 retval += (i == 0) ? constructName(*it, firstnameform)
599 : constructName(*it, othernameform);
601 retval += constructName(*it, citenameform);
605 retval = constructName(authors[0], firstnameform) + (buf ? buf->B_(etal) : from_ascii(etal));
607 retval = constructName(authors[0], citenameform) + (buf ? buf->B_(etal) : from_ascii(etal));
610 return convertLaTeXCommands(retval);
614 docstring const BibTeXInfo::getYear() const
617 // first try legacy year field
618 docstring year = operator[]("year");
621 // now try biblatex's date field
622 year = operator[]("date");
623 // Format is [-]YYYY-MM-DD*/[-]YYYY-MM-DD*
624 // We only want the years.
625 static regex const yreg("[-]?([\\d]{4}).*");
626 static regex const ereg(".*/[-]?([\\d]{4}).*");
628 string const date = to_utf8(year);
629 if (!regex_match(date, sm, yreg))
630 // cannot parse year.
632 year = from_ascii(sm[1]);
633 // check for an endyear
634 if (regex_match(date, sm, ereg))
635 year += char_type(0x2013) + from_ascii(sm[1]);
639 docstring const opt = label();
644 docstring tmp = split(opt, authors, '(');
646 // we don't have author (year)
649 tmp = split(tmp, year, ')');
654 void BibTeXInfo::getLocators(docstring & doi, docstring & url, docstring & file) const
657 // get "doi" entry from citation record
658 doi = operator[]("doi");
659 if (!doi.empty() && !prefixIs(doi,from_ascii("http")))
660 doi = "https://doi.org/" + doi;
661 // get "url" entry from citation record
662 url = operator[]("url");
663 // get "file" entry from citation record
664 file = operator[]("file");
666 // Jabref case, field has a format:
667 // Description:Location:Filetype;Description:Location:Filetype...
668 // We will grab only first pdf
670 docstring ret, filedest, tmp;
671 ret = split(file, tmp, ':');
672 tmp = split(ret, filedest, ':');
673 //TODO howto deal with relative directories?
674 FileName f(to_utf8(filedest));
676 file = "file:///" + filedest;
679 // kbibtex case, format:
680 // file1.pdf;file2.pdf
681 // We will grab only first pdf
684 kfile = operator[]("localfile");
685 if (!kfile.empty()) {
686 docstring filedest, tmp;
687 tmp = split(kfile, filedest, ';');
688 //TODO howto deal with relative directories?
689 FileName f(to_utf8(filedest));
691 file = "file:///" + filedest;
697 // try biblatex specific fields, see its manual
698 // 3.13.7 "Electronic Publishing Informationl"
699 docstring eprinttype = operator[]("eprinttype");
700 docstring eprint = operator[]("eprint");
704 if (eprinttype == "arxiv")
705 url = "https://arxiv.org/abs/" + eprint;
706 if (eprinttype == "jstor")
707 url = "https://www.jstor.org/stable/" + eprint;
708 if (eprinttype == "pubmed")
709 url = "http://www.ncbi.nlm.nih.gov/pubmed/" + eprint;
710 if (eprinttype == "hdl")
711 url = "https://hdl.handle.net/" + eprint;
712 if (eprinttype == "googlebooks")
713 url = "http://books.google.com/books?id=" + eprint;
718 // Here can be handled the bibliography environment. All one could do
719 // here is let LyX scan the entry for URL or HRef insets.
725 docstring parseOptions(docstring const & format, string & optkey,
726 docstring & ifpart, docstring & elsepart);
728 // Calls parseOptions to deal with an embedded option, such as:
729 // {%number%[[, no.~%number%]]}
730 // which must appear at the start of format. ifelsepart gets the
731 // whole of the option, and we return what's left after the option.
732 // we return format if there is an error.
733 docstring parseEmbeddedOption(docstring const & format, docstring & ifelsepart)
735 LASSERT(format[0] == '{' && format[1] == '%', return format);
739 docstring const rest = parseOptions(format, optkey, ifpart, elsepart);
740 if (format == rest) { // parse error
741 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
744 LASSERT(rest.size() <= format.size(),
745 { ifelsepart = docstring(); return format; });
746 ifelsepart = format.substr(0, format.size() - rest.size());
751 // Gets a "clause" from a format string, where the clause is
752 // delimited by '[[' and ']]'. Returns what is left after the
753 // clause is removed, and returns format if there is an error.
754 docstring getClause(docstring const & format, docstring & clause)
756 docstring fmt = format;
759 // we'll remove characters from the front of fmt as we
761 while (!fmt.empty()) {
762 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
767 // check for an embedded option
768 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
770 docstring const rest = parseEmbeddedOption(fmt, part);
772 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
777 } else { // it's just a normal character
786 // parse an options string, which must appear at the start of the
787 // format parameter. puts the parsed bits in optkey, ifpart, and
788 // elsepart and returns what's left after the option is removed.
789 // if there's an error, it returns format itself.
790 docstring parseOptions(docstring const & format, string & optkey,
791 docstring & ifpart, docstring & elsepart)
793 LASSERT(format[0] == '{' && format[1] == '%', return format);
795 docstring fmt = format.substr(2);
796 size_t pos = fmt.find('%'); // end of key
797 if (pos == string::npos) {
798 LYXERR0("Error parsing `" << format <<"'. Can't find end of key.");
801 optkey = to_utf8(fmt.substr(0, pos));
802 fmt = fmt.substr(pos + 1);
803 // [[format]] should be next
804 if (fmt[0] != '[' || fmt[1] != '[') {
805 LYXERR0("Error parsing `" << format <<"'. Can't find '[[' after key.");
809 docstring curfmt = fmt;
810 fmt = getClause(curfmt, ifpart);
812 LYXERR0("Error parsing `" << format <<"'. Couldn't get if clause.");
816 if (fmt[0] == '}') // we're done, no else clause
817 return fmt.substr(1);
819 // else part should follow
820 if (fmt[0] != '[' || fmt[1] != '[') {
821 LYXERR0("Error parsing `" << format <<"'. Can't find else clause.");
826 fmt = getClause(curfmt, elsepart);
828 if (fmt == curfmt || fmt[0] != '}') {
829 LYXERR0("Error parsing `" << format <<"'. Can't find end of option.");
832 return fmt.substr(1);
839 Bug #9131 revealed an oddity in how we are generating citation information
840 when more than one key is given. We end up building a longer and longer format
841 string as we go, which we then have to re-parse, over and over and over again,
842 rather than generating the information for the individual keys and then putting
843 all of that together. We do that to deal with the way separators work, from what
844 I can tell, but it still feels like a hack. Fixing this would require quite a
845 bit of work, however.
847 docstring BibTeXInfo::expandFormat(docstring const & format,
848 BibTeXInfoList const & xrefs, int & counter, Buffer const & buf,
849 CiteItem const & ci, bool next, bool second) const
851 // incorrect use of macros could put us in an infinite loop
852 static int const max_passes = 5000;
853 // the use of overly large keys can lead to performance problems, due
854 // to eventual attempts to convert LaTeX macros to unicode. See bug
855 // #8944. By default, the size is limited to 128 (in CiteItem), but
856 // for specific purposes (such as XHTML export), it needs to be enlarged
857 // This is perhaps not the best solution, but it will have to do for now.
858 size_t const max_keysize = ci.max_key_size;
859 odocstringstream ret; // return value
861 bool scanning_key = false;
862 bool scanning_rich = false;
864 CiteEngineType const engine_type = buf.params().citeEngineType();
865 docstring fmt = format;
866 // we'll remove characters from the front of fmt as we
868 while (!fmt.empty()) {
869 if (counter > max_passes) {
870 LYXERR0("Recursion limit reached while parsing `"
875 char_type thischar = fmt[0];
876 if (thischar == '%') {
877 // beginning or end of key
880 scanning_key = false;
881 // so we replace the key with its value, which may be empty
885 buf.params().documentClass().getCiteMacro(engine_type, key);
886 fmt = from_utf8(val) + fmt.substr(1);
889 } else if (prefixIs(key, "B_")) {
890 // a translatable bit (to the Buffer language)
892 buf.params().documentClass().getCiteMacro(engine_type, key);
893 docstring const trans =
894 translateIfPossible(from_utf8(val), buf.params().language->code());
896 } else if (key[0] == '_') {
897 // a translatable bit (to the GUI language)
899 buf.params().documentClass().getCiteMacro(engine_type, key);
900 docstring const trans =
901 translateIfPossible(from_utf8(val));
904 docstring const val =
905 getValueForKey(key, buf, ci, xrefs, max_keysize);
907 ret << from_ascii("{!<span class=\"bib-" + key + "\">!}");
910 ret << from_ascii("{!</span>!}");
918 else if (thischar == '{') {
919 // beginning of option?
921 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
924 if (fmt.size() > 1) {
926 // it is the beginning of an optional format
930 docstring const newfmt =
931 parseOptions(fmt, optkey, ifpart, elsepart);
932 if (newfmt == fmt) // parse error
935 docstring const val =
936 getValueForKey(optkey, buf, ci, xrefs);
937 if (optkey == "next" && next)
938 ret << ifpart; // without expansion
939 else if (optkey == "second" && second) {
941 ret << expandFormat(ifpart, xrefs, newcounter, buf,
943 } else if (!val.empty()) {
945 ret << expandFormat(ifpart, xrefs, newcounter, buf,
947 } else if (!elsepart.empty()) {
949 ret << expandFormat(elsepart, xrefs, newcounter, buf,
952 // fmt will have been shortened for us already
956 // beginning of rich text
957 scanning_rich = true;
959 ret << from_ascii("{!");
963 // we are here if '{' was not followed by % or !.
964 // So it's just a character.
967 else if (scanning_rich && thischar == '!'
968 && fmt.size() > 1 && fmt[1] == '}') {
970 scanning_rich = false;
972 ret << from_ascii("!}");
975 else if (scanning_key)
976 key += char(thischar);
980 } catch (EncodingException & /* e */) {
981 LYXERR0("Uncodable character '" << docstring(1, thischar) << " in citation label!");
987 LYXERR0("Never found end of key in `" << format << "'!");
991 LYXERR0("Never found end of rich text in `" << format << "'!");
998 docstring const & BibTeXInfo::getInfo(BibTeXInfoList const & xrefs,
999 Buffer const & buf, CiteItem const & ci, docstring const & format_in) const
1001 bool const richtext = ci.richtext;
1003 if (!richtext && !info_.empty()) {
1004 info_ = convertLaTeXCommands(processRichtext(info_, false));
1007 if (richtext && !info_richtext_.empty())
1008 return info_richtext_;
1011 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
1016 CiteEngineType const engine_type = buf.params().citeEngineType();
1017 DocumentClass const & dc = buf.params().documentClass();
1018 docstring const & format = format_in.empty()?
1019 from_utf8(dc.getCiteFormat(engine_type, to_utf8(entry_type_)))
1022 info_ = expandFormat(format, xrefs, counter, buf,
1025 if (info_.empty()) {
1026 // this probably shouldn't happen
1031 info_richtext_ = convertLaTeXCommands(processRichtext(info_, true));
1032 return info_richtext_;
1035 info_ = convertLaTeXCommands(processRichtext(info_, false));
1040 docstring const BibTeXInfo::getLabel(BibTeXInfoList const xrefs,
1041 Buffer const & buf, docstring const & format,
1042 CiteItem const & ci, bool next, bool second) const
1047 loclabel = expandFormat(format, xrefs, counter, buf, ci, next, second);
1049 if (!loclabel.empty() && !next) {
1050 loclabel = processRichtext(loclabel, ci.richtext);
1051 loclabel = convertLaTeXCommands(loclabel);
1058 docstring const & BibTeXInfo::operator[](docstring const & field) const
1060 BibTeXInfo::const_iterator it = find(field);
1063 static docstring const empty_value = docstring();
1068 docstring const & BibTeXInfo::operator[](string const & field) const
1070 return operator[](from_ascii(field));
1074 docstring BibTeXInfo::getValueForKey(string const & oldkey, Buffer const & buf,
1075 CiteItem const & ci, BibTeXInfoList const & xrefs, size_t maxsize) const
1077 // anything less is pointless
1078 LASSERT(maxsize >= 16, maxsize = 16);
1079 string key = oldkey;
1080 bool cleanit = false;
1081 if (prefixIs(oldkey, "clean:")) {
1082 key = oldkey.substr(6);
1086 docstring ret = operator[](key);
1087 if (ret.empty() && !xrefs.empty()) {
1088 // xr is a (reference to a) BibTeXInfo const *
1089 for (auto const & xr : xrefs) {
1090 if (xr && !(*xr)[key].empty()) {
1097 // some special keys
1098 // FIXME: dialog, textbefore and textafter have nothing to do with this
1099 if (key == "dialog" && ci.context == CiteItem::Dialog)
1100 ret = from_ascii("x"); // any non-empty string will do
1101 else if (key == "export" && ci.context == CiteItem::Export)
1102 ret = from_ascii("x"); // any non-empty string will do
1103 else if (key == "ifstar" && ci.Starred)
1104 ret = from_ascii("x"); // any non-empty string will do
1105 else if (key == "ifqualified" && ci.isQualified)
1106 ret = from_ascii("x"); // any non-empty string will do
1107 else if (key == "entrytype")
1109 else if (prefixIs(key, "ifentrytype:")
1110 && from_ascii(key.substr(12)) == entry_type_)
1111 ret = from_ascii("x"); // any non-empty string will do
1112 else if (key == "key")
1114 else if (key == "label")
1116 else if (key == "modifier" && modifier_ != 0)
1118 else if (key == "numericallabel")
1120 else if (prefixIs(key, "ifmultiple:")) {
1121 // Return whether we have multiple authors
1122 docstring const kind = operator[](from_ascii(key.substr(11)));
1123 if (multipleAuthors(kind))
1124 ret = from_ascii("x"); // any non-empty string will do
1126 else if (prefixIs(key, "abbrvnames:")) {
1127 // Special key to provide abbreviated name list,
1128 // with respect to maxcitenames. Suitable for Bibliography
1130 docstring const kind = operator[](from_ascii(key.substr(11)));
1131 ret = getAuthorList(&buf, kind, false, false, true);
1132 if (ci.forceUpperCase && isLowerCase(ret[0]))
1133 ret[0] = uppercase(ret[0]);
1134 } else if (prefixIs(key, "fullnames:")) {
1135 // Return a full name list. Suitable for Bibliography
1137 docstring const kind = operator[](from_ascii(key.substr(10)));
1138 ret = getAuthorList(&buf, kind, true, false, true);
1139 if (ci.forceUpperCase && isLowerCase(ret[0]))
1140 ret[0] = uppercase(ret[0]);
1141 } else if (prefixIs(key, "forceabbrvnames:")) {
1142 // Special key to provide abbreviated name lists,
1143 // irrespective of maxcitenames. Suitable for Bibliography
1145 docstring const kind = operator[](from_ascii(key.substr(15)));
1146 ret = getAuthorList(&buf, kind, false, true, true);
1147 if (ci.forceUpperCase && isLowerCase(ret[0]))
1148 ret[0] = uppercase(ret[0]);
1149 } else if (prefixIs(key, "abbrvbynames:")) {
1150 // Special key to provide abbreviated name list,
1151 // with respect to maxcitenames. Suitable for further names inside a
1152 // bibliography item // (such as "ed. by ...")
1153 docstring const kind = operator[](from_ascii(key.substr(11)));
1154 ret = getAuthorList(&buf, kind, false, false, true, false);
1155 if (ci.forceUpperCase && isLowerCase(ret[0]))
1156 ret[0] = uppercase(ret[0]);
1157 } else if (prefixIs(key, "fullbynames:")) {
1158 // Return a full name list. Suitable for further names inside a
1159 // bibliography item // (such as "ed. by ...")
1160 docstring const kind = operator[](from_ascii(key.substr(10)));
1161 ret = getAuthorList(&buf, kind, true, false, true, false);
1162 if (ci.forceUpperCase && isLowerCase(ret[0]))
1163 ret[0] = uppercase(ret[0]);
1164 } else if (prefixIs(key, "forceabbrvbynames:")) {
1165 // Special key to provide abbreviated name lists,
1166 // irrespective of maxcitenames. Suitable for further names inside a
1167 // bibliography item // (such as "ed. by ...")
1168 docstring const kind = operator[](from_ascii(key.substr(15)));
1169 ret = getAuthorList(&buf, kind, false, true, true, false);
1170 if (ci.forceUpperCase && isLowerCase(ret[0]))
1171 ret[0] = uppercase(ret[0]);
1172 } else if (key == "abbrvciteauthor") {
1173 // Special key to provide abbreviated author or
1174 // editor names (suitable for citation labels),
1175 // with respect to maxcitenames.
1176 ret = getAuthorOrEditorList(&buf, false, false);
1177 if (ci.forceUpperCase && isLowerCase(ret[0]))
1178 ret[0] = uppercase(ret[0]);
1179 } else if (key == "fullciteauthor") {
1180 // Return a full author or editor list (for citation labels)
1181 ret = getAuthorOrEditorList(&buf, true, false);
1182 if (ci.forceUpperCase && isLowerCase(ret[0]))
1183 ret[0] = uppercase(ret[0]);
1184 } else if (key == "forceabbrvciteauthor") {
1185 // Special key to provide abbreviated author or
1186 // editor names (suitable for citation labels),
1187 // irrespective of maxcitenames.
1188 ret = getAuthorOrEditorList(&buf, false, true);
1189 if (ci.forceUpperCase && isLowerCase(ret[0]))
1190 ret[0] = uppercase(ret[0]);
1191 } else if (key == "bibentry") {
1192 // Special key to provide the full bibliography entry: see getInfo()
1193 CiteEngineType const engine_type = buf.params().citeEngineType();
1194 DocumentClass const & dc = buf.params().documentClass();
1195 docstring const & format =
1196 from_utf8(dc.getCiteFormat(engine_type, to_utf8(entry_type_), false));
1198 ret = expandFormat(format, xrefs, counter, buf, ci, false, false);
1199 } else if (key == "textbefore")
1200 ret = ci.textBefore;
1201 else if (key == "textafter")
1203 else if (key == "curpretext") {
1204 vector<pair<docstring, docstring>> pres = ci.getPretexts();
1205 vector<pair<docstring, docstring>>::iterator it = pres.begin();
1207 for (; it != pres.end() ; ++it) {
1208 if ((*it).first == bib_key_ && numkey == num_bib_key_) {
1213 if ((*it).first == bib_key_)
1216 } else if (key == "curposttext") {
1217 vector<pair<docstring, docstring>> posts = ci.getPosttexts();
1218 vector<pair<docstring, docstring>>::iterator it = posts.begin();
1220 for (; it != posts.end() ; ++it) {
1221 if ((*it).first == bib_key_ && numkey == num_bib_key_) {
1226 if ((*it).first == bib_key_)
1229 } else if (key == "year")
1234 ret = xml::cleanAttr(ret);
1236 // make sure it is not too big
1237 support::truncateWithEllipsis(ret, maxsize);
1242 //////////////////////////////////////////////////////////////////////
1246 //////////////////////////////////////////////////////////////////////
1250 // A functor for use with sort, leading to case insensitive sorting
1251 bool compareNoCase(const docstring & a, const docstring & b) {
1252 return compare_no_case(a, b) < 0;
1258 vector<docstring> const BiblioInfo::getXRefs(BibTeXInfo const & data, bool const nested) const
1260 vector<docstring> result;
1261 if (!data.isBibTeX())
1263 // Legacy crossref field. This is not nestable.
1264 if (!nested && !data["crossref"].empty()) {
1265 docstring const xrefkey = data["crossref"];
1266 result.push_back(xrefkey);
1267 // However, check for nested xdatas
1268 BiblioInfo::const_iterator it = find(xrefkey);
1270 BibTeXInfo const & xref = it->second;
1271 vector<docstring> const nxdata = getXRefs(xref, true);
1272 if (!nxdata.empty())
1273 result.insert(result.end(), nxdata.begin(), nxdata.end());
1276 // Biblatex's xdata field. Infinitely nestable.
1277 // XData field can consist of a comma-separated list of keys
1278 vector<docstring> const xdatakeys = getVectorFromString(data["xdata"]);
1279 if (!xdatakeys.empty()) {
1280 for (auto const & xdatakey : xdatakeys) {
1281 result.push_back(xdatakey);
1282 BiblioInfo::const_iterator it = find(xdatakey);
1284 BibTeXInfo const & xdata = it->second;
1285 vector<docstring> const nxdata = getXRefs(xdata, true);
1286 if (!nxdata.empty())
1287 result.insert(result.end(), nxdata.begin(), nxdata.end());
1295 vector<docstring> const BiblioInfo::getKeys() const
1297 vector<docstring> bibkeys;
1298 for (auto const & bi : *this)
1299 bibkeys.push_back(bi.first);
1300 sort(bibkeys.begin(), bibkeys.end(), &compareNoCase);
1305 vector<docstring> const BiblioInfo::getFields() const
1307 vector<docstring> bibfields;
1308 for (auto const & fn : field_names_)
1309 bibfields.push_back(fn);
1310 sort(bibfields.begin(), bibfields.end());
1315 vector<docstring> const BiblioInfo::getEntries() const
1317 vector<docstring> bibentries;
1318 for (auto const & et : entry_types_)
1319 bibentries.push_back(et);
1320 sort(bibentries.begin(), bibentries.end());
1325 docstring const BiblioInfo::getAuthorOrEditorList(docstring const & key, Buffer const & buf) const
1327 BiblioInfo::const_iterator it = find(key);
1330 BibTeXInfo const & data = it->second;
1331 return data.getAuthorOrEditorList(&buf, false);
1335 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
1337 BiblioInfo::const_iterator it = find(key);
1340 BibTeXInfo const & data = it->second;
1341 return data.citeNumber();
1344 void BiblioInfo::getLocators(docstring const & key, docstring & doi, docstring & url, docstring & file) const
1346 BiblioInfo::const_iterator it = find(key);
1349 BibTeXInfo const & data = it->second;
1350 data.getLocators(doi,url,file);
1354 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
1356 BiblioInfo::const_iterator it = find(key);
1359 BibTeXInfo const & data = it->second;
1360 docstring year = data.getYear();
1362 // let's try the crossrefs
1363 vector<docstring> const xrefs = getXRefs(data);
1367 for (docstring const & xref : xrefs) {
1368 BiblioInfo::const_iterator const xrefit = find(xref);
1369 if (xrefit == end())
1371 BibTeXInfo const & xref_data = xrefit->second;
1372 year = xref_data.getYear();
1378 if (use_modifier && data.modifier() != 0)
1379 year += data.modifier();
1384 docstring const BiblioInfo::getYear(docstring const & key, Buffer const & buf, bool use_modifier) const
1386 docstring const year = getYear(key, use_modifier);
1388 return buf.B_("No year");
1393 docstring const BiblioInfo::getInfo(docstring const & key,
1394 Buffer const & buf, CiteItem const & ci, docstring const & format) const
1396 BiblioInfo::const_iterator it = find(key);
1398 return docstring(_("Bibliography entry not found!"));
1399 BibTeXInfo const & data = it->second;
1400 BibTeXInfoList xrefptrs;
1401 for (docstring const & xref : getXRefs(data)) {
1402 BiblioInfo::const_iterator const xrefit = find(xref);
1403 if (xrefit != end())
1404 xrefptrs.push_back(&(xrefit->second));
1406 return data.getInfo(xrefptrs, buf, ci, format);
1410 docstring const BiblioInfo::getLabel(vector<docstring> keys,
1411 Buffer const & buf, string const & style, CiteItem const & ci) const
1413 size_t max_size = ci.max_size;
1414 // shorter makes no sense
1415 LASSERT(max_size >= 16, max_size = 16);
1417 // we can't display more than 10 of these, anyway
1418 // but since we truncate in the middle,
1419 // we need to split into two halfs.
1420 bool const too_many_keys = keys.size() > 10;
1421 vector<docstring> lkeys;
1422 if (too_many_keys) {
1423 lkeys.insert(lkeys.end(), keys.end() - 5, keys.end());
1425 keys.insert(keys.end(), lkeys.begin(), lkeys.end());
1428 CiteEngineType const engine_type = buf.params().citeEngineType();
1429 DocumentClass const & dc = buf.params().documentClass();
1430 docstring const & format = from_utf8(dc.getCiteFormat(engine_type, style, false, "cite"));
1431 docstring ret = format;
1432 vector<docstring>::const_iterator key = keys.begin();
1433 vector<docstring>::const_iterator ken = keys.end();
1434 vector<docstring> handled_keys;
1435 for (int i = 0; key != ken; ++key, ++i) {
1436 handled_keys.push_back(*key);
1438 for (auto const & k : handled_keys) {
1442 BiblioInfo::const_iterator it = find(*key);
1443 BibTeXInfo empty_data;
1444 empty_data.key(*key);
1445 BibTeXInfo & data = empty_data;
1446 vector<BibTeXInfo const *> xrefptrs;
1449 for (docstring const & xref : getXRefs(data)) {
1450 BiblioInfo::const_iterator const xrefit = find(xref);
1451 if (xrefit != end())
1452 xrefptrs.push_back(&(xrefit->second));
1456 ret = data.getLabel(xrefptrs, buf, ret, ci, key + 1 != ken, i == 1);
1459 support::truncateWithEllipsis(ret, max_size, true);
1465 bool BiblioInfo::isBibtex(docstring const & key) const
1468 split(key, key1, ',');
1469 BiblioInfo::const_iterator it = find(key1);
1472 return it->second.isBibTeX();
1476 BiblioInfo::CiteStringMap const BiblioInfo::getCiteStrings(
1477 vector<docstring> const & keys, vector<CitationStyle> const & styles,
1478 Buffer const & buf, CiteItem const & ci) const
1481 return vector<pair<docstring,docstring>>();
1484 CiteStringMap csm(styles.size());
1485 for (size_t i = 0; i != csm.size(); ++i) {
1486 style = styles[i].name;
1487 csm[i] = make_pair(from_ascii(style), getLabel(keys, buf, style, ci));
1494 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
1496 bimap_.insert(info.begin(), info.end());
1497 field_names_.insert(info.field_names_.begin(), info.field_names_.end());
1498 entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
1504 // used in xhtml to sort a list of BibTeXInfo objects
1505 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
1507 docstring const lauth = lhs->getAuthorOrEditorList();
1508 docstring const rauth = rhs->getAuthorOrEditorList();
1509 docstring const lyear = lhs->getYear();
1510 docstring const ryear = rhs->getYear();
1511 docstring const ltitl = lhs->operator[]("title");
1512 docstring const rtitl = rhs->operator[]("title");
1513 return (lauth < rauth)
1514 || (lauth == rauth && lyear < ryear)
1515 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
1521 void BiblioInfo::collectCitedEntries(Buffer const & buf)
1523 cited_entries_.clear();
1524 // We are going to collect all the citation keys used in the document,
1525 // getting them from the TOC.
1526 // FIXME We may want to collect these differently, in the first case,
1527 // so that we might have them in order of appearance.
1528 set<docstring> citekeys;
1529 Toc const & toc = *buf.tocBackend().toc("citation");
1530 for (auto const & t : toc) {
1531 if (t.str().empty())
1533 vector<docstring> const keys = getVectorFromString(t.str());
1534 citekeys.insert(keys.begin(), keys.end());
1536 if (citekeys.empty())
1539 // We have a set of the keys used in this document.
1540 // We will now convert it to a list of the BibTeXInfo objects used in
1542 vector<BibTeXInfo const *> bi;
1543 for (auto const & ck : citekeys) {
1544 BiblioInfo::const_iterator const bt = find(ck);
1545 if (bt == end() || !bt->second.isBibTeX())
1547 bi.push_back(&(bt->second));
1550 sort(bi.begin(), bi.end(), lSorter);
1552 // Now we can write the sorted keys
1553 // b is a BibTeXInfo const *
1554 for (auto const & b : bi)
1555 cited_entries_.push_back(b->key());
1559 void BiblioInfo::makeCitationLabels(Buffer const & buf)
1561 collectCitedEntries(buf);
1562 CiteEngineType const engine_type = buf.params().citeEngineType();
1563 bool const numbers = (engine_type & ENGINE_TYPE_NUMERICAL);
1567 // used to remember the last one we saw
1568 // we'll be comparing entries to see if we need to add
1569 // modifiers, like "1984a"
1570 map<docstring, BibTeXInfo>::iterator last = bimap_.end();
1572 // add letters to years
1573 for (auto const & ce : cited_entries_) {
1574 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(ce);
1575 // this shouldn't happen, but...
1576 if (biit == bimap_.end())
1577 // ...fail gracefully, anyway.
1579 BibTeXInfo & entry = biit->second;
1581 docstring const num = convert<docstring>(++keynumber);
1582 entry.setCiteNumber(num);
1584 // The first test here is checking whether this is the first
1585 // time through the loop. If so, then we do not have anything
1586 // with which to compare.
1587 if (last != bimap_.end()
1588 && entry.getAuthorOrEditorList() == last->second.getAuthorOrEditorList()
1589 // we access the year via getYear() so as to get it from the xref,
1590 // if we need to do so
1591 && getYear(entry.key()) == getYear(last->second.key())) {
1592 if (modifier == 0) {
1593 // so the last one should have been 'a'
1594 last->second.setModifier('a');
1596 } else if (modifier == 'z')
1603 entry.setModifier(modifier);
1604 // remember the last one
1609 for (auto const & ce : cited_entries_) {
1610 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(ce);
1611 // this shouldn't happen, but...
1612 if (biit == bimap_.end())
1613 // ...fail gracefully, anyway.
1615 BibTeXInfo & entry = biit->second;
1617 entry.label(entry.citeNumber());
1619 docstring const auth = entry.getAuthorOrEditorList(&buf, false);
1620 // we do it this way so as to access the xref, if necessary
1621 // note that this also gives us the modifier
1622 docstring const year = getYear(ce, buf, true);
1623 if (!auth.empty() && !year.empty())
1624 entry.label(auth + ' ' + year);
1626 entry.label(entry.key());
1632 //////////////////////////////////////////////////////////////////////
1636 //////////////////////////////////////////////////////////////////////
1639 CitationStyle citationStyleFromString(string const & command,
1640 BufferParams const & params)
1643 if (command.empty())
1646 string const alias = params.getCiteAlias(command);
1647 string cmd = alias.empty() ? command : alias;
1648 if (isUpperCase(command[0])) {
1649 cs.forceUpperCase = true;
1650 cmd[0] = lowercase(cmd[0]);
1653 size_t const n = command.size() - 1;
1654 if (command[n] == '*') {
1655 cs.hasStarredVersion = true;
1656 if (suffixIs(cmd, '*'))
1657 cmd = cmd.substr(0, cmd.size() - 1);
1665 string citationStyleToString(const CitationStyle & cs, bool const latex)
1667 string cmd = latex ? cs.cmd : cs.name;
1668 if (cs.forceUpperCase)
1669 cmd[0] = uppercase(cmd[0]);
1670 if (cs.hasStarredVersion)
1676 docstring authorsToDocBookAuthorGroup(docstring const & authorsString, XMLStream & xs, Buffer const & buf)
1678 // This function closely mimics getAuthorList, but produces DocBook instead of text.
1679 // It has been greatly simplified, as the complete list of authors is always produced. No separators are required,
1680 // as the output has a database-like shape.
1681 // constructName has also been merged within, as it becomes really simple and leads to no copy-paste.
1683 if (authorsString.empty()) {
1687 // Split the input list of authors into individual authors.
1688 vector<docstring> const authors = getAuthors(authorsString);
1690 // Retrieve the "et al." variation.
1691 string const etal = buf.params().documentClass().getCiteMacro(buf.params().citeEngineType(), "_etal");
1693 // Output the list of authors.
1694 xs << xml::StartTag("authorgroup");
1695 auto it = authors.cbegin();
1696 auto en = authors.cend();
1697 for (size_t i = 0; it != en; ++it, ++i) {
1698 xs << xml::StartTag("author");
1700 xs << xml::StartTag("personname");
1702 docstring name = *it;
1704 // All authors go in a <personname>. If more structure is known, use it; otherwise (just "et al."), print it as such.
1705 if (name == "others") {
1708 name_parts parts = nameParts(name);
1709 if (! parts.prefix.empty()) {
1710 xs << xml::StartTag("honorific");
1712 xs << xml::EndTag("honorific");
1715 if (! parts.prename.empty()) {
1716 xs << xml::StartTag("firstname");
1717 xs << parts.prename;
1718 xs << xml::EndTag("firstname");
1721 if (! parts.surname.empty()) {
1722 xs << xml::StartTag("surname");
1723 xs << parts.surname;
1724 xs << xml::EndTag("surname");
1727 if (! parts.suffix.empty()) {
1728 xs << xml::StartTag("othername", "role=\"suffix\"");
1730 xs << xml::EndTag("othername");
1735 xs << xml::EndTag("personname");
1737 xs << xml::EndTag("author");
1740 // Could add an affiliation after <personname>, but not stored in BibTeX.
1742 xs << xml::EndTag("authorgroup");