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 "ParIterator.h"
28 #include "texstream.h"
29 #include "TocBackend.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/FileNameList.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
41 using namespace lyx::support;
45 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
46 : InsetCommand(buf, p)
48 buffer().removeBiblioTempFiles();
52 InsetCitation::~InsetCitation()
55 /* We do not use buffer() because Coverity believes that this
56 * may throw an exception. Actually this code path is not
57 * taken when buffer_ == 0 */
58 buffer_->removeBiblioTempFiles();
62 // May well be over-ridden when session settings are loaded
63 // in GuiCitation. Unfortunately, that will not happen until
64 // such a dialog is created.
65 bool InsetCitation::last_literal = true;
68 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
70 static ParamInfo param_info_;
72 // standard cite does only take one argument, but biblatex, jurabib
73 // and natbib extend this to two arguments, so
74 // we have to allow both here. InsetCitation takes care that
75 // LaTeX output is nevertheless correct.
76 if (param_info_.empty()) {
77 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
78 ParamInfo::HANDLING_LATEXIFY);
79 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
80 ParamInfo::HANDLING_LATEXIFY);
81 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
82 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
83 ParamInfo::HANDLING_LATEXIFY);
84 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
85 ParamInfo::HANDLING_LATEXIFY);
86 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
92 // We allow any command here, since we fall back to cite
93 // anyway if a command is not allowed by a style
94 bool InsetCitation::isCompatibleCommand(string const &)
100 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
101 vector<CitationStyle> const & valid_styles) const
103 CitationStyle cs = valid_styles[0];
104 cs.forceUpperCase = false;
105 cs.hasStarredVersion = false;
107 string normalized_input = input;
108 string::size_type const n = input.size() - 1;
109 if (isUpperCase(input[0]))
110 normalized_input[0] = lowercase(input[0]);
112 normalized_input = normalized_input.substr(0, n);
114 string const alias = bp.getCiteAlias(normalized_input);
116 normalized_input = alias;
118 vector<CitationStyle>::const_iterator it = valid_styles.begin();
119 vector<CitationStyle>::const_iterator end = valid_styles.end();
120 for (; it != end; ++it) {
121 CitationStyle this_cs = *it;
122 if (this_cs.name == normalized_input) {
132 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
134 switch (cmd.action()) {
135 case LFUN_INSET_MODIFY: {
136 buffer().removeBiblioTempFiles();
137 cache.recalculate = true;
138 if (cmd.getArg(0) == "toggleparam") {
139 string cmdname = getCmdName();
141 buffer().masterParams().getCiteAlias(cmdname);
144 string const par = cmd.getArg(1);
145 string newcmdname = cmdname;
147 if (suffixIs(cmdname, "*"))
148 newcmdname = rtrim(cmdname, "*");
150 newcmdname = cmdname + "*";
151 } else if (par == "casing") {
152 if (isUpperCase(cmdname[0]))
153 newcmdname[0] = lowercase(cmdname[0]);
155 newcmdname[0] = uppercase(newcmdname[0]);
157 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
162 InsetCommand::doDispatch(cur, cmd);
167 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
168 FuncStatus & status) const
170 switch (cmd.action()) {
171 // Handle the alias case
172 case LFUN_INSET_MODIFY:
173 if (cmd.getArg(0) == "changetype") {
174 string cmdname = getCmdName();
176 buffer().masterParams().getCiteAlias(cmdname);
179 if (suffixIs(cmdname, "*"))
180 cmdname = rtrim(cmdname, "*");
181 string const newtype = cmd.getArg(1);
182 status.setEnabled(isCompatibleCommand(newtype));
183 status.setOnOff(newtype == cmdname);
185 if (cmd.getArg(0) == "toggleparam") {
186 string cmdname = getCmdName();
188 buffer().masterParams().getCiteAlias(cmdname);
191 vector<CitationStyle> citation_styles =
192 buffer().masterParams().citeStyles();
193 CitationStyle cs = getCitationStyle(buffer().masterParams(),
194 cmdname, citation_styles);
195 if (cmd.getArg(1) == "star") {
196 status.setEnabled(cs.hasStarredVersion);
197 status.setOnOff(suffixIs(cmdname, "*"));
199 else if (cmd.getArg(1) == "casing") {
200 status.setEnabled(cs.forceUpperCase);
201 status.setOnOff(isUpperCase(cmdname[0]));
206 return InsetCommand::getStatus(cur, cmd, status);
211 bool InsetCitation::addKey(string const & key)
213 docstring const ukey = from_utf8(key);
214 docstring const & curkeys = getParam("key");
215 if (curkeys.empty()) {
216 setParam("key", ukey);
217 cache.recalculate = true;
221 vector<docstring> keys = getVectorFromString(curkeys);
222 vector<docstring>::const_iterator it = keys.begin();
223 vector<docstring>::const_iterator en = keys.end();
224 for (; it != en; ++it) {
226 LYXERR0("Key " << key << " already present.");
230 keys.push_back(ukey);
231 setParam("key", getStringFromVector(keys));
232 cache.recalculate = true;
237 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
239 Buffer const & buf = bv.buffer();
240 // Only after the buffer is loaded from file...
241 if (!buf.isFullyLoaded())
244 BiblioInfo const & bi = buf.masterBibInfo();
246 return _("No bibliography defined!");
248 docstring const & key = getParam("key");
250 return _("No citations selected!");
254 vector<docstring> keys = getVectorFromString(key);
255 if (keys.size() == 1)
256 return bi.getInfo(keys[0], buffer(), ci);
261 for (docstring const & kvar : keys) {
262 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
263 // limit to reasonable size.
264 if (count > 9 && keys.size() > 11) {
265 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
267 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
271 if (key_info.empty())
273 tip += "<li>" + key_info + "</li>";
283 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
284 vector<CitationStyle> const & valid_styles)
286 CitationStyle cs = valid_styles[0];
287 cs.forceUpperCase = false;
288 cs.hasStarredVersion = false;
290 string normalized_input = input;
291 string::size_type const n = input.size() - 1;
292 if (isUpperCase(input[0]))
293 normalized_input[0] = lowercase(input[0]);
295 normalized_input = normalized_input.substr(0, n);
297 string const alias = bp.getCiteAlias(normalized_input);
299 normalized_input = alias;
301 vector<CitationStyle>::const_iterator it = valid_styles.begin();
302 vector<CitationStyle>::const_iterator end = valid_styles.end();
303 for (; it != end; ++it) {
304 CitationStyle this_cs = *it;
305 if (this_cs.name == normalized_input) {
311 cs.forceUpperCase &= input[0] == uppercase(input[0]);
312 cs.hasStarredVersion &= input[n] == '*';
318 inline docstring wrapCitation(docstring const & key,
319 docstring const & content, bool for_xhtml)
323 // we have to do the escaping here, because we will ultimately
324 // write this as a raw string, so as not to escape the tags.
325 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
326 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
329 } // anonymous namespace
332 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
334 vector<docstring> ps =
335 getVectorFromString(p, from_ascii("\t"));
337 for (docstring const & s: ps) {
340 if (contains(s, ' '))
341 val = split(s, key, ' ');
342 res.push_back(make_pair(key, val));
347 docstring InsetCitation::generateLabel(bool for_xhtml) const
350 label = complexLabel(for_xhtml);
352 // Fallback to fail-safe
354 label = basicLabel(for_xhtml);
360 docstring InsetCitation::complexLabel(bool for_xhtml) const
362 Buffer const & buf = buffer();
363 // Only start the process off after the buffer is loaded from file.
364 if (!buf.isFullyLoaded())
367 docstring const & key = getParam("key");
369 BiblioInfo const & biblist = buf.masterBibInfo();
371 // mark broken citations
374 if (biblist.empty()) {
380 return _("No citations selected!");
382 // check all citations
383 // we only really want the last 'false', to suppress trimming, but
384 // we need to give the other defaults, too, to set it.
385 vector<docstring> keys =
386 getVectorFromString(key, from_ascii(","), false, false);
387 for (auto const & k : keys) {
388 if (biblist.find(k) == biblist.end()) {
394 string cite_type = getCmdName();
395 bool const uppercase = isUpperCase(cite_type[0]);
397 cite_type[0] = lowercase(cite_type[0]);
398 bool const starred = (cite_type[cite_type.size() - 1] == '*');
400 cite_type = cite_type.substr(0, cite_type.size() - 1);
403 string const alias = buf.masterParams().getCiteAlias(cite_type);
407 // FIXME: allow to add cite macros
409 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
410 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
413 CitationStyle cs = getCitationStyle(buffer().masterParams(),
414 cite_type, buffer().masterParams().citeStyles());
415 bool const qualified = cs.hasQualifiedList
417 || !getParam("pretextlist").empty()
418 || !getParam("posttextlist").empty());
419 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
420 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
423 ci.textBefore = getParam("before");
424 ci.textAfter = getParam("after");
425 ci.forceUpperCase = uppercase;
426 ci.Starred = starred;
427 ci.max_size = UINT_MAX;
428 ci.isQualified = qualified;
430 ci.posttexts = posts;
432 ci.max_key_size = UINT_MAX;
433 ci.context = CiteItem::Export;
435 ci.richtext = for_xhtml;
436 label = biblist.getLabel(keys, buffer(), cite_type, ci);
441 docstring InsetCitation::basicLabel(bool for_xhtml) const
443 docstring keys = getParam("key");
448 // if there is no comma, then everything goes into key
449 // and keys will be empty.
450 keys = split(keys, key, ',');
453 label += wrapCitation(key, key, for_xhtml);
454 } while (!keys.empty());
456 docstring const & after = getParam("after");
458 label += ", " + after;
460 return '[' + label + ']';
464 bool InsetCitation::forceLTR(OutputParams const & rp) const
466 // We have to force LTR for numeric references
467 // [= bibliography, plain BibTeX, numeric natbib
468 // and biblatex]. Except for XeTeX/bidi. See #3005.
469 if (rp.useBidiPackage())
471 return (buffer().masterParams().citeEngine() == "basic"
472 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
475 docstring InsetCitation::screenLabel() const
477 return cache.screen_label;
481 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
483 if (!cache.recalculate && buffer().citeLabelsValid())
485 // The label may have changed, so we have to re-create it.
486 docstring const glabel = generateLabel();
487 cache.recalculate = false;
488 cache.generated_label = glabel;
489 unsigned int const maxLabelChars = 45;
490 cache.screen_label = glabel;
491 support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
495 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
496 UpdateType, TocBackend & backend) const
499 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
500 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
501 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
502 // then we will also need to change that routine.
505 tocitem = _("BROKEN: ");
506 tocitem += getParam("key");
507 TocBuilder & b = backend.builder("citation");
508 b.pushItem(cpit, tocitem, output_active);
511 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
512 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
517 int InsetCitation::plaintext(odocstringstream & os,
518 OutputParams const &, size_t) const
520 string const & cmd = getCmdName();
524 docstring const label = generateLabel(false);
530 static docstring const cleanupWhitespace(docstring const & citelist)
532 docstring::const_iterator it = citelist.begin();
533 docstring::const_iterator end = citelist.end();
534 // Paranoia check: make sure that there is no whitespace in here
535 // -- at least not behind commas or at the beginning
537 char_type last = ',';
538 for (; it != end; ++it) {
541 if (*it != ' ' || last != ',')
548 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
550 os << from_ascii("<citation>")
551 << cleanupWhitespace(getParam("key"))
552 << from_ascii("</citation>");
557 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
559 string const & cmd = getCmdName();
563 // have to output this raw, because generateLabel() will include tags
564 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
570 void InsetCitation::toString(odocstream & os) const
572 odocstringstream ods;
573 plaintext(ods, OutputParams(0));
578 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
584 // Have to overwrite the default InsetCommand method in order to check that
585 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
586 // citations and then changes his mind, turning natbib support off. The output
587 // should revert to the default citation command as provided by the citation
588 // engine, e.g. \cite[]{} for the basic engine.
589 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
591 // When this is a child compiled on its own, we use the childs
592 // own bibinfo, else the master's
593 BiblioInfo const & bi = runparams.is_child
594 ? buffer().masterBibInfo() : buffer().bibInfo();
595 docstring const key = getParam("key");
596 // "keyonly" command: output the plain key and stop.
597 if (getCmdName() == "keyonly") {
598 // Special command to only return the key
599 if (!bi.isBibtex(getParam("key")))
600 // escape chars with bibitems
601 os << escape(cleanupWhitespace(key));
603 os << cleanupWhitespace(key);
606 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
607 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
608 getCmdName(), citation_styles);
610 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
612 // check if we have to do a qualified list
613 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
614 bool const qualified = cs.hasQualifiedList
615 && (!getParam("pretextlist").empty()
616 || !getParam("posttextlist").empty());
618 if (runparams.inulemcmd > 0)
621 os << "\\" << cite_str;
626 ParamInfo const & pinfo = findInfo(string());
627 docstring before = params().prepareCommand(runparams, getParam("before"),
628 pinfo["before"].handling());
629 docstring after = params().prepareCommand(runparams, getParam("after"),
630 pinfo["after"].handling());
631 if (!before.empty() && cs.textBefore) {
633 os << '(' << protectArgument(before, '(', ')')
634 << ")(" << protectArgument(after, '(', ')') << ')';
636 os << '[' << protectArgument(before) << "]["
637 << protectArgument(after) << ']';
638 } else if (!after.empty() && cs.textAfter) {
640 os << '(' << protectArgument(after, '(', ')') << ')';
642 os << '[' << protectArgument(after) << ']';
645 if (!bi.isBibtex(key))
646 // escape chars with bibitems
647 os << '{' << escape(cleanupWhitespace(key)) << '}';
650 QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
651 QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
652 for (docstring const & k : keys) {
654 QualifiedList::iterator it = pres.begin();
655 for (; it != pres.end() ; ++it) {
656 if ((*it).first == k) {
657 prenote = (*it).second;
662 docstring bef = params().prepareCommand(runparams, prenote,
663 pinfo["pretextlist"].handling());
665 QualifiedList::iterator pit = posts.begin();
666 for (; pit != posts.end() ; ++pit) {
667 if ((*pit).first == k) {
668 postnote = (*pit).second;
673 docstring aft = params().prepareCommand(runparams, postnote,
674 pinfo["posttextlist"].handling());
676 os << '[' << protectArgument(bef)
677 << "][" << protectArgument(aft) << ']';
678 else if (!aft.empty())
679 os << '[' << protectArgument(aft) << ']';
680 os << '{' << k << '}';
683 os << '{' << cleanupWhitespace(key) << '}';
686 if (runparams.inulemcmd)
691 string InsetCitation::contextMenuName() const
693 return "context-citation";