2 * \file InsetCitation.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "InsetCitation.h"
16 #include "BiblioInfo.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
29 #include "output_xhtml.h"
30 #include "output_docbook.h"
31 #include "ParIterator.h"
32 #include "texstream.h"
33 #include "TocBackend.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/FileNameList.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
45 using namespace lyx::support;
49 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
50 : InsetCommand(buf, p)
52 buffer().removeBiblioTempFiles();
57 InsetCitation::~InsetCitation()
60 /* We do not use buffer() because Coverity believes that this
61 * may throw an exception. Actually this code path is not
62 * taken when buffer_ == 0 */
63 buffer_->removeBiblioTempFiles();
67 // May well be over-ridden when session settings are loaded
68 // in GuiCitation. Unfortunately, that will not happen until
69 // such a dialog is created.
70 bool InsetCitation::last_literal = true;
73 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
75 static ParamInfo param_info_;
77 // standard cite does only take one argument, but biblatex, jurabib
78 // and natbib extend this to two arguments, so
79 // we have to allow both here. InsetCitation takes care that
80 // LaTeX output is nevertheless correct.
81 if (param_info_.empty()) {
82 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
83 ParamInfo::HANDLING_LATEXIFY);
84 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
85 ParamInfo::HANDLING_LATEXIFY);
86 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
87 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
88 ParamInfo::HANDLING_LATEXIFY);
89 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
90 ParamInfo::HANDLING_LATEXIFY);
91 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
97 // We allow any command here, since we fall back to cite
98 // anyway if a command is not allowed by a style
99 bool InsetCitation::isCompatibleCommand(string const &)
105 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
106 vector<CitationStyle> const & valid_styles) const
108 CitationStyle cs = valid_styles[0];
109 cs.forceUpperCase = false;
110 cs.hasStarredVersion = false;
112 string normalized_input = input;
113 string::size_type const n = input.size() - 1;
114 if (isUpperCase(input[0]))
115 normalized_input[0] = lowercase(input[0]);
117 normalized_input = normalized_input.substr(0, n);
119 string const alias = bp.getCiteAlias(normalized_input);
121 normalized_input = alias;
123 vector<CitationStyle>::const_iterator it = valid_styles.begin();
124 vector<CitationStyle>::const_iterator end = valid_styles.end();
125 for (; it != end; ++it) {
126 CitationStyle this_cs = *it;
127 if (this_cs.name == normalized_input) {
137 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
139 switch (cmd.action()) {
140 case LFUN_INSET_EDIT:
143 case LFUN_INSET_MODIFY: {
144 buffer().removeBiblioTempFiles();
145 cache.recalculate = true;
146 if (cmd.getArg(0) == "toggleparam") {
147 string cmdname = getCmdName();
149 buffer().masterParams().getCiteAlias(cmdname);
152 string const par = cmd.getArg(1);
153 string newcmdname = cmdname;
155 if (suffixIs(cmdname, "*"))
156 newcmdname = rtrim(cmdname, "*");
158 newcmdname = cmdname + "*";
159 } else if (par == "casing") {
160 if (isUpperCase(cmdname[0]))
161 newcmdname[0] = lowercase(cmdname[0]);
163 newcmdname[0] = uppercase(newcmdname[0]);
165 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
170 InsetCommand::doDispatch(cur, cmd);
171 if (cmd.action() == LFUN_INSET_MODIFY)
176 bool InsetCitation::openCitationPossible() const
178 Buffer const & buf = *buffer_;
179 // only after the buffer is loaded from file...
180 if (!buf.isFullyLoaded())
183 BiblioInfo const & bi = buf.masterBibInfo();
187 docstring const & key = getParam("key");
191 // does bibtex item contains some locator?
192 vector<docstring> keys = getVectorFromString(key);
193 docstring doi, url, file;
194 for (docstring const & kvar : keys) {
195 bi.getLocators(kvar, doi, url, file);
196 if (!file.empty() || !doi.empty() || !url.empty())
200 // last resort: is external script activated?
201 return lyxrc.citation_search;
204 void InsetCitation::openCitation()
206 Buffer const & buf = *buffer_;
207 BiblioInfo const & bi = buf.masterBibInfo();
208 docstring const & key = getParam("key");
210 vector<docstring> keys = getVectorFromString(key);
211 docstring titledata, doi, url, file;
212 for (docstring const & kvar : keys) {
214 titledata = bi.getInfo(kvar, buffer(), ci,
215 from_ascii(lyxrc.citation_search_pattern));
216 // some cleanup: commas, " and " and " et al.", as used in name lists,
217 // are not expected in file names
218 titledata = subst(titledata, from_ascii(","), docstring());
219 titledata = subst(titledata, from_ascii(" and "), from_ascii(" "));
220 titledata = subst(titledata, from_ascii(" et al."), docstring());
221 bi.getLocators(kvar, doi, url, file);
222 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
223 << url << " file:" << file << " title data:" << titledata
224 << " citation search: " << lyxrc.citation_search
225 << " citation search pattern: " << lyxrc.citation_search_pattern);
229 } else if (!doi.empty()) {
231 } else if (!url.empty()) {
234 locator = "EXTERNAL " + titledata;
236 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
242 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
243 FuncStatus & status) const
245 switch (cmd.action()) {
246 // Handle the alias case
247 case LFUN_INSET_MODIFY:
248 if (cmd.getArg(0) == "changetype") {
249 string cmdname = getCmdName();
251 buffer().masterParams().getCiteAlias(cmdname);
254 if (suffixIs(cmdname, "*"))
255 cmdname = rtrim(cmdname, "*");
256 string const newtype = cmd.getArg(1);
257 status.setEnabled(isCompatibleCommand(newtype));
258 status.setOnOff(newtype == cmdname);
260 if (cmd.getArg(0) == "toggleparam") {
261 string cmdname = getCmdName();
263 buffer().masterParams().getCiteAlias(cmdname);
266 vector<CitationStyle> citation_styles =
267 buffer().masterParams().citeStyles();
268 CitationStyle cs = getCitationStyle(buffer().masterParams(),
269 cmdname, citation_styles);
270 if (cmd.getArg(1) == "star") {
271 status.setEnabled(cs.hasStarredVersion);
272 status.setOnOff(suffixIs(cmdname, "*"));
274 else if (cmd.getArg(1) == "casing") {
275 status.setEnabled(cs.forceUpperCase);
276 status.setOnOff(isUpperCase(cmdname[0]));
280 case LFUN_INSET_EDIT:
281 return openCitationPossible();
283 return InsetCommand::getStatus(cur, cmd, status);
288 bool InsetCitation::addKey(string const & key)
290 docstring const ukey = from_utf8(trim(key));
291 docstring const & curkeys = getParam("key");
292 if (curkeys.empty()) {
293 setParam("key", ukey);
294 cache.recalculate = true;
298 vector<docstring> keys = getVectorFromString(curkeys);
299 for (auto const & k : keys) {
301 LYXERR0("Key " << key << " already present.");
305 keys.push_back(ukey);
306 setParam("key", getStringFromVector(keys));
307 cache.recalculate = true;
312 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
314 Buffer const & buf = bv.buffer();
315 // Only after the buffer is loaded from file...
316 if (!buf.isFullyLoaded())
319 BiblioInfo const & bi = buf.masterBibInfo();
321 return _("No bibliography defined!");
323 docstring const & key = getParam("key");
325 return _("No citations selected!");
329 vector<docstring> keys = getVectorFromString(key);
330 if (keys.size() == 1)
331 return bi.getInfo(keys[0], buffer(), ci);
336 for (docstring const & kvar : keys) {
337 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
338 // limit to reasonable size.
339 if (count > 9 && keys.size() > 11) {
340 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
342 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
346 if (key_info.empty())
348 tip += "<li>" + key_info + "</li>";
358 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
359 vector<CitationStyle> const & valid_styles)
361 CitationStyle cs = valid_styles[0];
362 cs.forceUpperCase = false;
363 cs.hasStarredVersion = false;
365 string normalized_input = input;
366 string::size_type const n = input.size() - 1;
367 if (isUpperCase(input[0]))
368 normalized_input[0] = lowercase(input[0]);
370 normalized_input = normalized_input.substr(0, n);
372 string const alias = bp.getCiteAlias(normalized_input);
374 normalized_input = alias;
376 vector<CitationStyle>::const_iterator it = valid_styles.begin();
377 vector<CitationStyle>::const_iterator end = valid_styles.end();
378 for (; it != end; ++it) {
379 CitationStyle this_cs = *it;
380 if (this_cs.name == normalized_input) {
386 cs.forceUpperCase &= input[0] == uppercase(input[0]);
387 cs.hasStarredVersion &= input[n] == '*';
393 inline docstring wrapCitation(docstring const & key,
394 docstring const & content, bool for_xhtml)
398 // we have to do the escaping here, because we will ultimately
399 // write this as a raw string, so as not to escape the tags.
400 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
401 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
404 } // anonymous namespace
407 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
409 vector<docstring> ps =
410 getVectorFromString(p, from_ascii("\t"));
412 for (docstring const & s: ps) {
415 if (contains(s, ' '))
416 val = split(s, key, ' ');
417 res.push_back(make_pair(key, val));
422 docstring InsetCitation::generateLabel(bool for_xhtml) const
425 label = complexLabel(for_xhtml);
427 // Fallback to fail-safe
429 label = basicLabel(for_xhtml);
435 docstring InsetCitation::complexLabel(bool for_xhtml) const
437 Buffer const & buf = buffer();
438 // Only start the process off after the buffer is loaded from file.
439 if (!buf.isFullyLoaded())
442 docstring const & key = getParam("key");
444 BiblioInfo const & biblist = buf.masterBibInfo();
446 // mark broken citations
449 if (biblist.empty()) {
455 return _("No citations selected!");
457 // check all citations
458 // we only really want the last 'false', to suppress trimming, but
459 // we need to give the other defaults, too, to set it.
460 vector<docstring> keys =
461 getVectorFromString(key, from_ascii(","), false, false);
462 for (auto const & k : keys) {
463 if (biblist.find(k) == biblist.end()) {
469 string cite_type = getCmdName();
470 bool const uppercase = isUpperCase(cite_type[0]);
472 cite_type[0] = lowercase(cite_type[0]);
473 bool const starred = (cite_type[cite_type.size() - 1] == '*');
475 cite_type = cite_type.substr(0, cite_type.size() - 1);
478 string const alias = buf.masterParams().getCiteAlias(cite_type);
482 // FIXME: allow to add cite macros
484 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
485 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
488 CitationStyle cs = getCitationStyle(buffer().masterParams(),
489 cite_type, buffer().masterParams().citeStyles());
490 bool const qualified = cs.hasQualifiedList
492 || !getParam("pretextlist").empty()
493 || !getParam("posttextlist").empty());
494 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
495 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
498 ci.textBefore = getParam("before");
499 ci.textAfter = getParam("after");
500 ci.forceUpperCase = uppercase;
501 ci.Starred = starred;
502 ci.max_size = UINT_MAX;
503 ci.isQualified = qualified;
505 ci.posttexts = posts;
507 ci.max_key_size = UINT_MAX;
508 ci.context = CiteItem::Export;
510 ci.richtext = for_xhtml;
511 label = biblist.getLabel(keys, buffer(), cite_type, ci);
516 docstring InsetCitation::basicLabel(bool for_xhtml) const
518 docstring keys = getParam("key");
523 // if there is no comma, then everything goes into key
524 // and keys will be empty.
525 keys = split(keys, key, ',');
528 label += wrapCitation(key, key, for_xhtml);
529 } while (!keys.empty());
531 docstring const & after = getParam("after");
533 label += ", " + after;
535 return '[' + label + ']';
539 bool InsetCitation::forceLTR(OutputParams const & rp) const
541 // We have to force LTR for numeric references
542 // [= bibliography, plain BibTeX, numeric natbib
543 // and biblatex]. Except for XeTeX/bidi. See #3005.
544 if (rp.useBidiPackage())
546 return (buffer().masterParams().citeEngine() == "basic"
547 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
550 docstring InsetCitation::screenLabel() const
552 return cache.screen_label;
556 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
558 if (!cache.recalculate && buffer().citeLabelsValid())
560 // The label may have changed, so we have to re-create it.
561 docstring const glabel = generateLabel();
562 cache.recalculate = false;
563 cache.generated_label = glabel;
564 unsigned int const maxLabelChars = 45;
565 cache.screen_label = glabel;
566 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
570 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
571 UpdateType, TocBackend & backend) const
574 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
575 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
576 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
577 // then we will also need to change that routine.
580 tocitem = _("BROKEN: ");
581 tocitem += getParam("key");
582 TocBuilder & b = backend.builder("citation");
583 b.pushItem(cpit, tocitem, output_active);
586 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
587 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
592 int InsetCitation::plaintext(odocstringstream & os,
593 OutputParams const &, size_t) const
595 string const & cmd = getCmdName();
599 docstring const label = generateLabel();
605 static docstring const cleanupWhitespace(docstring const & citelist)
607 // Paranoia check: make sure that there is no whitespace in here
608 // -- at least not behind commas or at the beginning
610 char_type last = ',';
611 for (char_type c : citelist) {
614 if (c != ' ' || last != ',')
621 void InsetCitation::cleanKeys() {
622 docstring cleankeys = cleanupWhitespace(getParam("key"));
623 setParam("key", cleankeys);
626 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
628 if (getCmdName() == "nocite")
631 // Split the different citations (on ","), so that one tag can be output for each of them.
632 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
633 docstring citations = getParam("key");
634 if (citations.find(',') == string::npos) {
635 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
638 while (pos != string::npos) {
639 pos = citations.find(',');
640 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
641 citations.erase(0, pos + 1);
643 if (pos != string::npos) {
651 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
653 if (getCmdName() == "nocite")
656 // have to output this raw, because generateLabel() will include tags
657 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
663 void InsetCitation::toString(odocstream & os) const
665 odocstringstream ods;
666 plaintext(ods, OutputParams(nullptr));
671 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
677 // Have to overwrite the default InsetCommand method in order to check that
678 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
679 // citations and then changes his mind, turning natbib support off. The output
680 // should revert to the default citation command as provided by the citation
681 // engine, e.g. \cite[]{} for the basic engine.
682 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
684 // When this is a child compiled on its own, we use the children
685 // own bibinfo, else the master's
686 BiblioInfo const & bi = runparams.is_child
687 ? buffer().masterBibInfo() : buffer().bibInfo();
688 docstring const key = getParam("key");
689 // "keyonly" command: output the plain key and stop.
690 if (getCmdName() == "keyonly") {
691 // Special command to only return the key
692 if (!bi.isBibtex(getParam("key")))
693 // escape chars with bibitems
694 os << escape(cleanupWhitespace(key));
696 os << cleanupWhitespace(key);
699 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
700 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
701 getCmdName(), citation_styles);
703 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
705 // check if we have to do a qualified list
706 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
707 bool const qualified = cs.hasQualifiedList
708 && (!getParam("pretextlist").empty()
709 || !getParam("posttextlist").empty());
711 if (runparams.inulemcmd > 0)
714 os << "\\" << cite_str;
719 ParamInfo const & pinfo = findInfo(string());
720 docstring before = params().prepareCommand(runparams, getParam("before"),
721 pinfo["before"].handling());
722 docstring after = params().prepareCommand(runparams, getParam("after"),
723 pinfo["after"].handling());
724 if (!before.empty() && cs.textBefore) {
726 os << '(' << protectArgument(before, '(', ')')
727 << ")(" << protectArgument(after, '(', ')') << ')';
729 os << '[' << protectArgument(before) << "]["
730 << protectArgument(after) << ']';
731 } else if (!after.empty() && cs.textAfter) {
733 os << '(' << protectArgument(after, '(', ')') << ')';
735 os << '[' << protectArgument(after) << ']';
738 if (!bi.isBibtex(key))
739 // escape chars with bibitems
740 os << '{' << escape(cleanupWhitespace(key)) << '}';
743 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
744 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
745 for (docstring const & k : keys) {
747 QualifiedList::iterator it = pres.begin();
748 for (; it != pres.end() ; ++it) {
749 if ((*it).first == k) {
750 prenote = (*it).second;
755 docstring bef = params().prepareCommand(runparams, prenote,
756 pinfo["pretextlist"].handling());
758 QualifiedList::iterator pit = posts.begin();
759 for (; pit != posts.end() ; ++pit) {
760 if ((*pit).first == k) {
761 postnote = (*pit).second;
766 docstring aft = params().prepareCommand(runparams, postnote,
767 pinfo["posttextlist"].handling());
769 os << '[' << protectArgument(bef)
770 << "][" << protectArgument(aft) << ']';
771 else if (!aft.empty())
772 os << '[' << protectArgument(aft) << ']';
773 os << '{' << k << '}';
776 os << '{' << cleanupWhitespace(key) << '}';
779 if (runparams.inulemcmd)
784 pair<int, int> InsetCitation::isWords() const
786 docstring const label = generateLabel(false);
787 return pair<int, int>(label.size(), wordCount(label));
791 string InsetCitation::contextMenuName() const
793 return "context-citation";