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"
27 #include "output_xhtml.h"
28 #include "output_docbook.h"
29 #include "ParIterator.h"
30 #include "texstream.h"
31 #include "TocBackend.h"
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/FileNameList.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
43 using namespace lyx::support;
47 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
48 : InsetCommand(buf, p)
50 buffer().removeBiblioTempFiles();
54 InsetCitation::~InsetCitation()
57 /* We do not use buffer() because Coverity believes that this
58 * may throw an exception. Actually this code path is not
59 * taken when buffer_ == 0 */
60 buffer_->removeBiblioTempFiles();
64 // May well be over-ridden when session settings are loaded
65 // in GuiCitation. Unfortunately, that will not happen until
66 // such a dialog is created.
67 bool InsetCitation::last_literal = true;
70 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
72 static ParamInfo param_info_;
74 // standard cite does only take one argument, but biblatex, jurabib
75 // and natbib extend this to two arguments, so
76 // we have to allow both here. InsetCitation takes care that
77 // LaTeX output is nevertheless correct.
78 if (param_info_.empty()) {
79 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
80 ParamInfo::HANDLING_LATEXIFY);
81 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
82 ParamInfo::HANDLING_LATEXIFY);
83 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
84 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
85 ParamInfo::HANDLING_LATEXIFY);
86 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
87 ParamInfo::HANDLING_LATEXIFY);
88 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
94 // We allow any command here, since we fall back to cite
95 // anyway if a command is not allowed by a style
96 bool InsetCitation::isCompatibleCommand(string const &)
102 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
103 vector<CitationStyle> const & valid_styles) const
105 CitationStyle cs = valid_styles[0];
106 cs.forceUpperCase = false;
107 cs.hasStarredVersion = false;
109 string normalized_input = input;
110 string::size_type const n = input.size() - 1;
111 if (isUpperCase(input[0]))
112 normalized_input[0] = lowercase(input[0]);
114 normalized_input = normalized_input.substr(0, n);
116 string const alias = bp.getCiteAlias(normalized_input);
118 normalized_input = alias;
120 vector<CitationStyle>::const_iterator it = valid_styles.begin();
121 vector<CitationStyle>::const_iterator end = valid_styles.end();
122 for (; it != end; ++it) {
123 CitationStyle this_cs = *it;
124 if (this_cs.name == normalized_input) {
134 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
136 switch (cmd.action()) {
137 case LFUN_INSET_EDIT:
140 case LFUN_INSET_MODIFY: {
141 buffer().removeBiblioTempFiles();
142 cache.recalculate = true;
143 if (cmd.getArg(0) == "toggleparam") {
144 string cmdname = getCmdName();
146 buffer().masterParams().getCiteAlias(cmdname);
149 string const par = cmd.getArg(1);
150 string newcmdname = cmdname;
152 if (suffixIs(cmdname, "*"))
153 newcmdname = rtrim(cmdname, "*");
155 newcmdname = cmdname + "*";
156 } else if (par == "casing") {
157 if (isUpperCase(cmdname[0]))
158 newcmdname[0] = lowercase(cmdname[0]);
160 newcmdname[0] = uppercase(newcmdname[0]);
162 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
167 InsetCommand::doDispatch(cur, cmd);
172 void InsetCitation::openCitation(){
173 Buffer const & buf = *buffer_;
174 // Only after the buffer is loaded from file...
175 if (!buf.isFullyLoaded())
178 BiblioInfo const & bi = buf.masterBibInfo();
182 docstring const & key = getParam("key");
186 vector<docstring> keys = getVectorFromString(key);
187 docstring year, author, doi, url, file;
188 for (docstring const & kvar : keys) {
189 year = bi.getYear(kvar, buffer(), false);
190 author = bi.getAuthorOrEditorList(kvar, buffer());
191 bi.getLocators(kvar, doi, url, file);
192 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
193 << url << " file:" << file << " author:" << author << " year:" << year);
197 } else if (!doi.empty()) {
199 } else if (!url.empty()) {
202 locator = "EXTERNAL " + year + " " + author;
204 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
210 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
211 FuncStatus & status) const
213 switch (cmd.action()) {
214 // Handle the alias case
215 case LFUN_INSET_MODIFY:
216 if (cmd.getArg(0) == "changetype") {
217 string cmdname = getCmdName();
219 buffer().masterParams().getCiteAlias(cmdname);
222 if (suffixIs(cmdname, "*"))
223 cmdname = rtrim(cmdname, "*");
224 string const newtype = cmd.getArg(1);
225 status.setEnabled(isCompatibleCommand(newtype));
226 status.setOnOff(newtype == cmdname);
228 if (cmd.getArg(0) == "toggleparam") {
229 string cmdname = getCmdName();
231 buffer().masterParams().getCiteAlias(cmdname);
234 vector<CitationStyle> citation_styles =
235 buffer().masterParams().citeStyles();
236 CitationStyle cs = getCitationStyle(buffer().masterParams(),
237 cmdname, citation_styles);
238 if (cmd.getArg(1) == "star") {
239 status.setEnabled(cs.hasStarredVersion);
240 status.setOnOff(suffixIs(cmdname, "*"));
242 else if (cmd.getArg(1) == "casing") {
243 status.setEnabled(cs.forceUpperCase);
244 status.setOnOff(isUpperCase(cmdname[0]));
248 case LFUN_INSET_EDIT:
251 return InsetCommand::getStatus(cur, cmd, status);
256 bool InsetCitation::addKey(string const & key)
258 docstring const ukey = from_utf8(key);
259 docstring const & curkeys = getParam("key");
260 if (curkeys.empty()) {
261 setParam("key", ukey);
262 cache.recalculate = true;
266 vector<docstring> keys = getVectorFromString(curkeys);
267 vector<docstring>::const_iterator it = keys.begin();
268 vector<docstring>::const_iterator en = keys.end();
269 for (; it != en; ++it) {
271 LYXERR0("Key " << key << " already present.");
275 keys.push_back(ukey);
276 setParam("key", getStringFromVector(keys));
277 cache.recalculate = true;
282 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
284 Buffer const & buf = bv.buffer();
285 // Only after the buffer is loaded from file...
286 if (!buf.isFullyLoaded())
289 BiblioInfo const & bi = buf.masterBibInfo();
291 return _("No bibliography defined!");
293 docstring const & key = getParam("key");
295 return _("No citations selected!");
299 vector<docstring> keys = getVectorFromString(key);
300 if (keys.size() == 1)
301 return bi.getInfo(keys[0], buffer(), ci);
306 for (docstring const & kvar : keys) {
307 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
308 // limit to reasonable size.
309 if (count > 9 && keys.size() > 11) {
310 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
312 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
316 if (key_info.empty())
318 tip += "<li>" + key_info + "</li>";
328 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
329 vector<CitationStyle> const & valid_styles)
331 CitationStyle cs = valid_styles[0];
332 cs.forceUpperCase = false;
333 cs.hasStarredVersion = false;
335 string normalized_input = input;
336 string::size_type const n = input.size() - 1;
337 if (isUpperCase(input[0]))
338 normalized_input[0] = lowercase(input[0]);
340 normalized_input = normalized_input.substr(0, n);
342 string const alias = bp.getCiteAlias(normalized_input);
344 normalized_input = alias;
346 vector<CitationStyle>::const_iterator it = valid_styles.begin();
347 vector<CitationStyle>::const_iterator end = valid_styles.end();
348 for (; it != end; ++it) {
349 CitationStyle this_cs = *it;
350 if (this_cs.name == normalized_input) {
356 cs.forceUpperCase &= input[0] == uppercase(input[0]);
357 cs.hasStarredVersion &= input[n] == '*';
363 inline docstring wrapCitation(docstring const & key,
364 docstring const & content, bool for_xhtml)
368 // we have to do the escaping here, because we will ultimately
369 // write this as a raw string, so as not to escape the tags.
370 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
371 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
374 } // anonymous namespace
377 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
379 vector<docstring> ps =
380 getVectorFromString(p, from_ascii("\t"));
382 for (docstring const & s: ps) {
385 if (contains(s, ' '))
386 val = split(s, key, ' ');
387 res.push_back(make_pair(key, val));
392 docstring InsetCitation::generateLabel(bool for_xhtml) const
395 label = complexLabel(for_xhtml);
397 // Fallback to fail-safe
399 label = basicLabel(for_xhtml);
405 docstring InsetCitation::complexLabel(bool for_xhtml) const
407 Buffer const & buf = buffer();
408 // Only start the process off after the buffer is loaded from file.
409 if (!buf.isFullyLoaded())
412 docstring const & key = getParam("key");
414 BiblioInfo const & biblist = buf.masterBibInfo();
416 // mark broken citations
419 if (biblist.empty()) {
425 return _("No citations selected!");
427 // check all citations
428 // we only really want the last 'false', to suppress trimming, but
429 // we need to give the other defaults, too, to set it.
430 vector<docstring> keys =
431 getVectorFromString(key, from_ascii(","), false, false);
432 for (auto const & k : keys) {
433 if (biblist.find(k) == biblist.end()) {
439 string cite_type = getCmdName();
440 bool const uppercase = isUpperCase(cite_type[0]);
442 cite_type[0] = lowercase(cite_type[0]);
443 bool const starred = (cite_type[cite_type.size() - 1] == '*');
445 cite_type = cite_type.substr(0, cite_type.size() - 1);
448 string const alias = buf.masterParams().getCiteAlias(cite_type);
452 // FIXME: allow to add cite macros
454 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
455 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
458 CitationStyle cs = getCitationStyle(buffer().masterParams(),
459 cite_type, buffer().masterParams().citeStyles());
460 bool const qualified = cs.hasQualifiedList
462 || !getParam("pretextlist").empty()
463 || !getParam("posttextlist").empty());
464 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
465 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
468 ci.textBefore = getParam("before");
469 ci.textAfter = getParam("after");
470 ci.forceUpperCase = uppercase;
471 ci.Starred = starred;
472 ci.max_size = UINT_MAX;
473 ci.isQualified = qualified;
475 ci.posttexts = posts;
477 ci.max_key_size = UINT_MAX;
478 ci.context = CiteItem::Export;
480 ci.richtext = for_xhtml;
481 label = biblist.getLabel(keys, buffer(), cite_type, ci);
486 docstring InsetCitation::basicLabel(bool for_xhtml) const
488 docstring keys = getParam("key");
493 // if there is no comma, then everything goes into key
494 // and keys will be empty.
495 keys = split(keys, key, ',');
498 label += wrapCitation(key, key, for_xhtml);
499 } while (!keys.empty());
501 docstring const & after = getParam("after");
503 label += ", " + after;
505 return '[' + label + ']';
509 bool InsetCitation::forceLTR(OutputParams const & rp) const
511 // We have to force LTR for numeric references
512 // [= bibliography, plain BibTeX, numeric natbib
513 // and biblatex]. Except for XeTeX/bidi. See #3005.
514 if (rp.useBidiPackage())
516 return (buffer().masterParams().citeEngine() == "basic"
517 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
520 docstring InsetCitation::screenLabel() const
522 return cache.screen_label;
526 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
528 if (!cache.recalculate && buffer().citeLabelsValid())
530 // The label may have changed, so we have to re-create it.
531 docstring const glabel = generateLabel();
532 cache.recalculate = false;
533 cache.generated_label = glabel;
534 unsigned int const maxLabelChars = 45;
535 cache.screen_label = glabel;
536 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
540 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
541 UpdateType, TocBackend & backend) const
544 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
545 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
546 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
547 // then we will also need to change that routine.
550 tocitem = _("BROKEN: ");
551 tocitem += getParam("key");
552 TocBuilder & b = backend.builder("citation");
553 b.pushItem(cpit, tocitem, output_active);
556 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
557 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
562 int InsetCitation::plaintext(odocstringstream & os,
563 OutputParams const &, size_t) const
565 string const & cmd = getCmdName();
569 docstring const label = generateLabel(false);
575 static docstring const cleanupWhitespace(docstring const & citelist)
577 docstring::const_iterator it = citelist.begin();
578 docstring::const_iterator end = citelist.end();
579 // Paranoia check: make sure that there is no whitespace in here
580 // -- at least not behind commas or at the beginning
582 char_type last = ',';
583 for (; it != end; ++it) {
586 if (*it != ' ' || last != ',')
593 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
595 if (getCmdName() == "nocite")
598 // Split the different citations (on ","), so that one tag can be output for each of them.
599 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
600 docstring citations = getParam("key");
601 if (citations.find(',') == string::npos) {
602 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
605 while (pos != string::npos) {
606 pos = citations.find(',');
607 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
608 citations.erase(0, pos + 1);
610 if (pos != string::npos) {
618 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
620 if (getCmdName() == "nocite")
623 // have to output this raw, because generateLabel() will include tags
624 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
630 void InsetCitation::toString(odocstream & os) const
632 odocstringstream ods;
633 plaintext(ods, OutputParams(0));
638 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
644 // Have to overwrite the default InsetCommand method in order to check that
645 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
646 // citations and then changes his mind, turning natbib support off. The output
647 // should revert to the default citation command as provided by the citation
648 // engine, e.g. \cite[]{} for the basic engine.
649 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
651 // When this is a child compiled on its own, we use the children
652 // own bibinfo, else the master's
653 BiblioInfo const & bi = runparams.is_child
654 ? buffer().masterBibInfo() : buffer().bibInfo();
655 docstring const key = getParam("key");
656 // "keyonly" command: output the plain key and stop.
657 if (getCmdName() == "keyonly") {
658 // Special command to only return the key
659 if (!bi.isBibtex(getParam("key")))
660 // escape chars with bibitems
661 os << escape(cleanupWhitespace(key));
663 os << cleanupWhitespace(key);
666 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
667 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
668 getCmdName(), citation_styles);
670 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
672 // check if we have to do a qualified list
673 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
674 bool const qualified = cs.hasQualifiedList
675 && (!getParam("pretextlist").empty()
676 || !getParam("posttextlist").empty());
678 if (runparams.inulemcmd > 0)
681 os << "\\" << cite_str;
686 ParamInfo const & pinfo = findInfo(string());
687 docstring before = params().prepareCommand(runparams, getParam("before"),
688 pinfo["before"].handling());
689 docstring after = params().prepareCommand(runparams, getParam("after"),
690 pinfo["after"].handling());
691 if (!before.empty() && cs.textBefore) {
693 os << '(' << protectArgument(before, '(', ')')
694 << ")(" << protectArgument(after, '(', ')') << ')';
696 os << '[' << protectArgument(before) << "]["
697 << protectArgument(after) << ']';
698 } else if (!after.empty() && cs.textAfter) {
700 os << '(' << protectArgument(after, '(', ')') << ')';
702 os << '[' << protectArgument(after) << ']';
705 if (!bi.isBibtex(key))
706 // escape chars with bibitems
707 os << '{' << escape(cleanupWhitespace(key)) << '}';
710 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
711 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
712 for (docstring const & k : keys) {
714 QualifiedList::iterator it = pres.begin();
715 for (; it != pres.end() ; ++it) {
716 if ((*it).first == k) {
717 prenote = (*it).second;
722 docstring bef = params().prepareCommand(runparams, prenote,
723 pinfo["pretextlist"].handling());
725 QualifiedList::iterator pit = posts.begin();
726 for (; pit != posts.end() ; ++pit) {
727 if ((*pit).first == k) {
728 postnote = (*pit).second;
733 docstring aft = params().prepareCommand(runparams, postnote,
734 pinfo["posttextlist"].handling());
736 os << '[' << protectArgument(bef)
737 << "][" << protectArgument(aft) << ']';
738 else if (!aft.empty())
739 os << '[' << protectArgument(aft) << ']';
740 os << '{' << k << '}';
743 os << '{' << cleanupWhitespace(key) << '}';
746 if (runparams.inulemcmd)
751 string InsetCitation::contextMenuName() const
753 return "context-citation";