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"
21 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "LaTeXFeatures.h"
28 #include "output_xhtml.h"
29 #include "output_docbook.h"
30 #include "ParIterator.h"
31 #include "texstream.h"
32 #include "TocBackend.h"
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/FileNameList.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
44 using namespace lyx::support;
48 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
49 : InsetCommand(buf, p)
51 buffer().removeBiblioTempFiles();
55 InsetCitation::~InsetCitation()
58 /* We do not use buffer() because Coverity believes that this
59 * may throw an exception. Actually this code path is not
60 * taken when buffer_ == 0 */
61 buffer_->removeBiblioTempFiles();
65 // May well be over-ridden when session settings are loaded
66 // in GuiCitation. Unfortunately, that will not happen until
67 // such a dialog is created.
68 bool InsetCitation::last_literal = true;
71 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
73 static ParamInfo param_info_;
75 // standard cite does only take one argument, but biblatex, jurabib
76 // and natbib extend this to two arguments, so
77 // we have to allow both here. InsetCitation takes care that
78 // LaTeX output is nevertheless correct.
79 if (param_info_.empty()) {
80 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
81 ParamInfo::HANDLING_LATEXIFY);
82 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
83 ParamInfo::HANDLING_LATEXIFY);
84 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
85 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
86 ParamInfo::HANDLING_LATEXIFY);
87 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
88 ParamInfo::HANDLING_LATEXIFY);
89 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
95 // We allow any command here, since we fall back to cite
96 // anyway if a command is not allowed by a style
97 bool InsetCitation::isCompatibleCommand(string const &)
103 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
104 vector<CitationStyle> const & valid_styles) const
106 CitationStyle cs = valid_styles[0];
107 cs.forceUpperCase = false;
108 cs.hasStarredVersion = false;
110 string normalized_input = input;
111 string::size_type const n = input.size() - 1;
112 if (isUpperCase(input[0]))
113 normalized_input[0] = lowercase(input[0]);
115 normalized_input = normalized_input.substr(0, n);
117 string const alias = bp.getCiteAlias(normalized_input);
119 normalized_input = alias;
121 vector<CitationStyle>::const_iterator it = valid_styles.begin();
122 vector<CitationStyle>::const_iterator end = valid_styles.end();
123 for (; it != end; ++it) {
124 CitationStyle this_cs = *it;
125 if (this_cs.name == normalized_input) {
135 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
137 switch (cmd.action()) {
138 case LFUN_INSET_EDIT:
141 case LFUN_INSET_MODIFY: {
142 buffer().removeBiblioTempFiles();
143 cache.recalculate = true;
144 if (cmd.getArg(0) == "toggleparam") {
145 string cmdname = getCmdName();
147 buffer().masterParams().getCiteAlias(cmdname);
150 string const par = cmd.getArg(1);
151 string newcmdname = cmdname;
153 if (suffixIs(cmdname, "*"))
154 newcmdname = rtrim(cmdname, "*");
156 newcmdname = cmdname + "*";
157 } else if (par == "casing") {
158 if (isUpperCase(cmdname[0]))
159 newcmdname[0] = lowercase(cmdname[0]);
161 newcmdname[0] = uppercase(newcmdname[0]);
163 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
168 InsetCommand::doDispatch(cur, cmd);
172 bool InsetCitation::openCitationPossible() const
174 Buffer const & buf = *buffer_;
175 // only after the buffer is loaded from file...
176 if (!buf.isFullyLoaded())
179 BiblioInfo const & bi = buf.masterBibInfo();
183 docstring const & key = getParam("key");
187 // does bibtex item contains some locator?
188 vector<docstring> keys = getVectorFromString(key);
189 docstring doi, url, file;
190 for (docstring const & kvar : keys) {
191 bi.getLocators(kvar, doi, url, file);
192 if (!file.empty() || !doi.empty() || !url.empty())
196 // last resort: is external script activated?
197 return lyxrc.citation_search;
200 void InsetCitation::openCitation()
202 Buffer const & buf = *buffer_;
203 BiblioInfo const & bi = buf.masterBibInfo();
204 docstring const & key = getParam("key");
206 vector<docstring> keys = getVectorFromString(key);
207 docstring titledata, doi, url, file;
208 for (docstring const & kvar : keys) {
210 titledata = bi.getInfo(kvar, buffer(), ci,
211 from_ascii(lyxrc.citation_search_pattern));
212 // some cleanup: commas and " and ", as used in name lists,
213 // are not expected in file names
214 titledata = subst(titledata, from_ascii(","), docstring());
215 titledata = subst(titledata, from_ascii(" and "), from_ascii(" "));
216 bi.getLocators(kvar, doi, url, file);
217 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
218 << url << " file:" << file << " title data:" << titledata);
222 } else if (!doi.empty()) {
224 } else if (!url.empty()) {
227 locator = "EXTERNAL " + titledata;
229 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
235 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
236 FuncStatus & status) const
238 switch (cmd.action()) {
239 // Handle the alias case
240 case LFUN_INSET_MODIFY:
241 if (cmd.getArg(0) == "changetype") {
242 string cmdname = getCmdName();
244 buffer().masterParams().getCiteAlias(cmdname);
247 if (suffixIs(cmdname, "*"))
248 cmdname = rtrim(cmdname, "*");
249 string const newtype = cmd.getArg(1);
250 status.setEnabled(isCompatibleCommand(newtype));
251 status.setOnOff(newtype == cmdname);
253 if (cmd.getArg(0) == "toggleparam") {
254 string cmdname = getCmdName();
256 buffer().masterParams().getCiteAlias(cmdname);
259 vector<CitationStyle> citation_styles =
260 buffer().masterParams().citeStyles();
261 CitationStyle cs = getCitationStyle(buffer().masterParams(),
262 cmdname, citation_styles);
263 if (cmd.getArg(1) == "star") {
264 status.setEnabled(cs.hasStarredVersion);
265 status.setOnOff(suffixIs(cmdname, "*"));
267 else if (cmd.getArg(1) == "casing") {
268 status.setEnabled(cs.forceUpperCase);
269 status.setOnOff(isUpperCase(cmdname[0]));
273 case LFUN_INSET_EDIT:
274 return openCitationPossible();
276 return InsetCommand::getStatus(cur, cmd, status);
281 bool InsetCitation::addKey(string const & key)
283 docstring const ukey = from_utf8(key);
284 docstring const & curkeys = getParam("key");
285 if (curkeys.empty()) {
286 setParam("key", ukey);
287 cache.recalculate = true;
291 vector<docstring> keys = getVectorFromString(curkeys);
292 vector<docstring>::const_iterator it = keys.begin();
293 vector<docstring>::const_iterator en = keys.end();
294 for (; it != en; ++it) {
296 LYXERR0("Key " << key << " already present.");
300 keys.push_back(ukey);
301 setParam("key", getStringFromVector(keys));
302 cache.recalculate = true;
307 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
309 Buffer const & buf = bv.buffer();
310 // Only after the buffer is loaded from file...
311 if (!buf.isFullyLoaded())
314 BiblioInfo const & bi = buf.masterBibInfo();
316 return _("No bibliography defined!");
318 docstring const & key = getParam("key");
320 return _("No citations selected!");
324 vector<docstring> keys = getVectorFromString(key);
325 if (keys.size() == 1)
326 return bi.getInfo(keys[0], buffer(), ci);
331 for (docstring const & kvar : keys) {
332 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
333 // limit to reasonable size.
334 if (count > 9 && keys.size() > 11) {
335 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
337 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
341 if (key_info.empty())
343 tip += "<li>" + key_info + "</li>";
353 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
354 vector<CitationStyle> const & valid_styles)
356 CitationStyle cs = valid_styles[0];
357 cs.forceUpperCase = false;
358 cs.hasStarredVersion = false;
360 string normalized_input = input;
361 string::size_type const n = input.size() - 1;
362 if (isUpperCase(input[0]))
363 normalized_input[0] = lowercase(input[0]);
365 normalized_input = normalized_input.substr(0, n);
367 string const alias = bp.getCiteAlias(normalized_input);
369 normalized_input = alias;
371 vector<CitationStyle>::const_iterator it = valid_styles.begin();
372 vector<CitationStyle>::const_iterator end = valid_styles.end();
373 for (; it != end; ++it) {
374 CitationStyle this_cs = *it;
375 if (this_cs.name == normalized_input) {
381 cs.forceUpperCase &= input[0] == uppercase(input[0]);
382 cs.hasStarredVersion &= input[n] == '*';
388 inline docstring wrapCitation(docstring const & key,
389 docstring const & content, bool for_xhtml)
393 // we have to do the escaping here, because we will ultimately
394 // write this as a raw string, so as not to escape the tags.
395 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
396 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
399 } // anonymous namespace
402 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
404 vector<docstring> ps =
405 getVectorFromString(p, from_ascii("\t"));
407 for (docstring const & s: ps) {
410 if (contains(s, ' '))
411 val = split(s, key, ' ');
412 res.push_back(make_pair(key, val));
417 docstring InsetCitation::generateLabel(bool for_xhtml) const
420 label = complexLabel(for_xhtml);
422 // Fallback to fail-safe
424 label = basicLabel(for_xhtml);
430 docstring InsetCitation::complexLabel(bool for_xhtml) const
432 Buffer const & buf = buffer();
433 // Only start the process off after the buffer is loaded from file.
434 if (!buf.isFullyLoaded())
437 docstring const & key = getParam("key");
439 BiblioInfo const & biblist = buf.masterBibInfo();
441 // mark broken citations
444 if (biblist.empty()) {
450 return _("No citations selected!");
452 // check all citations
453 // we only really want the last 'false', to suppress trimming, but
454 // we need to give the other defaults, too, to set it.
455 vector<docstring> keys =
456 getVectorFromString(key, from_ascii(","), false, false);
457 for (auto const & k : keys) {
458 if (biblist.find(k) == biblist.end()) {
464 string cite_type = getCmdName();
465 bool const uppercase = isUpperCase(cite_type[0]);
467 cite_type[0] = lowercase(cite_type[0]);
468 bool const starred = (cite_type[cite_type.size() - 1] == '*');
470 cite_type = cite_type.substr(0, cite_type.size() - 1);
473 string const alias = buf.masterParams().getCiteAlias(cite_type);
477 // FIXME: allow to add cite macros
479 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
480 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
483 CitationStyle cs = getCitationStyle(buffer().masterParams(),
484 cite_type, buffer().masterParams().citeStyles());
485 bool const qualified = cs.hasQualifiedList
487 || !getParam("pretextlist").empty()
488 || !getParam("posttextlist").empty());
489 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
490 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
493 ci.textBefore = getParam("before");
494 ci.textAfter = getParam("after");
495 ci.forceUpperCase = uppercase;
496 ci.Starred = starred;
497 ci.max_size = UINT_MAX;
498 ci.isQualified = qualified;
500 ci.posttexts = posts;
502 ci.max_key_size = UINT_MAX;
503 ci.context = CiteItem::Export;
505 ci.richtext = for_xhtml;
506 label = biblist.getLabel(keys, buffer(), cite_type, ci);
511 docstring InsetCitation::basicLabel(bool for_xhtml) const
513 docstring keys = getParam("key");
518 // if there is no comma, then everything goes into key
519 // and keys will be empty.
520 keys = split(keys, key, ',');
523 label += wrapCitation(key, key, for_xhtml);
524 } while (!keys.empty());
526 docstring const & after = getParam("after");
528 label += ", " + after;
530 return '[' + label + ']';
534 bool InsetCitation::forceLTR(OutputParams const & rp) const
536 // We have to force LTR for numeric references
537 // [= bibliography, plain BibTeX, numeric natbib
538 // and biblatex]. Except for XeTeX/bidi. See #3005.
539 if (rp.useBidiPackage())
541 return (buffer().masterParams().citeEngine() == "basic"
542 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
545 docstring InsetCitation::screenLabel() const
547 return cache.screen_label;
551 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
553 if (!cache.recalculate && buffer().citeLabelsValid())
555 // The label may have changed, so we have to re-create it.
556 docstring const glabel = generateLabel();
557 cache.recalculate = false;
558 cache.generated_label = glabel;
559 unsigned int const maxLabelChars = 45;
560 cache.screen_label = glabel;
561 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
565 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
566 UpdateType, TocBackend & backend) const
569 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
570 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
571 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
572 // then we will also need to change that routine.
575 tocitem = _("BROKEN: ");
576 tocitem += getParam("key");
577 TocBuilder & b = backend.builder("citation");
578 b.pushItem(cpit, tocitem, output_active);
581 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
582 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
587 int InsetCitation::plaintext(odocstringstream & os,
588 OutputParams const &, size_t) const
590 string const & cmd = getCmdName();
594 docstring const label = generateLabel(false);
600 static docstring const cleanupWhitespace(docstring const & citelist)
602 docstring::const_iterator it = citelist.begin();
603 docstring::const_iterator end = citelist.end();
604 // Paranoia check: make sure that there is no whitespace in here
605 // -- at least not behind commas or at the beginning
607 char_type last = ',';
608 for (; it != end; ++it) {
611 if (*it != ' ' || last != ',')
618 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
620 if (getCmdName() == "nocite")
623 // Split the different citations (on ","), so that one tag can be output for each of them.
624 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
625 docstring citations = getParam("key");
626 if (citations.find(',') == string::npos) {
627 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
630 while (pos != string::npos) {
631 pos = citations.find(',');
632 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
633 citations.erase(0, pos + 1);
635 if (pos != string::npos) {
643 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
645 if (getCmdName() == "nocite")
648 // have to output this raw, because generateLabel() will include tags
649 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
655 void InsetCitation::toString(odocstream & os) const
657 odocstringstream ods;
658 plaintext(ods, OutputParams(0));
663 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
669 // Have to overwrite the default InsetCommand method in order to check that
670 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
671 // citations and then changes his mind, turning natbib support off. The output
672 // should revert to the default citation command as provided by the citation
673 // engine, e.g. \cite[]{} for the basic engine.
674 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
676 // When this is a child compiled on its own, we use the children
677 // own bibinfo, else the master's
678 BiblioInfo const & bi = runparams.is_child
679 ? buffer().masterBibInfo() : buffer().bibInfo();
680 docstring const key = getParam("key");
681 // "keyonly" command: output the plain key and stop.
682 if (getCmdName() == "keyonly") {
683 // Special command to only return the key
684 if (!bi.isBibtex(getParam("key")))
685 // escape chars with bibitems
686 os << escape(cleanupWhitespace(key));
688 os << cleanupWhitespace(key);
691 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
692 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
693 getCmdName(), citation_styles);
695 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
697 // check if we have to do a qualified list
698 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
699 bool const qualified = cs.hasQualifiedList
700 && (!getParam("pretextlist").empty()
701 || !getParam("posttextlist").empty());
703 if (runparams.inulemcmd > 0)
706 os << "\\" << cite_str;
711 ParamInfo const & pinfo = findInfo(string());
712 docstring before = params().prepareCommand(runparams, getParam("before"),
713 pinfo["before"].handling());
714 docstring after = params().prepareCommand(runparams, getParam("after"),
715 pinfo["after"].handling());
716 if (!before.empty() && cs.textBefore) {
718 os << '(' << protectArgument(before, '(', ')')
719 << ")(" << protectArgument(after, '(', ')') << ')';
721 os << '[' << protectArgument(before) << "]["
722 << protectArgument(after) << ']';
723 } else if (!after.empty() && cs.textAfter) {
725 os << '(' << protectArgument(after, '(', ')') << ')';
727 os << '[' << protectArgument(after) << ']';
730 if (!bi.isBibtex(key))
731 // escape chars with bibitems
732 os << '{' << escape(cleanupWhitespace(key)) << '}';
735 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
736 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
737 for (docstring const & k : keys) {
739 QualifiedList::iterator it = pres.begin();
740 for (; it != pres.end() ; ++it) {
741 if ((*it).first == k) {
742 prenote = (*it).second;
747 docstring bef = params().prepareCommand(runparams, prenote,
748 pinfo["pretextlist"].handling());
750 QualifiedList::iterator pit = posts.begin();
751 for (; pit != posts.end() ; ++pit) {
752 if ((*pit).first == k) {
753 postnote = (*pit).second;
758 docstring aft = params().prepareCommand(runparams, postnote,
759 pinfo["posttextlist"].handling());
761 os << '[' << protectArgument(bef)
762 << "][" << protectArgument(aft) << ']';
763 else if (!aft.empty())
764 os << '[' << protectArgument(aft) << ']';
765 os << '{' << k << '}';
768 os << '{' << cleanupWhitespace(key) << '}';
771 if (runparams.inulemcmd)
776 string InsetCitation::contextMenuName() const
778 return "context-citation";