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();
56 InsetCitation::~InsetCitation()
59 /* We do not use buffer() because Coverity believes that this
60 * may throw an exception. Actually this code path is not
61 * taken when buffer_ == 0 */
62 buffer_->removeBiblioTempFiles();
66 // May well be over-ridden when session settings are loaded
67 // in GuiCitation. Unfortunately, that will not happen until
68 // such a dialog is created.
69 bool InsetCitation::last_literal = true;
72 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
74 static ParamInfo param_info_;
76 // standard cite does only take one argument, but biblatex, jurabib
77 // and natbib extend this to two arguments, so
78 // we have to allow both here. InsetCitation takes care that
79 // LaTeX output is nevertheless correct.
80 if (param_info_.empty()) {
81 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
82 ParamInfo::HANDLING_LATEXIFY);
83 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
84 ParamInfo::HANDLING_LATEXIFY);
85 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
86 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
87 ParamInfo::HANDLING_LATEXIFY);
88 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
89 ParamInfo::HANDLING_LATEXIFY);
90 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
96 // We allow any command here, since we fall back to cite
97 // anyway if a command is not allowed by a style
98 bool InsetCitation::isCompatibleCommand(string const &)
104 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
105 vector<CitationStyle> const & valid_styles) const
107 CitationStyle cs = valid_styles[0];
108 cs.forceUpperCase = false;
109 cs.hasStarredVersion = false;
111 string normalized_input = input;
112 string::size_type const n = input.size() - 1;
113 if (isUpperCase(input[0]))
114 normalized_input[0] = lowercase(input[0]);
116 normalized_input = normalized_input.substr(0, n);
118 string const alias = bp.getCiteAlias(normalized_input);
120 normalized_input = alias;
122 vector<CitationStyle>::const_iterator it = valid_styles.begin();
123 vector<CitationStyle>::const_iterator end = valid_styles.end();
124 for (; it != end; ++it) {
125 CitationStyle this_cs = *it;
126 if (this_cs.name == normalized_input) {
136 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
138 switch (cmd.action()) {
139 case LFUN_INSET_EDIT:
142 case LFUN_INSET_MODIFY: {
143 buffer().removeBiblioTempFiles();
144 cache.recalculate = true;
145 if (cmd.getArg(0) == "toggleparam") {
146 string cmdname = getCmdName();
148 buffer().masterParams().getCiteAlias(cmdname);
151 string const par = cmd.getArg(1);
152 string newcmdname = cmdname;
154 if (suffixIs(cmdname, "*"))
155 newcmdname = rtrim(cmdname, "*");
157 newcmdname = cmdname + "*";
158 } else if (par == "casing") {
159 if (isUpperCase(cmdname[0]))
160 newcmdname[0] = lowercase(cmdname[0]);
162 newcmdname[0] = uppercase(newcmdname[0]);
164 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
169 InsetCommand::doDispatch(cur, cmd);
173 bool InsetCitation::openCitationPossible() const
175 Buffer const & buf = *buffer_;
176 // only after the buffer is loaded from file...
177 if (!buf.isFullyLoaded())
180 BiblioInfo const & bi = buf.masterBibInfo();
184 docstring const & key = getParam("key");
188 // does bibtex item contains some locator?
189 vector<docstring> keys = getVectorFromString(key);
190 docstring doi, url, file;
191 for (docstring const & kvar : keys) {
192 bi.getLocators(kvar, doi, url, file);
193 if (!file.empty() || !doi.empty() || !url.empty())
197 // last resort: is external script activated?
198 return lyxrc.citation_search;
201 void InsetCitation::openCitation()
203 Buffer const & buf = *buffer_;
204 BiblioInfo const & bi = buf.masterBibInfo();
205 docstring const & key = getParam("key");
207 vector<docstring> keys = getVectorFromString(key);
208 docstring titledata, doi, url, file;
209 for (docstring const & kvar : keys) {
211 titledata = bi.getInfo(kvar, buffer(), ci,
212 from_ascii(lyxrc.citation_search_pattern));
213 // some cleanup: commas and " and ", as used in name lists,
214 // are not expected in file names
215 titledata = subst(titledata, from_ascii(","), docstring());
216 titledata = subst(titledata, from_ascii(" and "), from_ascii(" "));
217 bi.getLocators(kvar, doi, url, file);
218 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
219 << url << " file:" << file << " title data:" << titledata
220 << " citation search: " << lyxrc.citation_search
221 << " citation search pattern: " << lyxrc.citation_search_pattern);
225 } else if (!doi.empty()) {
227 } else if (!url.empty()) {
230 locator = "EXTERNAL " + titledata;
232 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
238 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
239 FuncStatus & status) const
241 switch (cmd.action()) {
242 // Handle the alias case
243 case LFUN_INSET_MODIFY:
244 if (cmd.getArg(0) == "changetype") {
245 string cmdname = getCmdName();
247 buffer().masterParams().getCiteAlias(cmdname);
250 if (suffixIs(cmdname, "*"))
251 cmdname = rtrim(cmdname, "*");
252 string const newtype = cmd.getArg(1);
253 status.setEnabled(isCompatibleCommand(newtype));
254 status.setOnOff(newtype == cmdname);
256 if (cmd.getArg(0) == "toggleparam") {
257 string cmdname = getCmdName();
259 buffer().masterParams().getCiteAlias(cmdname);
262 vector<CitationStyle> citation_styles =
263 buffer().masterParams().citeStyles();
264 CitationStyle cs = getCitationStyle(buffer().masterParams(),
265 cmdname, citation_styles);
266 if (cmd.getArg(1) == "star") {
267 status.setEnabled(cs.hasStarredVersion);
268 status.setOnOff(suffixIs(cmdname, "*"));
270 else if (cmd.getArg(1) == "casing") {
271 status.setEnabled(cs.forceUpperCase);
272 status.setOnOff(isUpperCase(cmdname[0]));
276 case LFUN_INSET_EDIT:
277 return openCitationPossible();
279 return InsetCommand::getStatus(cur, cmd, status);
284 bool InsetCitation::addKey(string const & key)
286 docstring const ukey = from_utf8(key);
287 docstring const & curkeys = getParam("key");
288 if (curkeys.empty()) {
289 setParam("key", ukey);
290 cache.recalculate = true;
294 vector<docstring> keys = getVectorFromString(curkeys);
295 vector<docstring>::const_iterator it = keys.begin();
296 vector<docstring>::const_iterator en = keys.end();
297 for (; it != en; ++it) {
299 LYXERR0("Key " << key << " already present.");
303 keys.push_back(ukey);
304 setParam("key", getStringFromVector(keys));
305 cache.recalculate = true;
310 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
312 Buffer const & buf = bv.buffer();
313 // Only after the buffer is loaded from file...
314 if (!buf.isFullyLoaded())
317 BiblioInfo const & bi = buf.masterBibInfo();
319 return _("No bibliography defined!");
321 docstring const & key = getParam("key");
323 return _("No citations selected!");
327 vector<docstring> keys = getVectorFromString(key);
328 if (keys.size() == 1)
329 return bi.getInfo(keys[0], buffer(), ci);
334 for (docstring const & kvar : keys) {
335 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
336 // limit to reasonable size.
337 if (count > 9 && keys.size() > 11) {
338 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
340 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
344 if (key_info.empty())
346 tip += "<li>" + key_info + "</li>";
356 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
357 vector<CitationStyle> const & valid_styles)
359 CitationStyle cs = valid_styles[0];
360 cs.forceUpperCase = false;
361 cs.hasStarredVersion = false;
363 string normalized_input = input;
364 string::size_type const n = input.size() - 1;
365 if (isUpperCase(input[0]))
366 normalized_input[0] = lowercase(input[0]);
368 normalized_input = normalized_input.substr(0, n);
370 string const alias = bp.getCiteAlias(normalized_input);
372 normalized_input = alias;
374 vector<CitationStyle>::const_iterator it = valid_styles.begin();
375 vector<CitationStyle>::const_iterator end = valid_styles.end();
376 for (; it != end; ++it) {
377 CitationStyle this_cs = *it;
378 if (this_cs.name == normalized_input) {
384 cs.forceUpperCase &= input[0] == uppercase(input[0]);
385 cs.hasStarredVersion &= input[n] == '*';
391 inline docstring wrapCitation(docstring const & key,
392 docstring const & content, bool for_xhtml)
396 // we have to do the escaping here, because we will ultimately
397 // write this as a raw string, so as not to escape the tags.
398 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
399 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
402 } // anonymous namespace
405 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
407 vector<docstring> ps =
408 getVectorFromString(p, from_ascii("\t"));
410 for (docstring const & s: ps) {
413 if (contains(s, ' '))
414 val = split(s, key, ' ');
415 res.push_back(make_pair(key, val));
420 docstring InsetCitation::generateLabel(bool for_xhtml) const
423 label = complexLabel(for_xhtml);
425 // Fallback to fail-safe
427 label = basicLabel(for_xhtml);
433 docstring InsetCitation::complexLabel(bool for_xhtml) const
435 Buffer const & buf = buffer();
436 // Only start the process off after the buffer is loaded from file.
437 if (!buf.isFullyLoaded())
440 docstring const & key = getParam("key");
442 BiblioInfo const & biblist = buf.masterBibInfo();
444 // mark broken citations
447 if (biblist.empty()) {
453 return _("No citations selected!");
455 // check all citations
456 // we only really want the last 'false', to suppress trimming, but
457 // we need to give the other defaults, too, to set it.
458 vector<docstring> keys =
459 getVectorFromString(key, from_ascii(","), false, false);
460 for (auto const & k : keys) {
461 if (biblist.find(k) == biblist.end()) {
467 string cite_type = getCmdName();
468 bool const uppercase = isUpperCase(cite_type[0]);
470 cite_type[0] = lowercase(cite_type[0]);
471 bool const starred = (cite_type[cite_type.size() - 1] == '*');
473 cite_type = cite_type.substr(0, cite_type.size() - 1);
476 string const alias = buf.masterParams().getCiteAlias(cite_type);
480 // FIXME: allow to add cite macros
482 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
483 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
486 CitationStyle cs = getCitationStyle(buffer().masterParams(),
487 cite_type, buffer().masterParams().citeStyles());
488 bool const qualified = cs.hasQualifiedList
490 || !getParam("pretextlist").empty()
491 || !getParam("posttextlist").empty());
492 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
493 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
496 ci.textBefore = getParam("before");
497 ci.textAfter = getParam("after");
498 ci.forceUpperCase = uppercase;
499 ci.Starred = starred;
500 ci.max_size = UINT_MAX;
501 ci.isQualified = qualified;
503 ci.posttexts = posts;
505 ci.max_key_size = UINT_MAX;
506 ci.context = CiteItem::Export;
508 ci.richtext = for_xhtml;
509 label = biblist.getLabel(keys, buffer(), cite_type, ci);
514 docstring InsetCitation::basicLabel(bool for_xhtml) const
516 docstring keys = getParam("key");
521 // if there is no comma, then everything goes into key
522 // and keys will be empty.
523 keys = split(keys, key, ',');
526 label += wrapCitation(key, key, for_xhtml);
527 } while (!keys.empty());
529 docstring const & after = getParam("after");
531 label += ", " + after;
533 return '[' + label + ']';
537 bool InsetCitation::forceLTR(OutputParams const & rp) const
539 // We have to force LTR for numeric references
540 // [= bibliography, plain BibTeX, numeric natbib
541 // and biblatex]. Except for XeTeX/bidi. See #3005.
542 if (rp.useBidiPackage())
544 return (buffer().masterParams().citeEngine() == "basic"
545 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
548 docstring InsetCitation::screenLabel() const
550 return cache.screen_label;
554 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
556 if (!cache.recalculate && buffer().citeLabelsValid())
558 // The label may have changed, so we have to re-create it.
559 docstring const glabel = generateLabel();
560 cache.recalculate = false;
561 cache.generated_label = glabel;
562 unsigned int const maxLabelChars = 45;
563 cache.screen_label = glabel;
564 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
568 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
569 UpdateType, TocBackend & backend) const
572 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
573 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
574 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
575 // then we will also need to change that routine.
578 tocitem = _("BROKEN: ");
579 tocitem += getParam("key");
580 TocBuilder & b = backend.builder("citation");
581 b.pushItem(cpit, tocitem, output_active);
584 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
585 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
590 int InsetCitation::plaintext(odocstringstream & os,
591 OutputParams const &, size_t) const
593 string const & cmd = getCmdName();
597 docstring const label = generateLabel();
603 static docstring const cleanupWhitespace(docstring const & citelist)
605 docstring::const_iterator it = citelist.begin();
606 docstring::const_iterator end = citelist.end();
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 (; it != end; ++it) {
614 if (*it != ' ' || last != ',')
621 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
623 if (getCmdName() == "nocite")
626 // Split the different citations (on ","), so that one tag can be output for each of them.
627 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
628 docstring citations = getParam("key");
629 if (citations.find(',') == string::npos) {
630 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
633 while (pos != string::npos) {
634 pos = citations.find(',');
635 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
636 citations.erase(0, pos + 1);
638 if (pos != string::npos) {
646 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
648 if (getCmdName() == "nocite")
651 // have to output this raw, because generateLabel() will include tags
652 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
658 void InsetCitation::toString(odocstream & os) const
660 odocstringstream ods;
661 plaintext(ods, OutputParams(nullptr));
666 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
672 // Have to overwrite the default InsetCommand method in order to check that
673 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
674 // citations and then changes his mind, turning natbib support off. The output
675 // should revert to the default citation command as provided by the citation
676 // engine, e.g. \cite[]{} for the basic engine.
677 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
679 // When this is a child compiled on its own, we use the children
680 // own bibinfo, else the master's
681 BiblioInfo const & bi = runparams.is_child
682 ? buffer().masterBibInfo() : buffer().bibInfo();
683 docstring const key = getParam("key");
684 // "keyonly" command: output the plain key and stop.
685 if (getCmdName() == "keyonly") {
686 // Special command to only return the key
687 if (!bi.isBibtex(getParam("key")))
688 // escape chars with bibitems
689 os << escape(cleanupWhitespace(key));
691 os << cleanupWhitespace(key);
694 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
695 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
696 getCmdName(), citation_styles);
698 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
700 // check if we have to do a qualified list
701 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
702 bool const qualified = cs.hasQualifiedList
703 && (!getParam("pretextlist").empty()
704 || !getParam("posttextlist").empty());
706 if (runparams.inulemcmd > 0)
709 os << "\\" << cite_str;
714 ParamInfo const & pinfo = findInfo(string());
715 docstring before = params().prepareCommand(runparams, getParam("before"),
716 pinfo["before"].handling());
717 docstring after = params().prepareCommand(runparams, getParam("after"),
718 pinfo["after"].handling());
719 if (!before.empty() && cs.textBefore) {
721 os << '(' << protectArgument(before, '(', ')')
722 << ")(" << protectArgument(after, '(', ')') << ')';
724 os << '[' << protectArgument(before) << "]["
725 << protectArgument(after) << ']';
726 } else if (!after.empty() && cs.textAfter) {
728 os << '(' << protectArgument(after, '(', ')') << ')';
730 os << '[' << protectArgument(after) << ']';
733 if (!bi.isBibtex(key))
734 // escape chars with bibitems
735 os << '{' << escape(cleanupWhitespace(key)) << '}';
738 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
739 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
740 for (docstring const & k : keys) {
742 QualifiedList::iterator it = pres.begin();
743 for (; it != pres.end() ; ++it) {
744 if ((*it).first == k) {
745 prenote = (*it).second;
750 docstring bef = params().prepareCommand(runparams, prenote,
751 pinfo["pretextlist"].handling());
753 QualifiedList::iterator pit = posts.begin();
754 for (; pit != posts.end() ; ++pit) {
755 if ((*pit).first == k) {
756 postnote = (*pit).second;
761 docstring aft = params().prepareCommand(runparams, postnote,
762 pinfo["posttextlist"].handling());
764 os << '[' << protectArgument(bef)
765 << "][" << protectArgument(aft) << ']';
766 else if (!aft.empty())
767 os << '[' << protectArgument(aft) << ']';
768 os << '{' << k << '}';
771 os << '{' << cleanupWhitespace(key) << '}';
774 if (runparams.inulemcmd)
779 pair<int, int> InsetCitation::isWords() const
781 docstring const label = generateLabel(false);
782 return pair<int, int>(label.size(), wordCount(label));
786 string InsetCitation::contextMenuName() const
788 return "context-citation";