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
219 << " citation search: " << lyxrc.citation_search
220 << " citation search pattern: " << lyxrc.citation_search_pattern);
224 } else if (!doi.empty()) {
226 } else if (!url.empty()) {
229 locator = "EXTERNAL " + titledata;
231 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
237 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
238 FuncStatus & status) const
240 switch (cmd.action()) {
241 // Handle the alias case
242 case LFUN_INSET_MODIFY:
243 if (cmd.getArg(0) == "changetype") {
244 string cmdname = getCmdName();
246 buffer().masterParams().getCiteAlias(cmdname);
249 if (suffixIs(cmdname, "*"))
250 cmdname = rtrim(cmdname, "*");
251 string const newtype = cmd.getArg(1);
252 status.setEnabled(isCompatibleCommand(newtype));
253 status.setOnOff(newtype == cmdname);
255 if (cmd.getArg(0) == "toggleparam") {
256 string cmdname = getCmdName();
258 buffer().masterParams().getCiteAlias(cmdname);
261 vector<CitationStyle> citation_styles =
262 buffer().masterParams().citeStyles();
263 CitationStyle cs = getCitationStyle(buffer().masterParams(),
264 cmdname, citation_styles);
265 if (cmd.getArg(1) == "star") {
266 status.setEnabled(cs.hasStarredVersion);
267 status.setOnOff(suffixIs(cmdname, "*"));
269 else if (cmd.getArg(1) == "casing") {
270 status.setEnabled(cs.forceUpperCase);
271 status.setOnOff(isUpperCase(cmdname[0]));
275 case LFUN_INSET_EDIT:
276 return openCitationPossible();
278 return InsetCommand::getStatus(cur, cmd, status);
283 bool InsetCitation::addKey(string const & key)
285 docstring const ukey = from_utf8(key);
286 docstring const & curkeys = getParam("key");
287 if (curkeys.empty()) {
288 setParam("key", ukey);
289 cache.recalculate = true;
293 vector<docstring> keys = getVectorFromString(curkeys);
294 vector<docstring>::const_iterator it = keys.begin();
295 vector<docstring>::const_iterator en = keys.end();
296 for (; it != en; ++it) {
298 LYXERR0("Key " << key << " already present.");
302 keys.push_back(ukey);
303 setParam("key", getStringFromVector(keys));
304 cache.recalculate = true;
309 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
311 Buffer const & buf = bv.buffer();
312 // Only after the buffer is loaded from file...
313 if (!buf.isFullyLoaded())
316 BiblioInfo const & bi = buf.masterBibInfo();
318 return _("No bibliography defined!");
320 docstring const & key = getParam("key");
322 return _("No citations selected!");
326 vector<docstring> keys = getVectorFromString(key);
327 if (keys.size() == 1)
328 return bi.getInfo(keys[0], buffer(), ci);
333 for (docstring const & kvar : keys) {
334 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
335 // limit to reasonable size.
336 if (count > 9 && keys.size() > 11) {
337 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
339 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
343 if (key_info.empty())
345 tip += "<li>" + key_info + "</li>";
355 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
356 vector<CitationStyle> const & valid_styles)
358 CitationStyle cs = valid_styles[0];
359 cs.forceUpperCase = false;
360 cs.hasStarredVersion = false;
362 string normalized_input = input;
363 string::size_type const n = input.size() - 1;
364 if (isUpperCase(input[0]))
365 normalized_input[0] = lowercase(input[0]);
367 normalized_input = normalized_input.substr(0, n);
369 string const alias = bp.getCiteAlias(normalized_input);
371 normalized_input = alias;
373 vector<CitationStyle>::const_iterator it = valid_styles.begin();
374 vector<CitationStyle>::const_iterator end = valid_styles.end();
375 for (; it != end; ++it) {
376 CitationStyle this_cs = *it;
377 if (this_cs.name == normalized_input) {
383 cs.forceUpperCase &= input[0] == uppercase(input[0]);
384 cs.hasStarredVersion &= input[n] == '*';
390 inline docstring wrapCitation(docstring const & key,
391 docstring const & content, bool for_xhtml)
395 // we have to do the escaping here, because we will ultimately
396 // write this as a raw string, so as not to escape the tags.
397 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
398 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
401 } // anonymous namespace
404 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
406 vector<docstring> ps =
407 getVectorFromString(p, from_ascii("\t"));
409 for (docstring const & s: ps) {
412 if (contains(s, ' '))
413 val = split(s, key, ' ');
414 res.push_back(make_pair(key, val));
419 docstring InsetCitation::generateLabel(bool for_xhtml) const
422 label = complexLabel(for_xhtml);
424 // Fallback to fail-safe
426 label = basicLabel(for_xhtml);
432 docstring InsetCitation::complexLabel(bool for_xhtml) const
434 Buffer const & buf = buffer();
435 // Only start the process off after the buffer is loaded from file.
436 if (!buf.isFullyLoaded())
439 docstring const & key = getParam("key");
441 BiblioInfo const & biblist = buf.masterBibInfo();
443 // mark broken citations
446 if (biblist.empty()) {
452 return _("No citations selected!");
454 // check all citations
455 // we only really want the last 'false', to suppress trimming, but
456 // we need to give the other defaults, too, to set it.
457 vector<docstring> keys =
458 getVectorFromString(key, from_ascii(","), false, false);
459 for (auto const & k : keys) {
460 if (biblist.find(k) == biblist.end()) {
466 string cite_type = getCmdName();
467 bool const uppercase = isUpperCase(cite_type[0]);
469 cite_type[0] = lowercase(cite_type[0]);
470 bool const starred = (cite_type[cite_type.size() - 1] == '*');
472 cite_type = cite_type.substr(0, cite_type.size() - 1);
475 string const alias = buf.masterParams().getCiteAlias(cite_type);
479 // FIXME: allow to add cite macros
481 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
482 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
485 CitationStyle cs = getCitationStyle(buffer().masterParams(),
486 cite_type, buffer().masterParams().citeStyles());
487 bool const qualified = cs.hasQualifiedList
489 || !getParam("pretextlist").empty()
490 || !getParam("posttextlist").empty());
491 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
492 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
495 ci.textBefore = getParam("before");
496 ci.textAfter = getParam("after");
497 ci.forceUpperCase = uppercase;
498 ci.Starred = starred;
499 ci.max_size = UINT_MAX;
500 ci.isQualified = qualified;
502 ci.posttexts = posts;
504 ci.max_key_size = UINT_MAX;
505 ci.context = CiteItem::Export;
507 ci.richtext = for_xhtml;
508 label = biblist.getLabel(keys, buffer(), cite_type, ci);
513 docstring InsetCitation::basicLabel(bool for_xhtml) const
515 docstring keys = getParam("key");
520 // if there is no comma, then everything goes into key
521 // and keys will be empty.
522 keys = split(keys, key, ',');
525 label += wrapCitation(key, key, for_xhtml);
526 } while (!keys.empty());
528 docstring const & after = getParam("after");
530 label += ", " + after;
532 return '[' + label + ']';
536 bool InsetCitation::forceLTR(OutputParams const & rp) const
538 // We have to force LTR for numeric references
539 // [= bibliography, plain BibTeX, numeric natbib
540 // and biblatex]. Except for XeTeX/bidi. See #3005.
541 if (rp.useBidiPackage())
543 return (buffer().masterParams().citeEngine() == "basic"
544 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
547 docstring InsetCitation::screenLabel() const
549 return cache.screen_label;
553 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
555 if (!cache.recalculate && buffer().citeLabelsValid())
557 // The label may have changed, so we have to re-create it.
558 docstring const glabel = generateLabel();
559 cache.recalculate = false;
560 cache.generated_label = glabel;
561 unsigned int const maxLabelChars = 45;
562 cache.screen_label = glabel;
563 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
567 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
568 UpdateType, TocBackend & backend) const
571 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
572 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
573 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
574 // then we will also need to change that routine.
577 tocitem = _("BROKEN: ");
578 tocitem += getParam("key");
579 TocBuilder & b = backend.builder("citation");
580 b.pushItem(cpit, tocitem, output_active);
583 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
584 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
589 int InsetCitation::plaintext(odocstringstream & os,
590 OutputParams const &, size_t) const
592 string const & cmd = getCmdName();
596 docstring const label = generateLabel(false);
602 static docstring const cleanupWhitespace(docstring const & citelist)
604 docstring::const_iterator it = citelist.begin();
605 docstring::const_iterator end = citelist.end();
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 (; it != end; ++it) {
613 if (*it != ' ' || last != ',')
620 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
622 if (getCmdName() == "nocite")
625 // Split the different citations (on ","), so that one tag can be output for each of them.
626 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
627 docstring citations = getParam("key");
628 if (citations.find(',') == string::npos) {
629 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
632 while (pos != string::npos) {
633 pos = citations.find(',');
634 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
635 citations.erase(0, pos + 1);
637 if (pos != string::npos) {
645 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
647 if (getCmdName() == "nocite")
650 // have to output this raw, because generateLabel() will include tags
651 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
657 void InsetCitation::toString(odocstream & os) const
659 odocstringstream ods;
660 plaintext(ods, OutputParams(0));
665 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
671 // Have to overwrite the default InsetCommand method in order to check that
672 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
673 // citations and then changes his mind, turning natbib support off. The output
674 // should revert to the default citation command as provided by the citation
675 // engine, e.g. \cite[]{} for the basic engine.
676 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
678 // When this is a child compiled on its own, we use the children
679 // own bibinfo, else the master's
680 BiblioInfo const & bi = runparams.is_child
681 ? buffer().masterBibInfo() : buffer().bibInfo();
682 docstring const key = getParam("key");
683 // "keyonly" command: output the plain key and stop.
684 if (getCmdName() == "keyonly") {
685 // Special command to only return the key
686 if (!bi.isBibtex(getParam("key")))
687 // escape chars with bibitems
688 os << escape(cleanupWhitespace(key));
690 os << cleanupWhitespace(key);
693 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
694 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
695 getCmdName(), citation_styles);
697 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
699 // check if we have to do a qualified list
700 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
701 bool const qualified = cs.hasQualifiedList
702 && (!getParam("pretextlist").empty()
703 || !getParam("posttextlist").empty());
705 if (runparams.inulemcmd > 0)
708 os << "\\" << cite_str;
713 ParamInfo const & pinfo = findInfo(string());
714 docstring before = params().prepareCommand(runparams, getParam("before"),
715 pinfo["before"].handling());
716 docstring after = params().prepareCommand(runparams, getParam("after"),
717 pinfo["after"].handling());
718 if (!before.empty() && cs.textBefore) {
720 os << '(' << protectArgument(before, '(', ')')
721 << ")(" << protectArgument(after, '(', ')') << ')';
723 os << '[' << protectArgument(before) << "]["
724 << protectArgument(after) << ']';
725 } else if (!after.empty() && cs.textAfter) {
727 os << '(' << protectArgument(after, '(', ')') << ')';
729 os << '[' << protectArgument(after) << ']';
732 if (!bi.isBibtex(key))
733 // escape chars with bibitems
734 os << '{' << escape(cleanupWhitespace(key)) << '}';
737 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
738 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
739 for (docstring const & k : keys) {
741 QualifiedList::iterator it = pres.begin();
742 for (; it != pres.end() ; ++it) {
743 if ((*it).first == k) {
744 prenote = (*it).second;
749 docstring bef = params().prepareCommand(runparams, prenote,
750 pinfo["pretextlist"].handling());
752 QualifiedList::iterator pit = posts.begin();
753 for (; pit != posts.end() ; ++pit) {
754 if ((*pit).first == k) {
755 postnote = (*pit).second;
760 docstring aft = params().prepareCommand(runparams, postnote,
761 pinfo["posttextlist"].handling());
763 os << '[' << protectArgument(bef)
764 << "][" << protectArgument(aft) << ']';
765 else if (!aft.empty())
766 os << '[' << protectArgument(aft) << ']';
767 os << '{' << k << '}';
770 os << '{' << cleanupWhitespace(key) << '}';
773 if (runparams.inulemcmd)
778 string InsetCitation::contextMenuName() const
780 return "context-citation";