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 available?
197 if (!lyxrc.citation_search_view.empty())
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 year, author, doi, url, file;
210 for (docstring const & kvar : keys) {
211 year = bi.getYear(kvar, buffer(), false);
212 author = bi.getAuthorOrEditorList(kvar, buffer());
213 bi.getLocators(kvar, doi, url, file);
214 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
215 << url << " file:" << file << " author:" << author << " year:" << year);
219 } else if (!doi.empty()) {
221 } else if (!url.empty()) {
224 locator = "EXTERNAL " + year + " " + author;
226 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
232 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
233 FuncStatus & status) const
235 switch (cmd.action()) {
236 // Handle the alias case
237 case LFUN_INSET_MODIFY:
238 if (cmd.getArg(0) == "changetype") {
239 string cmdname = getCmdName();
241 buffer().masterParams().getCiteAlias(cmdname);
244 if (suffixIs(cmdname, "*"))
245 cmdname = rtrim(cmdname, "*");
246 string const newtype = cmd.getArg(1);
247 status.setEnabled(isCompatibleCommand(newtype));
248 status.setOnOff(newtype == cmdname);
250 if (cmd.getArg(0) == "toggleparam") {
251 string cmdname = getCmdName();
253 buffer().masterParams().getCiteAlias(cmdname);
256 vector<CitationStyle> citation_styles =
257 buffer().masterParams().citeStyles();
258 CitationStyle cs = getCitationStyle(buffer().masterParams(),
259 cmdname, citation_styles);
260 if (cmd.getArg(1) == "star") {
261 status.setEnabled(cs.hasStarredVersion);
262 status.setOnOff(suffixIs(cmdname, "*"));
264 else if (cmd.getArg(1) == "casing") {
265 status.setEnabled(cs.forceUpperCase);
266 status.setOnOff(isUpperCase(cmdname[0]));
270 case LFUN_INSET_EDIT:
271 return openCitationPossible();
273 return InsetCommand::getStatus(cur, cmd, status);
278 bool InsetCitation::addKey(string const & key)
280 docstring const ukey = from_utf8(key);
281 docstring const & curkeys = getParam("key");
282 if (curkeys.empty()) {
283 setParam("key", ukey);
284 cache.recalculate = true;
288 vector<docstring> keys = getVectorFromString(curkeys);
289 vector<docstring>::const_iterator it = keys.begin();
290 vector<docstring>::const_iterator en = keys.end();
291 for (; it != en; ++it) {
293 LYXERR0("Key " << key << " already present.");
297 keys.push_back(ukey);
298 setParam("key", getStringFromVector(keys));
299 cache.recalculate = true;
304 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
306 Buffer const & buf = bv.buffer();
307 // Only after the buffer is loaded from file...
308 if (!buf.isFullyLoaded())
311 BiblioInfo const & bi = buf.masterBibInfo();
313 return _("No bibliography defined!");
315 docstring const & key = getParam("key");
317 return _("No citations selected!");
321 vector<docstring> keys = getVectorFromString(key);
322 if (keys.size() == 1)
323 return bi.getInfo(keys[0], buffer(), ci);
328 for (docstring const & kvar : keys) {
329 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
330 // limit to reasonable size.
331 if (count > 9 && keys.size() > 11) {
332 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
334 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
338 if (key_info.empty())
340 tip += "<li>" + key_info + "</li>";
350 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
351 vector<CitationStyle> const & valid_styles)
353 CitationStyle cs = valid_styles[0];
354 cs.forceUpperCase = false;
355 cs.hasStarredVersion = false;
357 string normalized_input = input;
358 string::size_type const n = input.size() - 1;
359 if (isUpperCase(input[0]))
360 normalized_input[0] = lowercase(input[0]);
362 normalized_input = normalized_input.substr(0, n);
364 string const alias = bp.getCiteAlias(normalized_input);
366 normalized_input = alias;
368 vector<CitationStyle>::const_iterator it = valid_styles.begin();
369 vector<CitationStyle>::const_iterator end = valid_styles.end();
370 for (; it != end; ++it) {
371 CitationStyle this_cs = *it;
372 if (this_cs.name == normalized_input) {
378 cs.forceUpperCase &= input[0] == uppercase(input[0]);
379 cs.hasStarredVersion &= input[n] == '*';
385 inline docstring wrapCitation(docstring const & key,
386 docstring const & content, bool for_xhtml)
390 // we have to do the escaping here, because we will ultimately
391 // write this as a raw string, so as not to escape the tags.
392 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
393 xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
396 } // anonymous namespace
399 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
401 vector<docstring> ps =
402 getVectorFromString(p, from_ascii("\t"));
404 for (docstring const & s: ps) {
407 if (contains(s, ' '))
408 val = split(s, key, ' ');
409 res.push_back(make_pair(key, val));
414 docstring InsetCitation::generateLabel(bool for_xhtml) const
417 label = complexLabel(for_xhtml);
419 // Fallback to fail-safe
421 label = basicLabel(for_xhtml);
427 docstring InsetCitation::complexLabel(bool for_xhtml) const
429 Buffer const & buf = buffer();
430 // Only start the process off after the buffer is loaded from file.
431 if (!buf.isFullyLoaded())
434 docstring const & key = getParam("key");
436 BiblioInfo const & biblist = buf.masterBibInfo();
438 // mark broken citations
441 if (biblist.empty()) {
447 return _("No citations selected!");
449 // check all citations
450 // we only really want the last 'false', to suppress trimming, but
451 // we need to give the other defaults, too, to set it.
452 vector<docstring> keys =
453 getVectorFromString(key, from_ascii(","), false, false);
454 for (auto const & k : keys) {
455 if (biblist.find(k) == biblist.end()) {
461 string cite_type = getCmdName();
462 bool const uppercase = isUpperCase(cite_type[0]);
464 cite_type[0] = lowercase(cite_type[0]);
465 bool const starred = (cite_type[cite_type.size() - 1] == '*');
467 cite_type = cite_type.substr(0, cite_type.size() - 1);
470 string const alias = buf.masterParams().getCiteAlias(cite_type);
474 // FIXME: allow to add cite macros
476 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
477 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
480 CitationStyle cs = getCitationStyle(buffer().masterParams(),
481 cite_type, buffer().masterParams().citeStyles());
482 bool const qualified = cs.hasQualifiedList
484 || !getParam("pretextlist").empty()
485 || !getParam("posttextlist").empty());
486 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
487 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
490 ci.textBefore = getParam("before");
491 ci.textAfter = getParam("after");
492 ci.forceUpperCase = uppercase;
493 ci.Starred = starred;
494 ci.max_size = UINT_MAX;
495 ci.isQualified = qualified;
497 ci.posttexts = posts;
499 ci.max_key_size = UINT_MAX;
500 ci.context = CiteItem::Export;
502 ci.richtext = for_xhtml;
503 label = biblist.getLabel(keys, buffer(), cite_type, ci);
508 docstring InsetCitation::basicLabel(bool for_xhtml) const
510 docstring keys = getParam("key");
515 // if there is no comma, then everything goes into key
516 // and keys will be empty.
517 keys = split(keys, key, ',');
520 label += wrapCitation(key, key, for_xhtml);
521 } while (!keys.empty());
523 docstring const & after = getParam("after");
525 label += ", " + after;
527 return '[' + label + ']';
531 bool InsetCitation::forceLTR(OutputParams const & rp) const
533 // We have to force LTR for numeric references
534 // [= bibliography, plain BibTeX, numeric natbib
535 // and biblatex]. Except for XeTeX/bidi. See #3005.
536 if (rp.useBidiPackage())
538 return (buffer().masterParams().citeEngine() == "basic"
539 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
542 docstring InsetCitation::screenLabel() const
544 return cache.screen_label;
548 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
550 if (!cache.recalculate && buffer().citeLabelsValid())
552 // The label may have changed, so we have to re-create it.
553 docstring const glabel = generateLabel();
554 cache.recalculate = false;
555 cache.generated_label = glabel;
556 unsigned int const maxLabelChars = 45;
557 cache.screen_label = glabel;
558 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
562 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
563 UpdateType, TocBackend & backend) const
566 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
567 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
568 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
569 // then we will also need to change that routine.
572 tocitem = _("BROKEN: ");
573 tocitem += getParam("key");
574 TocBuilder & b = backend.builder("citation");
575 b.pushItem(cpit, tocitem, output_active);
578 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
579 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
584 int InsetCitation::plaintext(odocstringstream & os,
585 OutputParams const &, size_t) const
587 string const & cmd = getCmdName();
591 docstring const label = generateLabel(false);
597 static docstring const cleanupWhitespace(docstring const & citelist)
599 docstring::const_iterator it = citelist.begin();
600 docstring::const_iterator end = citelist.end();
601 // Paranoia check: make sure that there is no whitespace in here
602 // -- at least not behind commas or at the beginning
604 char_type last = ',';
605 for (; it != end; ++it) {
608 if (*it != ' ' || last != ',')
615 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
617 if (getCmdName() == "nocite")
620 // Split the different citations (on ","), so that one tag can be output for each of them.
621 // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
622 docstring citations = getParam("key");
623 if (citations.find(',') == string::npos) {
624 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
627 while (pos != string::npos) {
628 pos = citations.find(',');
629 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
630 citations.erase(0, pos + 1);
632 if (pos != string::npos) {
640 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
642 if (getCmdName() == "nocite")
645 // have to output this raw, because generateLabel() will include tags
646 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
652 void InsetCitation::toString(odocstream & os) const
654 odocstringstream ods;
655 plaintext(ods, OutputParams(0));
660 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
666 // Have to overwrite the default InsetCommand method in order to check that
667 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
668 // citations and then changes his mind, turning natbib support off. The output
669 // should revert to the default citation command as provided by the citation
670 // engine, e.g. \cite[]{} for the basic engine.
671 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
673 // When this is a child compiled on its own, we use the children
674 // own bibinfo, else the master's
675 BiblioInfo const & bi = runparams.is_child
676 ? buffer().masterBibInfo() : buffer().bibInfo();
677 docstring const key = getParam("key");
678 // "keyonly" command: output the plain key and stop.
679 if (getCmdName() == "keyonly") {
680 // Special command to only return the key
681 if (!bi.isBibtex(getParam("key")))
682 // escape chars with bibitems
683 os << escape(cleanupWhitespace(key));
685 os << cleanupWhitespace(key);
688 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
689 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
690 getCmdName(), citation_styles);
692 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
694 // check if we have to do a qualified list
695 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
696 bool const qualified = cs.hasQualifiedList
697 && (!getParam("pretextlist").empty()
698 || !getParam("posttextlist").empty());
700 if (runparams.inulemcmd > 0)
703 os << "\\" << cite_str;
708 ParamInfo const & pinfo = findInfo(string());
709 docstring before = params().prepareCommand(runparams, getParam("before"),
710 pinfo["before"].handling());
711 docstring after = params().prepareCommand(runparams, getParam("after"),
712 pinfo["after"].handling());
713 if (!before.empty() && cs.textBefore) {
715 os << '(' << protectArgument(before, '(', ')')
716 << ")(" << protectArgument(after, '(', ')') << ')';
718 os << '[' << protectArgument(before) << "]["
719 << protectArgument(after) << ']';
720 } else if (!after.empty() && cs.textAfter) {
722 os << '(' << protectArgument(after, '(', ')') << ')';
724 os << '[' << protectArgument(after) << ']';
727 if (!bi.isBibtex(key))
728 // escape chars with bibitems
729 os << '{' << escape(cleanupWhitespace(key)) << '}';
732 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
733 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
734 for (docstring const & k : keys) {
736 QualifiedList::iterator it = pres.begin();
737 for (; it != pres.end() ; ++it) {
738 if ((*it).first == k) {
739 prenote = (*it).second;
744 docstring bef = params().prepareCommand(runparams, prenote,
745 pinfo["pretextlist"].handling());
747 QualifiedList::iterator pit = posts.begin();
748 for (; pit != posts.end() ; ++pit) {
749 if ((*pit).first == k) {
750 postnote = (*pit).second;
755 docstring aft = params().prepareCommand(runparams, postnote,
756 pinfo["posttextlist"].handling());
758 os << '[' << protectArgument(bef)
759 << "][" << protectArgument(aft) << ']';
760 else if (!aft.empty())
761 os << '[' << protectArgument(aft) << ']';
762 os << '{' << k << '}';
765 os << '{' << cleanupWhitespace(key) << '}';
768 if (runparams.inulemcmd)
773 string InsetCitation::contextMenuName() const
775 return "context-citation";