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"
26 #include "output_xhtml.h"
27 #include "output_docbook.h"
28 #include "ParIterator.h"
29 #include "texstream.h"
30 #include "TocBackend.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/FileNameList.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
42 using namespace lyx::support;
46 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
47 : InsetCommand(buf, p)
49 buffer().removeBiblioTempFiles();
53 InsetCitation::~InsetCitation()
56 /* We do not use buffer() because Coverity believes that this
57 * may throw an exception. Actually this code path is not
58 * taken when buffer_ == 0 */
59 buffer_->removeBiblioTempFiles();
63 // May well be over-ridden when session settings are loaded
64 // in GuiCitation. Unfortunately, that will not happen until
65 // such a dialog is created.
66 bool InsetCitation::last_literal = true;
69 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
71 static ParamInfo param_info_;
73 // standard cite does only take one argument, but biblatex, jurabib
74 // and natbib extend this to two arguments, so
75 // we have to allow both here. InsetCitation takes care that
76 // LaTeX output is nevertheless correct.
77 if (param_info_.empty()) {
78 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
79 ParamInfo::HANDLING_LATEXIFY);
80 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
81 ParamInfo::HANDLING_LATEXIFY);
82 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
83 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
84 ParamInfo::HANDLING_LATEXIFY);
85 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
86 ParamInfo::HANDLING_LATEXIFY);
87 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
93 // We allow any command here, since we fall back to cite
94 // anyway if a command is not allowed by a style
95 bool InsetCitation::isCompatibleCommand(string const &)
101 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
102 vector<CitationStyle> const & valid_styles) const
104 CitationStyle cs = valid_styles[0];
105 cs.forceUpperCase = false;
106 cs.hasStarredVersion = false;
108 string normalized_input = input;
109 string::size_type const n = input.size() - 1;
110 if (isUpperCase(input[0]))
111 normalized_input[0] = lowercase(input[0]);
113 normalized_input = normalized_input.substr(0, n);
115 string const alias = bp.getCiteAlias(normalized_input);
117 normalized_input = alias;
119 vector<CitationStyle>::const_iterator it = valid_styles.begin();
120 vector<CitationStyle>::const_iterator end = valid_styles.end();
121 for (; it != end; ++it) {
122 CitationStyle this_cs = *it;
123 if (this_cs.name == normalized_input) {
133 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
135 switch (cmd.action()) {
136 case LFUN_INSET_MODIFY: {
137 buffer().removeBiblioTempFiles();
138 cache.recalculate = true;
139 if (cmd.getArg(0) == "toggleparam") {
140 string cmdname = getCmdName();
142 buffer().masterParams().getCiteAlias(cmdname);
145 string const par = cmd.getArg(1);
146 string newcmdname = cmdname;
148 if (suffixIs(cmdname, "*"))
149 newcmdname = rtrim(cmdname, "*");
151 newcmdname = cmdname + "*";
152 } else if (par == "casing") {
153 if (isUpperCase(cmdname[0]))
154 newcmdname[0] = lowercase(cmdname[0]);
156 newcmdname[0] = uppercase(newcmdname[0]);
158 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
163 InsetCommand::doDispatch(cur, cmd);
168 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
169 FuncStatus & status) const
171 switch (cmd.action()) {
172 // Handle the alias case
173 case LFUN_INSET_MODIFY:
174 if (cmd.getArg(0) == "changetype") {
175 string cmdname = getCmdName();
177 buffer().masterParams().getCiteAlias(cmdname);
180 if (suffixIs(cmdname, "*"))
181 cmdname = rtrim(cmdname, "*");
182 string const newtype = cmd.getArg(1);
183 status.setEnabled(isCompatibleCommand(newtype));
184 status.setOnOff(newtype == cmdname);
186 if (cmd.getArg(0) == "toggleparam") {
187 string cmdname = getCmdName();
189 buffer().masterParams().getCiteAlias(cmdname);
192 vector<CitationStyle> citation_styles =
193 buffer().masterParams().citeStyles();
194 CitationStyle cs = getCitationStyle(buffer().masterParams(),
195 cmdname, citation_styles);
196 if (cmd.getArg(1) == "star") {
197 status.setEnabled(cs.hasStarredVersion);
198 status.setOnOff(suffixIs(cmdname, "*"));
200 else if (cmd.getArg(1) == "casing") {
201 status.setEnabled(cs.forceUpperCase);
202 status.setOnOff(isUpperCase(cmdname[0]));
207 return InsetCommand::getStatus(cur, cmd, status);
212 bool InsetCitation::addKey(string const & key)
214 docstring const ukey = from_utf8(key);
215 docstring const & curkeys = getParam("key");
216 if (curkeys.empty()) {
217 setParam("key", ukey);
218 cache.recalculate = true;
222 vector<docstring> keys = getVectorFromString(curkeys);
223 vector<docstring>::const_iterator it = keys.begin();
224 vector<docstring>::const_iterator en = keys.end();
225 for (; it != en; ++it) {
227 LYXERR0("Key " << key << " already present.");
231 keys.push_back(ukey);
232 setParam("key", getStringFromVector(keys));
233 cache.recalculate = true;
238 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
240 Buffer const & buf = bv.buffer();
241 // Only after the buffer is loaded from file...
242 if (!buf.isFullyLoaded())
245 BiblioInfo const & bi = buf.masterBibInfo();
247 return _("No bibliography defined!");
249 docstring const & key = getParam("key");
251 return _("No citations selected!");
255 vector<docstring> keys = getVectorFromString(key);
256 if (keys.size() == 1)
257 return bi.getInfo(keys[0], buffer(), ci);
262 for (docstring const & kvar : keys) {
263 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
264 // limit to reasonable size.
265 if (count > 9 && keys.size() > 11) {
266 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
268 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
272 if (key_info.empty())
274 tip += "<li>" + key_info + "</li>";
284 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
285 vector<CitationStyle> const & valid_styles)
287 CitationStyle cs = valid_styles[0];
288 cs.forceUpperCase = false;
289 cs.hasStarredVersion = false;
291 string normalized_input = input;
292 string::size_type const n = input.size() - 1;
293 if (isUpperCase(input[0]))
294 normalized_input[0] = lowercase(input[0]);
296 normalized_input = normalized_input.substr(0, n);
298 string const alias = bp.getCiteAlias(normalized_input);
300 normalized_input = alias;
302 vector<CitationStyle>::const_iterator it = valid_styles.begin();
303 vector<CitationStyle>::const_iterator end = valid_styles.end();
304 for (; it != end; ++it) {
305 CitationStyle this_cs = *it;
306 if (this_cs.name == normalized_input) {
312 cs.forceUpperCase &= input[0] == uppercase(input[0]);
313 cs.hasStarredVersion &= input[n] == '*';
319 inline docstring wrapCitation(docstring const & key,
320 docstring const & content, bool for_xhtml)
324 // we have to do the escaping here, because we will ultimately
325 // write this as a raw string, so as not to escape the tags.
326 return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
327 xml::xmlize(content, XMLStream::ESCAPE_ALL) + "</a>";
330 } // anonymous namespace
333 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
335 vector<docstring> ps =
336 getVectorFromString(p, from_ascii("\t"));
338 for (docstring const & s: ps) {
341 if (contains(s, ' '))
342 val = split(s, key, ' ');
343 res.push_back(make_pair(key, val));
348 docstring InsetCitation::generateLabel(bool for_xhtml) const
351 label = complexLabel(for_xhtml);
353 // Fallback to fail-safe
355 label = basicLabel(for_xhtml);
361 docstring InsetCitation::complexLabel(bool for_xhtml) const
363 Buffer const & buf = buffer();
364 // Only start the process off after the buffer is loaded from file.
365 if (!buf.isFullyLoaded())
368 docstring const & key = getParam("key");
370 BiblioInfo const & biblist = buf.masterBibInfo();
372 // mark broken citations
375 if (biblist.empty()) {
381 return _("No citations selected!");
383 // check all citations
384 // we only really want the last 'false', to suppress trimming, but
385 // we need to give the other defaults, too, to set it.
386 vector<docstring> keys =
387 getVectorFromString(key, from_ascii(","), false, false);
388 for (auto const & k : keys) {
389 if (biblist.find(k) == biblist.end()) {
395 string cite_type = getCmdName();
396 bool const uppercase = isUpperCase(cite_type[0]);
398 cite_type[0] = lowercase(cite_type[0]);
399 bool const starred = (cite_type[cite_type.size() - 1] == '*');
401 cite_type = cite_type.substr(0, cite_type.size() - 1);
404 string const alias = buf.masterParams().getCiteAlias(cite_type);
408 // FIXME: allow to add cite macros
410 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
411 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
414 CitationStyle cs = getCitationStyle(buffer().masterParams(),
415 cite_type, buffer().masterParams().citeStyles());
416 bool const qualified = cs.hasQualifiedList
418 || !getParam("pretextlist").empty()
419 || !getParam("posttextlist").empty());
420 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
421 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
424 ci.textBefore = getParam("before");
425 ci.textAfter = getParam("after");
426 ci.forceUpperCase = uppercase;
427 ci.Starred = starred;
428 ci.max_size = UINT_MAX;
429 ci.isQualified = qualified;
431 ci.posttexts = posts;
433 ci.max_key_size = UINT_MAX;
434 ci.context = CiteItem::Export;
436 ci.richtext = for_xhtml;
437 label = biblist.getLabel(keys, buffer(), cite_type, ci);
442 docstring InsetCitation::basicLabel(bool for_xhtml) const
444 docstring keys = getParam("key");
449 // if there is no comma, then everything goes into key
450 // and keys will be empty.
451 keys = split(keys, key, ',');
454 label += wrapCitation(key, key, for_xhtml);
455 } while (!keys.empty());
457 docstring const & after = getParam("after");
459 label += ", " + after;
461 return '[' + label + ']';
465 bool InsetCitation::forceLTR(OutputParams const & rp) const
467 // We have to force LTR for numeric references
468 // [= bibliography, plain BibTeX, numeric natbib
469 // and biblatex]. Except for XeTeX/bidi. See #3005.
470 if (rp.useBidiPackage())
472 return (buffer().masterParams().citeEngine() == "basic"
473 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
476 docstring InsetCitation::screenLabel() const
478 return cache.screen_label;
482 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
484 if (!cache.recalculate && buffer().citeLabelsValid())
486 // The label may have changed, so we have to re-create it.
487 docstring const glabel = generateLabel();
488 cache.recalculate = false;
489 cache.generated_label = glabel;
490 unsigned int const maxLabelChars = 45;
491 cache.screen_label = glabel;
492 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
496 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
497 UpdateType, TocBackend & backend) const
500 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
501 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
502 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
503 // then we will also need to change that routine.
506 tocitem = _("BROKEN: ");
507 tocitem += getParam("key");
508 TocBuilder & b = backend.builder("citation");
509 b.pushItem(cpit, tocitem, output_active);
512 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
513 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
518 int InsetCitation::plaintext(odocstringstream & os,
519 OutputParams const &, size_t) const
521 string const & cmd = getCmdName();
525 docstring const label = generateLabel(false);
531 static docstring const cleanupWhitespace(docstring const & citelist)
533 docstring::const_iterator it = citelist.begin();
534 docstring::const_iterator end = citelist.end();
535 // Paranoia check: make sure that there is no whitespace in here
536 // -- at least not behind commas or at the beginning
538 char_type last = ',';
539 for (; it != end; ++it) {
542 if (*it != ' ' || last != ',')
549 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
551 if (getCmdName() == "nocite")
554 // Split the different citations (on ","), so that one tag can be output for each of them.
555 string citations = to_utf8(getParam("key")); // Citation strings are not supposed to be too fancy.
556 if (citations.find(',') == string::npos) {
557 xs << xml::CompTag("biblioref", "endterm=\"" + citations + "\"");
560 while (pos != string::npos) {
561 pos = citations.find(',');
562 xs << xml::CompTag("biblioref", "endterm=\"" + citations.substr(0, pos) + "\"");
563 citations.erase(0, pos + 1);
565 if (pos != string::npos) {
573 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
575 if (getCmdName() == "nocite")
578 // have to output this raw, because generateLabel() will include tags
579 xs << XMLStream::ESCAPE_NONE << generateLabel(true);
585 void InsetCitation::toString(odocstream & os) const
587 odocstringstream ods;
588 plaintext(ods, OutputParams(0));
593 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
599 // Have to overwrite the default InsetCommand method in order to check that
600 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
601 // citations and then changes his mind, turning natbib support off. The output
602 // should revert to the default citation command as provided by the citation
603 // engine, e.g. \cite[]{} for the basic engine.
604 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
606 // When this is a child compiled on its own, we use the children
607 // own bibinfo, else the master's
608 BiblioInfo const & bi = runparams.is_child
609 ? buffer().masterBibInfo() : buffer().bibInfo();
610 docstring const key = getParam("key");
611 // "keyonly" command: output the plain key and stop.
612 if (getCmdName() == "keyonly") {
613 // Special command to only return the key
614 if (!bi.isBibtex(getParam("key")))
615 // escape chars with bibitems
616 os << escape(cleanupWhitespace(key));
618 os << cleanupWhitespace(key);
621 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
622 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
623 getCmdName(), citation_styles);
625 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
627 // check if we have to do a qualified list
628 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
629 bool const qualified = cs.hasQualifiedList
630 && (!getParam("pretextlist").empty()
631 || !getParam("posttextlist").empty());
633 if (runparams.inulemcmd > 0)
636 os << "\\" << cite_str;
641 ParamInfo const & pinfo = findInfo(string());
642 docstring before = params().prepareCommand(runparams, getParam("before"),
643 pinfo["before"].handling());
644 docstring after = params().prepareCommand(runparams, getParam("after"),
645 pinfo["after"].handling());
646 if (!before.empty() && cs.textBefore) {
648 os << '(' << protectArgument(before, '(', ')')
649 << ")(" << protectArgument(after, '(', ')') << ')';
651 os << '[' << protectArgument(before) << "]["
652 << protectArgument(after) << ']';
653 } else if (!after.empty() && cs.textAfter) {
655 os << '(' << protectArgument(after, '(', ')') << ')';
657 os << '[' << protectArgument(after) << ']';
660 if (!bi.isBibtex(key))
661 // escape chars with bibitems
662 os << '{' << escape(cleanupWhitespace(key)) << '}';
665 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
666 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
667 for (docstring const & k : keys) {
669 QualifiedList::iterator it = pres.begin();
670 for (; it != pres.end() ; ++it) {
671 if ((*it).first == k) {
672 prenote = (*it).second;
677 docstring bef = params().prepareCommand(runparams, prenote,
678 pinfo["pretextlist"].handling());
680 QualifiedList::iterator pit = posts.begin();
681 for (; pit != posts.end() ; ++pit) {
682 if ((*pit).first == k) {
683 postnote = (*pit).second;
688 docstring aft = params().prepareCommand(runparams, postnote,
689 pinfo["posttextlist"].handling());
691 os << '[' << protectArgument(bef)
692 << "][" << protectArgument(aft) << ']';
693 else if (!aft.empty())
694 os << '[' << protectArgument(aft) << ']';
695 os << '{' << k << '}';
698 os << '{' << cleanupWhitespace(key) << '}';
701 if (runparams.inulemcmd)
706 string InsetCitation::contextMenuName() const
708 return "context-citation";