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"
40 #include "support/textutils.h"
46 using namespace lyx::support;
50 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
51 : InsetCommand(buf, p)
53 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);
174 bool InsetCitation::openCitationPossible() const
176 Buffer const & buf = *buffer_;
177 // only after the buffer is loaded from file...
178 if (!buf.isFullyLoaded())
181 BiblioInfo const & bi = buf.masterBibInfo();
185 docstring const & key = getParam("key");
189 // does bibtex item contains some locator?
190 vector<docstring> keys = getVectorFromString(key);
191 docstring doi, url, file;
192 for (docstring const & kvar : keys) {
193 bi.getLocators(kvar, doi, url, file);
194 if (!file.empty() || !doi.empty() || !url.empty())
198 // last resort: is external script activated?
199 return lyxrc.citation_search;
202 void InsetCitation::openCitation()
204 Buffer const & buf = *buffer_;
205 BiblioInfo const & bi = buf.masterBibInfo();
206 docstring const & key = getParam("key");
208 vector<docstring> keys = getVectorFromString(key);
209 docstring titledata, doi, url, file;
210 for (docstring const & kvar : keys) {
212 titledata = bi.getInfo(kvar, buffer(), ci,
213 from_ascii(lyxrc.citation_search_pattern));
214 // some cleanup: commas and " and ", as used in name lists,
215 // are not expected in file names
216 titledata = subst(titledata, from_ascii(","), docstring());
217 titledata = subst(titledata, from_ascii(" and "), from_ascii(" "));
218 bi.getLocators(kvar, doi, url, file);
219 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
220 << url << " file:" << file << " title data:" << titledata
221 << " citation search: " << lyxrc.citation_search
222 << " citation search pattern: " << lyxrc.citation_search_pattern);
226 } else if (!doi.empty()) {
228 } else if (!url.empty()) {
231 locator = "EXTERNAL " + titledata;
233 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
239 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
240 FuncStatus & status) const
242 switch (cmd.action()) {
243 // Handle the alias case
244 case LFUN_INSET_MODIFY:
245 if (cmd.getArg(0) == "changetype") {
246 string cmdname = getCmdName();
248 buffer().masterParams().getCiteAlias(cmdname);
251 if (suffixIs(cmdname, "*"))
252 cmdname = rtrim(cmdname, "*");
253 string const newtype = cmd.getArg(1);
254 status.setEnabled(isCompatibleCommand(newtype));
255 status.setOnOff(newtype == cmdname);
257 if (cmd.getArg(0) == "toggleparam") {
258 string cmdname = getCmdName();
260 buffer().masterParams().getCiteAlias(cmdname);
263 vector<CitationStyle> citation_styles =
264 buffer().masterParams().citeStyles();
265 CitationStyle cs = getCitationStyle(buffer().masterParams(),
266 cmdname, citation_styles);
267 if (cmd.getArg(1) == "star") {
268 status.setEnabled(cs.hasStarredVersion);
269 status.setOnOff(suffixIs(cmdname, "*"));
271 else if (cmd.getArg(1) == "casing") {
272 status.setEnabled(cs.forceUpperCase);
273 status.setOnOff(isUpperCase(cmdname[0]));
277 case LFUN_INSET_EDIT:
278 return openCitationPossible();
280 return InsetCommand::getStatus(cur, cmd, status);
285 bool InsetCitation::addKey(string const & key)
287 docstring const ukey = from_utf8(key);
288 docstring const & curkeys = getParam("key");
289 if (curkeys.empty()) {
290 setParam("key", ukey);
291 cache.recalculate = true;
295 vector<docstring> keys = getVectorFromString(curkeys);
296 vector<docstring>::const_iterator it = keys.begin();
297 vector<docstring>::const_iterator en = keys.end();
298 for (; it != en; ++it) {
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 docstring::const_iterator it = citelist.begin();
607 docstring::const_iterator end = citelist.end();
608 // Paranoia check: make sure that there is no whitespace in here
609 // -- at least not behind commas or at the beginning
611 char_type last = ',';
612 for (; it != end; ++it) {
615 if (*it != ' ' || last != ',')
622 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
624 if (getCmdName() == "nocite")
627 // Split the different citations (on ","), so that one tag can be output for each of them.
628 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
629 docstring citations = getParam("key");
630 if (citations.find(',') == string::npos) {
631 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
634 while (pos != string::npos) {
635 pos = citations.find(',');
636 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
637 citations.erase(0, pos + 1);
639 if (pos != string::npos) {
647 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
649 if (getCmdName() == "nocite")
652 // have to output this raw, because generateLabel() will include tags
653 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
659 void InsetCitation::toString(odocstream & os) const
661 odocstringstream ods;
662 plaintext(ods, OutputParams(nullptr));
667 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
673 // Have to overwrite the default InsetCommand method in order to check that
674 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
675 // citations and then changes his mind, turning natbib support off. The output
676 // should revert to the default citation command as provided by the citation
677 // engine, e.g. \cite[]{} for the basic engine.
678 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
680 // When this is a child compiled on its own, we use the children
681 // own bibinfo, else the master's
682 BiblioInfo const & bi = runparams.is_child
683 ? buffer().masterBibInfo() : buffer().bibInfo();
684 docstring const key = getParam("key");
685 // "keyonly" command: output the plain key and stop.
686 if (getCmdName() == "keyonly") {
687 // Special command to only return the key
688 if (!bi.isBibtex(getParam("key")))
689 // escape chars with bibitems
690 os << escape(cleanupWhitespace(key));
692 os << cleanupWhitespace(key);
695 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
696 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
697 getCmdName(), citation_styles);
699 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
701 // check if we have to do a qualified list
702 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
703 bool const qualified = cs.hasQualifiedList
704 && (!getParam("pretextlist").empty()
705 || !getParam("posttextlist").empty());
707 if (runparams.inulemcmd > 0)
710 os << "\\" << cite_str;
715 ParamInfo const & pinfo = findInfo(string());
716 docstring before = params().prepareCommand(runparams, getParam("before"),
717 pinfo["before"].handling());
718 docstring after = params().prepareCommand(runparams, getParam("after"),
719 pinfo["after"].handling());
720 if (!before.empty() && cs.textBefore) {
722 os << '(' << protectArgument(before, '(', ')')
723 << ")(" << protectArgument(after, '(', ')') << ')';
725 os << '[' << protectArgument(before) << "]["
726 << protectArgument(after) << ']';
727 } else if (!after.empty() && cs.textAfter) {
729 os << '(' << protectArgument(after, '(', ')') << ')';
731 os << '[' << protectArgument(after) << ']';
734 if (!bi.isBibtex(key))
735 // escape chars with bibitems
736 os << '{' << escape(cleanupWhitespace(key)) << '}';
739 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
740 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
741 for (docstring const & k : keys) {
743 QualifiedList::iterator it = pres.begin();
744 for (; it != pres.end() ; ++it) {
745 if ((*it).first == k) {
746 prenote = (*it).second;
751 docstring bef = params().prepareCommand(runparams, prenote,
752 pinfo["pretextlist"].handling());
754 QualifiedList::iterator pit = posts.begin();
755 for (; pit != posts.end() ; ++pit) {
756 if ((*pit).first == k) {
757 postnote = (*pit).second;
762 docstring aft = params().prepareCommand(runparams, postnote,
763 pinfo["posttextlist"].handling());
765 os << '[' << protectArgument(bef)
766 << "][" << protectArgument(aft) << ']';
767 else if (!aft.empty())
768 os << '[' << protectArgument(aft) << ']';
769 os << '{' << k << '}';
772 os << '{' << cleanupWhitespace(key) << '}';
775 if (runparams.inulemcmd)
779 pair<int, int> InsetCitation::isWords() const
781 docstring const label = generateLabel(false);
783 for (auto const & c : label) {
787 return pair<int, int>(label.size(), words);
791 string InsetCitation::contextMenuName() const
793 return "context-citation";