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 ParamInfo InsetCitation::param_info_;
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 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
67 // standard cite does only take one argument, but biblatex, jurabib
68 // and natbib extend this to two arguments, so
69 // we have to allow both here. InsetCitation takes care that
70 // LaTeX output is nevertheless correct.
71 if (param_info_.empty()) {
72 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
73 ParamInfo::HANDLING_LATEXIFY);
74 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
75 ParamInfo::HANDLING_LATEXIFY);
76 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
77 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
78 ParamInfo::HANDLING_LATEXIFY);
79 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
80 ParamInfo::HANDLING_LATEXIFY);
81 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
87 // We allow any command here, since we fall back to cite
88 // anyway if a command is not allowed by a style
89 bool InsetCitation::isCompatibleCommand(string const &)
95 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
96 vector<CitationStyle> const & valid_styles) const
98 CitationStyle cs = valid_styles[0];
99 cs.forceUpperCase = false;
100 cs.hasStarredVersion = false;
102 string normalized_input = input;
103 string::size_type const n = input.size() - 1;
104 if (isUpperCase(input[0]))
105 normalized_input[0] = lowercase(input[0]);
107 normalized_input = normalized_input.substr(0, n);
109 string const alias = bp.getCiteAlias(normalized_input);
111 normalized_input = alias;
113 vector<CitationStyle>::const_iterator it = valid_styles.begin();
114 vector<CitationStyle>::const_iterator end = valid_styles.end();
115 for (; it != end; ++it) {
116 CitationStyle this_cs = *it;
117 if (this_cs.name == normalized_input) {
127 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
129 switch (cmd.action()) {
130 case LFUN_INSET_MODIFY: {
131 buffer().removeBiblioTempFiles();
132 cache.recalculate = true;
133 if (cmd.getArg(0) == "toggleparam") {
134 string cmdname = getCmdName();
136 buffer().masterParams().getCiteAlias(cmdname);
139 string const par = cmd.getArg(1);
140 string newcmdname = cmdname;
142 if (suffixIs(cmdname, "*"))
143 newcmdname = rtrim(cmdname, "*");
145 newcmdname = cmdname + "*";
146 } else if (par == "casing") {
147 if (isUpperCase(cmdname[0]))
148 newcmdname[0] = lowercase(cmdname[0]);
150 newcmdname[0] = uppercase(newcmdname[0]);
152 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
157 InsetCommand::doDispatch(cur, cmd);
162 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
163 FuncStatus & status) const
165 switch (cmd.action()) {
166 // Handle the alias case
167 case LFUN_INSET_MODIFY:
168 if (cmd.getArg(0) == "changetype") {
169 string cmdname = getCmdName();
171 buffer().masterParams().getCiteAlias(cmdname);
174 if (suffixIs(cmdname, "*"))
175 cmdname = rtrim(cmdname, "*");
176 string const newtype = cmd.getArg(1);
177 status.setEnabled(isCompatibleCommand(newtype));
178 status.setOnOff(newtype == cmdname);
180 if (cmd.getArg(0) == "toggleparam") {
181 string cmdname = getCmdName();
183 buffer().masterParams().getCiteAlias(cmdname);
186 vector<CitationStyle> citation_styles =
187 buffer().masterParams().citeStyles();
188 CitationStyle cs = getCitationStyle(buffer().masterParams(),
189 cmdname, citation_styles);
190 if (cmd.getArg(1) == "star") {
191 status.setEnabled(cs.hasStarredVersion);
192 status.setOnOff(suffixIs(cmdname, "*"));
194 else if (cmd.getArg(1) == "casing") {
195 status.setEnabled(cs.forceUpperCase);
196 status.setOnOff(isUpperCase(cmdname[0]));
201 return InsetCommand::getStatus(cur, cmd, status);
206 bool InsetCitation::addKey(string const & key)
208 docstring const ukey = from_utf8(key);
209 docstring const & curkeys = getParam("key");
210 if (curkeys.empty()) {
211 setParam("key", ukey);
212 cache.recalculate = true;
216 vector<docstring> keys = getVectorFromString(curkeys);
217 vector<docstring>::const_iterator it = keys.begin();
218 vector<docstring>::const_iterator en = keys.end();
219 for (; it != en; ++it) {
221 LYXERR0("Key " << key << " already present.");
225 keys.push_back(ukey);
226 setParam("key", getStringFromVector(keys));
227 cache.recalculate = true;
232 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
234 Buffer const & buf = bv.buffer();
235 // Only after the buffer is loaded from file...
236 if (!buf.isFullyLoaded())
239 BiblioInfo const & bi = buf.masterBibInfo();
241 return _("No bibliography defined!");
243 docstring const & key = getParam("key");
245 return _("No citations selected!");
249 vector<docstring> keys = getVectorFromString(key);
250 if (keys.size() == 1)
251 return bi.getInfo(keys[0], buffer(), ci);
256 for (docstring const & key : keys) {
257 docstring const key_info = bi.getInfo(key, buffer(), ci);
258 // limit to reasonable size.
259 if (count > 9 && keys.size() > 11) {
260 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
262 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
266 if (key_info.empty())
268 tip += "<li>" + key_info + "</li>";
278 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
279 vector<CitationStyle> const & valid_styles)
281 CitationStyle cs = valid_styles[0];
282 cs.forceUpperCase = false;
283 cs.hasStarredVersion = false;
285 string normalized_input = input;
286 string::size_type const n = input.size() - 1;
287 if (isUpperCase(input[0]))
288 normalized_input[0] = lowercase(input[0]);
290 normalized_input = normalized_input.substr(0, n);
292 string const alias = bp.getCiteAlias(normalized_input);
294 normalized_input = alias;
296 vector<CitationStyle>::const_iterator it = valid_styles.begin();
297 vector<CitationStyle>::const_iterator end = valid_styles.end();
298 for (; it != end; ++it) {
299 CitationStyle this_cs = *it;
300 if (this_cs.name == normalized_input) {
306 cs.forceUpperCase &= input[0] == uppercase(input[0]);
307 cs.hasStarredVersion &= input[n] == '*';
313 inline docstring wrapCitation(docstring const & key,
314 docstring const & content, bool for_xhtml)
318 // we have to do the escaping here, because we will ultimately
319 // write this as a raw string, so as not to escape the tags.
320 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
321 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
324 } // anonymous namespace
327 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
329 vector<docstring> ps =
330 getVectorFromString(p, from_ascii("\t"));
331 std::map<docstring, docstring> res;
332 for (docstring const & s: ps) {
334 docstring val = split(s, key, ' ');
340 docstring InsetCitation::generateLabel(bool for_xhtml) const
343 label = complexLabel(for_xhtml);
345 // Fallback to fail-safe
347 label = basicLabel(for_xhtml);
353 docstring InsetCitation::complexLabel(bool for_xhtml) const
355 Buffer const & buf = buffer();
356 // Only start the process off after the buffer is loaded from file.
357 if (!buf.isFullyLoaded())
360 BiblioInfo const & biblist = buf.masterBibInfo();
364 docstring const & key = getParam("key");
366 return _("No citations selected!");
368 string cite_type = getCmdName();
369 bool const uppercase = isUpperCase(cite_type[0]);
371 cite_type[0] = lowercase(cite_type[0]);
372 bool const starred = (cite_type[cite_type.size() - 1] == '*');
374 cite_type = cite_type.substr(0, cite_type.size() - 1);
377 string const alias = buf.masterParams().getCiteAlias(cite_type);
381 // FIXME: allow to add cite macros
383 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
384 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
387 // we only really want the last 'false', to suppress trimming, but
388 // we need to give the other defaults, too, to set it.
389 vector<docstring> keys =
390 getVectorFromString(key, from_ascii(","), false, false);
391 CitationStyle cs = getCitationStyle(buffer().masterParams(),
392 cite_type, buffer().masterParams().citeStyles());
393 bool const qualified = cs.hasQualifiedList
395 || !getParam("pretextlist").empty()
396 || !getParam("posttextlist").empty());
397 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
398 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
401 ci.textBefore = getParam("before");
402 ci.textAfter = getParam("after");
403 ci.forceUpperCase = uppercase;
404 ci.Starred = starred;
405 ci.max_size = UINT_MAX;
406 ci.isQualified = qualified;
408 ci.posttexts = posts;
410 ci.max_key_size = UINT_MAX;
411 ci.context = CiteItem::Export;
413 ci.richtext = for_xhtml;
414 label = biblist.getLabel(keys, buffer(), cite_type, ci);
419 docstring InsetCitation::basicLabel(bool for_xhtml) const
421 docstring keys = getParam("key");
426 // if there is no comma, then everything goes into key
427 // and keys will be empty.
428 keys = trim(split(keys, key, ','));
432 label += wrapCitation(key, key, for_xhtml);
433 } while (!keys.empty());
435 docstring const & after = getParam("after");
437 label += ", " + after;
439 return '[' + label + ']';
442 docstring InsetCitation::screenLabel() const
444 return cache.screen_label;
448 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
450 if (!cache.recalculate && buffer().citeLabelsValid())
452 // The label may have changed, so we have to re-create it.
453 docstring const glabel = generateLabel();
454 cache.recalculate = false;
455 cache.generated_label = glabel;
456 unsigned int const maxLabelChars = 45;
457 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
458 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
462 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
463 UpdateType, TocBackend & backend) const
466 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
467 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
468 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
469 // then we will also need to change that routine.
470 docstring const tocitem = getParam("key");
471 TocBuilder & b = backend.builder("citation");
472 b.pushItem(cpit, tocitem, output_active);
477 int InsetCitation::plaintext(odocstringstream & os,
478 OutputParams const &, size_t) const
480 string const & cmd = getCmdName();
484 docstring const label = generateLabel(false);
490 static docstring const cleanupWhitespace(docstring const & citelist)
492 docstring::const_iterator it = citelist.begin();
493 docstring::const_iterator end = citelist.end();
494 // Paranoia check: make sure that there is no whitespace in here
495 // -- at least not behind commas or at the beginning
497 char_type last = ',';
498 for (; it != end; ++it) {
501 if (*it != ' ' || last != ',')
508 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
510 os << from_ascii("<citation>")
511 << cleanupWhitespace(getParam("key"))
512 << from_ascii("</citation>");
517 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
519 string const & cmd = getCmdName();
523 // have to output this raw, because generateLabel() will include tags
524 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
530 void InsetCitation::toString(odocstream & os) const
532 odocstringstream ods;
533 plaintext(ods, OutputParams(0));
538 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
544 // Have to overwrite the default InsetCommand method in order to check that
545 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
546 // citations and then changes his mind, turning natbib support off. The output
547 // should revert to the default citation command as provided by the citation
548 // engine, e.g. \cite[]{} for the basic engine.
549 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
551 BiblioInfo const & bi = buffer().masterBibInfo();
552 docstring const key = getParam("key");
553 // "keyonly" command: output the plain key and stop.
554 if (getCmdName() == "keyonly") {
555 // Special command to only return the key
556 if (!bi.isBibtex(getParam("key")))
557 // escape chars with bibitems
558 os << escape(cleanupWhitespace(key));
560 os << cleanupWhitespace(key);
563 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
564 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
565 getCmdName(), citation_styles);
567 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
569 // check if we have to do a qualified list
570 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
571 bool const qualified = cs.hasQualifiedList
572 && (!getParam("pretextlist").empty()
573 || !getParam("posttextlist").empty());
575 if (runparams.inulemcmd > 0)
578 os << "\\" << cite_str;
583 docstring before = params().prepareCommand(runparams, getParam("before"),
584 param_info_["before"].handling());
585 docstring after = params().prepareCommand(runparams, getParam("after"),
586 param_info_["after"].handling());
587 if (!before.empty() && cs.textBefore) {
589 os << '(' << protectArgument(before, '(', ')')
590 << ")(" << protectArgument(after, '(', ')') << ')';
592 os << '[' << protectArgument(before) << "]["
593 << protectArgument(after) << ']';
594 } else if (!after.empty() && cs.textAfter) {
596 os << '(' << protectArgument(after, '(', ')') << ')';
598 os << '[' << protectArgument(after) << ']';
601 if (!bi.isBibtex(key))
602 // escape chars with bibitems
603 os << '{' << escape(cleanupWhitespace(key)) << '}';
606 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
607 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
608 for (docstring const & k: keys) {
609 docstring bef = params().prepareCommand(runparams, pres[k],
610 param_info_["pretextlist"].handling());
611 docstring aft = params().prepareCommand(runparams, posts[k],
612 param_info_["posttextlist"].handling());
614 os << '[' << protectArgument(bef)
615 << "][" << protectArgument(aft) << ']';
616 else if (!aft.empty())
617 os << '[' << protectArgument(aft) << ']';
618 os << '{' << k << '}';
621 os << '{' << cleanupWhitespace(key) << '}';
624 if (runparams.inulemcmd)
629 string InsetCitation::contextMenuName() const
631 return "context-citation";