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"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.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 & key : keys) {
263 docstring const key_info = bi.getInfo(key, 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-" + html::cleanAttr(key) + "'>" +
327 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
330 } // anonymous namespace
333 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
335 vector<docstring> ps =
336 getVectorFromString(p, from_ascii("\t"));
337 std::map<docstring, docstring> res;
338 for (docstring const & s: ps) {
340 docstring val = split(s, key, ' ');
346 docstring InsetCitation::generateLabel(bool for_xhtml) const
349 label = complexLabel(for_xhtml);
351 // Fallback to fail-safe
353 label = basicLabel(for_xhtml);
359 docstring InsetCitation::complexLabel(bool for_xhtml) const
361 Buffer const & buf = buffer();
362 // Only start the process off after the buffer is loaded from file.
363 if (!buf.isFullyLoaded())
366 BiblioInfo const & biblist = buf.masterBibInfo();
370 docstring const & key = getParam("key");
372 return _("No citations selected!");
374 string cite_type = getCmdName();
375 bool const uppercase = isUpperCase(cite_type[0]);
377 cite_type[0] = lowercase(cite_type[0]);
378 bool const starred = (cite_type[cite_type.size() - 1] == '*');
380 cite_type = cite_type.substr(0, cite_type.size() - 1);
383 string const alias = buf.masterParams().getCiteAlias(cite_type);
387 // FIXME: allow to add cite macros
389 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
390 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
393 // we only really want the last 'false', to suppress trimming, but
394 // we need to give the other defaults, too, to set it.
395 vector<docstring> keys =
396 getVectorFromString(key, from_ascii(","), false, false);
397 CitationStyle cs = getCitationStyle(buffer().masterParams(),
398 cite_type, buffer().masterParams().citeStyles());
399 bool const qualified = cs.hasQualifiedList
401 || !getParam("pretextlist").empty()
402 || !getParam("posttextlist").empty());
403 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
404 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
407 ci.textBefore = getParam("before");
408 ci.textAfter = getParam("after");
409 ci.forceUpperCase = uppercase;
410 ci.Starred = starred;
411 ci.max_size = UINT_MAX;
412 ci.isQualified = qualified;
414 ci.posttexts = posts;
416 ci.max_key_size = UINT_MAX;
417 ci.context = CiteItem::Export;
419 ci.richtext = for_xhtml;
420 label = biblist.getLabel(keys, buffer(), cite_type, ci);
425 docstring InsetCitation::basicLabel(bool for_xhtml) const
427 docstring keys = getParam("key");
432 // if there is no comma, then everything goes into key
433 // and keys will be empty.
434 keys = split(keys, key, ',');
437 label += wrapCitation(key, key, for_xhtml);
438 } while (!keys.empty());
440 docstring const & after = getParam("after");
442 label += ", " + after;
444 return '[' + label + ']';
448 bool InsetCitation::forceLTR(OutputParams const & rp) const
450 // We have to force LTR for numeric references
451 // [= plain BibTeX, numeric natbib and biblatex].
452 // Except for XeTeX/bidi . See #3005.
453 if (rp.local_font->isRightToLeft()
454 && rp.use_polyglossia
455 && rp.flavor == OutputParams::XETEX)
457 return (buffer().masterParams().citeEngine().list().front() == "basic"
458 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
461 docstring InsetCitation::screenLabel() const
463 return cache.screen_label;
467 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
469 if (!cache.recalculate && buffer().citeLabelsValid())
471 // The label may have changed, so we have to re-create it.
472 docstring const glabel = generateLabel();
473 cache.recalculate = false;
474 cache.generated_label = glabel;
475 unsigned int const maxLabelChars = 45;
476 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
477 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
481 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
482 UpdateType, TocBackend & backend) const
485 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
486 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
487 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
488 // then we will also need to change that routine.
489 docstring const tocitem = getParam("key");
490 TocBuilder & b = backend.builder("citation");
491 b.pushItem(cpit, tocitem, output_active);
496 int InsetCitation::plaintext(odocstringstream & os,
497 OutputParams const &, size_t) const
499 string const & cmd = getCmdName();
503 docstring const label = generateLabel(false);
509 static docstring const cleanupWhitespace(docstring const & citelist)
511 docstring::const_iterator it = citelist.begin();
512 docstring::const_iterator end = citelist.end();
513 // Paranoia check: make sure that there is no whitespace in here
514 // -- at least not behind commas or at the beginning
516 char_type last = ',';
517 for (; it != end; ++it) {
520 if (*it != ' ' || last != ',')
527 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
529 os << from_ascii("<citation>")
530 << cleanupWhitespace(getParam("key"))
531 << from_ascii("</citation>");
536 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
538 string const & cmd = getCmdName();
542 // have to output this raw, because generateLabel() will include tags
543 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
549 void InsetCitation::toString(odocstream & os) const
551 odocstringstream ods;
552 plaintext(ods, OutputParams(0));
557 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
563 // Have to overwrite the default InsetCommand method in order to check that
564 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
565 // citations and then changes his mind, turning natbib support off. The output
566 // should revert to the default citation command as provided by the citation
567 // engine, e.g. \cite[]{} for the basic engine.
568 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
570 // When this is a child compiled on its own, we use the childs
571 // own bibinfo, else the master's
572 BiblioInfo const & bi = runparams.is_child
573 ? buffer().masterBibInfo() : buffer().bibInfo();
574 docstring const key = getParam("key");
575 // "keyonly" command: output the plain key and stop.
576 if (getCmdName() == "keyonly") {
577 // Special command to only return the key
578 if (!bi.isBibtex(getParam("key")))
579 // escape chars with bibitems
580 os << escape(cleanupWhitespace(key));
582 os << cleanupWhitespace(key);
585 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
586 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
587 getCmdName(), citation_styles);
589 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
591 // check if we have to do a qualified list
592 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
593 bool const qualified = cs.hasQualifiedList
594 && (!getParam("pretextlist").empty()
595 || !getParam("posttextlist").empty());
597 if (runparams.inulemcmd > 0)
600 os << "\\" << cite_str;
605 ParamInfo const & pinfo = findInfo(string());
606 docstring before = params().prepareCommand(runparams, getParam("before"),
607 pinfo["before"].handling());
608 docstring after = params().prepareCommand(runparams, getParam("after"),
609 pinfo["after"].handling());
610 if (!before.empty() && cs.textBefore) {
612 os << '(' << protectArgument(before, '(', ')')
613 << ")(" << protectArgument(after, '(', ')') << ')';
615 os << '[' << protectArgument(before) << "]["
616 << protectArgument(after) << ']';
617 } else if (!after.empty() && cs.textAfter) {
619 os << '(' << protectArgument(after, '(', ')') << ')';
621 os << '[' << protectArgument(after) << ']';
624 if (!bi.isBibtex(key))
625 // escape chars with bibitems
626 os << '{' << escape(cleanupWhitespace(key)) << '}';
629 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
630 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
631 for (docstring const & k: keys) {
632 docstring bef = params().prepareCommand(runparams, pres[k],
633 pinfo["pretextlist"].handling());
634 docstring aft = params().prepareCommand(runparams, posts[k],
635 pinfo["posttextlist"].handling());
637 os << '[' << protectArgument(bef)
638 << "][" << protectArgument(aft) << ']';
639 else if (!aft.empty())
640 os << '[' << protectArgument(aft) << ']';
641 os << '{' << k << '}';
644 os << '{' << cleanupWhitespace(key) << '}';
647 if (runparams.inulemcmd)
652 string InsetCitation::contextMenuName() const
654 return "context-citation";