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 ", 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 bi.getLocators(kvar, doi, url, file);
221 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
222 << url << " file:" << file << " title data:" << titledata
223 << " citation search: " << lyxrc.citation_search
224 << " citation search pattern: " << lyxrc.citation_search_pattern);
228 } else if (!doi.empty()) {
230 } else if (!url.empty()) {
233 locator = "EXTERNAL " + titledata;
235 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
241 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
242 FuncStatus & status) const
244 switch (cmd.action()) {
245 // Handle the alias case
246 case LFUN_INSET_MODIFY:
247 if (cmd.getArg(0) == "changetype") {
248 string cmdname = getCmdName();
250 buffer().masterParams().getCiteAlias(cmdname);
253 if (suffixIs(cmdname, "*"))
254 cmdname = rtrim(cmdname, "*");
255 string const newtype = cmd.getArg(1);
256 status.setEnabled(isCompatibleCommand(newtype));
257 status.setOnOff(newtype == cmdname);
259 if (cmd.getArg(0) == "toggleparam") {
260 string cmdname = getCmdName();
262 buffer().masterParams().getCiteAlias(cmdname);
265 vector<CitationStyle> citation_styles =
266 buffer().masterParams().citeStyles();
267 CitationStyle cs = getCitationStyle(buffer().masterParams(),
268 cmdname, citation_styles);
269 if (cmd.getArg(1) == "star") {
270 status.setEnabled(cs.hasStarredVersion);
271 status.setOnOff(suffixIs(cmdname, "*"));
273 else if (cmd.getArg(1) == "casing") {
274 status.setEnabled(cs.forceUpperCase);
275 status.setOnOff(isUpperCase(cmdname[0]));
279 case LFUN_INSET_EDIT:
280 return openCitationPossible();
282 return InsetCommand::getStatus(cur, cmd, status);
287 bool InsetCitation::addKey(string const & key)
289 docstring const ukey = from_utf8(trim(key));
290 docstring const & curkeys = getParam("key");
291 if (curkeys.empty()) {
292 setParam("key", ukey);
293 cache.recalculate = true;
297 vector<docstring> keys = getVectorFromString(curkeys);
298 for (auto const & k : keys) {
300 LYXERR0("Key " << key << " already present.");
304 keys.push_back(ukey);
305 setParam("key", getStringFromVector(keys));
306 cache.recalculate = true;
311 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
313 Buffer const & buf = bv.buffer();
314 // Only after the buffer is loaded from file...
315 if (!buf.isFullyLoaded())
318 BiblioInfo const & bi = buf.masterBibInfo();
320 return _("No bibliography defined!");
322 docstring const & key = getParam("key");
324 return _("No citations selected!");
328 vector<docstring> keys = getVectorFromString(key);
329 if (keys.size() == 1)
330 return bi.getInfo(keys[0], buffer(), ci);
335 for (docstring const & kvar : keys) {
336 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
337 // limit to reasonable size.
338 if (count > 9 && keys.size() > 11) {
339 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
341 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
345 if (key_info.empty())
347 tip += "<li>" + key_info + "</li>";
357 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
358 vector<CitationStyle> const & valid_styles)
360 CitationStyle cs = valid_styles[0];
361 cs.forceUpperCase = false;
362 cs.hasStarredVersion = false;
364 string normalized_input = input;
365 string::size_type const n = input.size() - 1;
366 if (isUpperCase(input[0]))
367 normalized_input[0] = lowercase(input[0]);
369 normalized_input = normalized_input.substr(0, n);
371 string const alias = bp.getCiteAlias(normalized_input);
373 normalized_input = alias;
375 vector<CitationStyle>::const_iterator it = valid_styles.begin();
376 vector<CitationStyle>::const_iterator end = valid_styles.end();
377 for (; it != end; ++it) {
378 CitationStyle this_cs = *it;
379 if (this_cs.name == normalized_input) {
385 cs.forceUpperCase &= input[0] == uppercase(input[0]);
386 cs.hasStarredVersion &= input[n] == '*';
392 inline docstring wrapCitation(docstring const & key,
393 docstring const & content, bool for_xhtml)
397 // we have to do the escaping here, because we will ultimately
398 // write this as a raw string, so as not to escape the tags.
399 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
400 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
403 } // anonymous namespace
406 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
408 vector<docstring> ps =
409 getVectorFromString(p, from_ascii("\t"));
411 for (docstring const & s: ps) {
414 if (contains(s, ' '))
415 val = split(s, key, ' ');
416 res.push_back(make_pair(key, val));
421 docstring InsetCitation::generateLabel(bool for_xhtml) const
424 label = complexLabel(for_xhtml);
426 // Fallback to fail-safe
428 label = basicLabel(for_xhtml);
434 docstring InsetCitation::complexLabel(bool for_xhtml) const
436 Buffer const & buf = buffer();
437 // Only start the process off after the buffer is loaded from file.
438 if (!buf.isFullyLoaded())
441 docstring const & key = getParam("key");
443 BiblioInfo const & biblist = buf.masterBibInfo();
445 // mark broken citations
448 if (biblist.empty()) {
454 return _("No citations selected!");
456 // check all citations
457 // we only really want the last 'false', to suppress trimming, but
458 // we need to give the other defaults, too, to set it.
459 vector<docstring> keys =
460 getVectorFromString(key, from_ascii(","), false, false);
461 for (auto const & k : keys) {
462 if (biblist.find(k) == biblist.end()) {
468 string cite_type = getCmdName();
469 bool const uppercase = isUpperCase(cite_type[0]);
471 cite_type[0] = lowercase(cite_type[0]);
472 bool const starred = (cite_type[cite_type.size() - 1] == '*');
474 cite_type = cite_type.substr(0, cite_type.size() - 1);
477 string const alias = buf.masterParams().getCiteAlias(cite_type);
481 // FIXME: allow to add cite macros
483 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
484 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
487 CitationStyle cs = getCitationStyle(buffer().masterParams(),
488 cite_type, buffer().masterParams().citeStyles());
489 bool const qualified = cs.hasQualifiedList
491 || !getParam("pretextlist").empty()
492 || !getParam("posttextlist").empty());
493 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
494 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
497 ci.textBefore = getParam("before");
498 ci.textAfter = getParam("after");
499 ci.forceUpperCase = uppercase;
500 ci.Starred = starred;
501 ci.max_size = UINT_MAX;
502 ci.isQualified = qualified;
504 ci.posttexts = posts;
506 ci.max_key_size = UINT_MAX;
507 ci.context = CiteItem::Export;
509 ci.richtext = for_xhtml;
510 label = biblist.getLabel(keys, buffer(), cite_type, ci);
515 docstring InsetCitation::basicLabel(bool for_xhtml) const
517 docstring keys = getParam("key");
522 // if there is no comma, then everything goes into key
523 // and keys will be empty.
524 keys = split(keys, key, ',');
527 label += wrapCitation(key, key, for_xhtml);
528 } while (!keys.empty());
530 docstring const & after = getParam("after");
532 label += ", " + after;
534 return '[' + label + ']';
538 bool InsetCitation::forceLTR(OutputParams const & rp) const
540 // We have to force LTR for numeric references
541 // [= bibliography, plain BibTeX, numeric natbib
542 // and biblatex]. Except for XeTeX/bidi. See #3005.
543 if (rp.useBidiPackage())
545 return (buffer().masterParams().citeEngine() == "basic"
546 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
549 docstring InsetCitation::screenLabel() const
551 return cache.screen_label;
555 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
557 if (!cache.recalculate && buffer().citeLabelsValid())
559 // The label may have changed, so we have to re-create it.
560 docstring const glabel = generateLabel();
561 cache.recalculate = false;
562 cache.generated_label = glabel;
563 unsigned int const maxLabelChars = 45;
564 cache.screen_label = glabel;
565 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
569 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
570 UpdateType, TocBackend & backend) const
573 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
574 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
575 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
576 // then we will also need to change that routine.
579 tocitem = _("BROKEN: ");
580 tocitem += getParam("key");
581 TocBuilder & b = backend.builder("citation");
582 b.pushItem(cpit, tocitem, output_active);
585 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
586 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
591 int InsetCitation::plaintext(odocstringstream & os,
592 OutputParams const &, size_t) const
594 string const & cmd = getCmdName();
598 docstring const label = generateLabel();
604 static docstring const cleanupWhitespace(docstring const & citelist)
606 // Paranoia check: make sure that there is no whitespace in here
607 // -- at least not behind commas or at the beginning
609 char_type last = ',';
610 for (char_type c : citelist) {
613 if (c != ' ' || last != ',')
620 void InsetCitation::cleanKeys() {
621 docstring cleankeys = cleanupWhitespace(getParam("key"));
622 setParam("key", cleankeys);
625 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
627 if (getCmdName() == "nocite")
630 // Split the different citations (on ","), so that one tag can be output for each of them.
631 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
632 docstring citations = getParam("key");
633 if (citations.find(',') == string::npos) {
634 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
637 while (pos != string::npos) {
638 pos = citations.find(',');
639 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
640 citations.erase(0, pos + 1);
642 if (pos != string::npos) {
650 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
652 if (getCmdName() == "nocite")
655 // have to output this raw, because generateLabel() will include tags
656 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
662 void InsetCitation::toString(odocstream & os) const
664 odocstringstream ods;
665 plaintext(ods, OutputParams(nullptr));
670 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
676 // Have to overwrite the default InsetCommand method in order to check that
677 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
678 // citations and then changes his mind, turning natbib support off. The output
679 // should revert to the default citation command as provided by the citation
680 // engine, e.g. \cite[]{} for the basic engine.
681 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
683 // When this is a child compiled on its own, we use the children
684 // own bibinfo, else the master's
685 BiblioInfo const & bi = runparams.is_child
686 ? buffer().masterBibInfo() : buffer().bibInfo();
687 docstring const key = getParam("key");
688 // "keyonly" command: output the plain key and stop.
689 if (getCmdName() == "keyonly") {
690 // Special command to only return the key
691 if (!bi.isBibtex(getParam("key")))
692 // escape chars with bibitems
693 os << escape(cleanupWhitespace(key));
695 os << cleanupWhitespace(key);
698 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
699 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
700 getCmdName(), citation_styles);
702 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
704 // check if we have to do a qualified list
705 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
706 bool const qualified = cs.hasQualifiedList
707 && (!getParam("pretextlist").empty()
708 || !getParam("posttextlist").empty());
710 if (runparams.inulemcmd > 0)
713 os << "\\" << cite_str;
718 ParamInfo const & pinfo = findInfo(string());
719 docstring before = params().prepareCommand(runparams, getParam("before"),
720 pinfo["before"].handling());
721 docstring after = params().prepareCommand(runparams, getParam("after"),
722 pinfo["after"].handling());
723 if (!before.empty() && cs.textBefore) {
725 os << '(' << protectArgument(before, '(', ')')
726 << ")(" << protectArgument(after, '(', ')') << ')';
728 os << '[' << protectArgument(before) << "]["
729 << protectArgument(after) << ']';
730 } else if (!after.empty() && cs.textAfter) {
732 os << '(' << protectArgument(after, '(', ')') << ')';
734 os << '[' << protectArgument(after) << ']';
737 if (!bi.isBibtex(key))
738 // escape chars with bibitems
739 os << '{' << escape(cleanupWhitespace(key)) << '}';
742 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
743 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
744 for (docstring const & k : keys) {
746 QualifiedList::iterator it = pres.begin();
747 for (; it != pres.end() ; ++it) {
748 if ((*it).first == k) {
749 prenote = (*it).second;
754 docstring bef = params().prepareCommand(runparams, prenote,
755 pinfo["pretextlist"].handling());
757 QualifiedList::iterator pit = posts.begin();
758 for (; pit != posts.end() ; ++pit) {
759 if ((*pit).first == k) {
760 postnote = (*pit).second;
765 docstring aft = params().prepareCommand(runparams, postnote,
766 pinfo["posttextlist"].handling());
768 os << '[' << protectArgument(bef)
769 << "][" << protectArgument(aft) << ']';
770 else if (!aft.empty())
771 os << '[' << protectArgument(aft) << ']';
772 os << '{' << k << '}';
775 os << '{' << cleanupWhitespace(key) << '}';
778 if (runparams.inulemcmd)
783 pair<int, int> InsetCitation::isWords() const
785 docstring const label = generateLabel(false);
786 return pair<int, int>(label.size(), wordCount(label));
790 string InsetCitation::contextMenuName() const
792 return "context-citation";