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 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
64 static ParamInfo param_info_;
66 // standard cite does only take one argument, but biblatex, jurabib
67 // and natbib extend this to two arguments, so
68 // we have to allow both here. InsetCitation takes care that
69 // LaTeX output is nevertheless correct.
70 if (param_info_.empty()) {
71 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
72 ParamInfo::HANDLING_LATEXIFY);
73 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
74 ParamInfo::HANDLING_LATEXIFY);
75 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
76 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
77 ParamInfo::HANDLING_LATEXIFY);
78 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
79 ParamInfo::HANDLING_LATEXIFY);
80 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
86 // We allow any command here, since we fall back to cite
87 // anyway if a command is not allowed by a style
88 bool InsetCitation::isCompatibleCommand(string const &)
94 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
95 vector<CitationStyle> const & valid_styles) const
97 CitationStyle cs = valid_styles[0];
98 cs.forceUpperCase = false;
99 cs.hasStarredVersion = false;
101 string normalized_input = input;
102 string::size_type const n = input.size() - 1;
103 if (isUpperCase(input[0]))
104 normalized_input[0] = lowercase(input[0]);
106 normalized_input = normalized_input.substr(0, n);
108 string const alias = bp.getCiteAlias(normalized_input);
110 normalized_input = alias;
112 vector<CitationStyle>::const_iterator it = valid_styles.begin();
113 vector<CitationStyle>::const_iterator end = valid_styles.end();
114 for (; it != end; ++it) {
115 CitationStyle this_cs = *it;
116 if (this_cs.name == normalized_input) {
126 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
128 switch (cmd.action()) {
129 case LFUN_INSET_MODIFY: {
130 buffer().removeBiblioTempFiles();
131 cache.recalculate = true;
132 if (cmd.getArg(0) == "toggleparam") {
133 string cmdname = getCmdName();
135 buffer().masterParams().getCiteAlias(cmdname);
138 string const par = cmd.getArg(1);
139 string newcmdname = cmdname;
141 if (suffixIs(cmdname, "*"))
142 newcmdname = rtrim(cmdname, "*");
144 newcmdname = cmdname + "*";
145 } else if (par == "casing") {
146 if (isUpperCase(cmdname[0]))
147 newcmdname[0] = lowercase(cmdname[0]);
149 newcmdname[0] = uppercase(newcmdname[0]);
151 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
156 InsetCommand::doDispatch(cur, cmd);
161 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
162 FuncStatus & status) const
164 switch (cmd.action()) {
165 // Handle the alias case
166 case LFUN_INSET_MODIFY:
167 if (cmd.getArg(0) == "changetype") {
168 string cmdname = getCmdName();
170 buffer().masterParams().getCiteAlias(cmdname);
173 if (suffixIs(cmdname, "*"))
174 cmdname = rtrim(cmdname, "*");
175 string const newtype = cmd.getArg(1);
176 status.setEnabled(isCompatibleCommand(newtype));
177 status.setOnOff(newtype == cmdname);
179 if (cmd.getArg(0) == "toggleparam") {
180 string cmdname = getCmdName();
182 buffer().masterParams().getCiteAlias(cmdname);
185 vector<CitationStyle> citation_styles =
186 buffer().masterParams().citeStyles();
187 CitationStyle cs = getCitationStyle(buffer().masterParams(),
188 cmdname, citation_styles);
189 if (cmd.getArg(1) == "star") {
190 status.setEnabled(cs.hasStarredVersion);
191 status.setOnOff(suffixIs(cmdname, "*"));
193 else if (cmd.getArg(1) == "casing") {
194 status.setEnabled(cs.forceUpperCase);
195 status.setOnOff(isUpperCase(cmdname[0]));
200 return InsetCommand::getStatus(cur, cmd, status);
205 bool InsetCitation::addKey(string const & key)
207 docstring const ukey = from_utf8(key);
208 docstring const & curkeys = getParam("key");
209 if (curkeys.empty()) {
210 setParam("key", ukey);
211 cache.recalculate = true;
215 vector<docstring> keys = getVectorFromString(curkeys);
216 vector<docstring>::const_iterator it = keys.begin();
217 vector<docstring>::const_iterator en = keys.end();
218 for (; it != en; ++it) {
220 LYXERR0("Key " << key << " already present.");
224 keys.push_back(ukey);
225 setParam("key", getStringFromVector(keys));
226 cache.recalculate = true;
231 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
233 Buffer const & buf = bv.buffer();
234 // Only after the buffer is loaded from file...
235 if (!buf.isFullyLoaded())
238 BiblioInfo const & bi = buf.masterBibInfo();
240 return _("No bibliography defined!");
242 docstring const & key = getParam("key");
244 return _("No citations selected!");
248 vector<docstring> keys = getVectorFromString(key);
249 if (keys.size() == 1)
250 return bi.getInfo(keys[0], buffer(), ci);
255 for (docstring const & kvar : keys) {
256 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
257 // limit to reasonable size.
258 if (count > 9 && keys.size() > 11) {
259 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
261 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
265 if (key_info.empty())
267 tip += "<li>" + key_info + "</li>";
277 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
278 vector<CitationStyle> const & valid_styles)
280 CitationStyle cs = valid_styles[0];
281 cs.forceUpperCase = false;
282 cs.hasStarredVersion = false;
284 string normalized_input = input;
285 string::size_type const n = input.size() - 1;
286 if (isUpperCase(input[0]))
287 normalized_input[0] = lowercase(input[0]);
289 normalized_input = normalized_input.substr(0, n);
291 string const alias = bp.getCiteAlias(normalized_input);
293 normalized_input = alias;
295 vector<CitationStyle>::const_iterator it = valid_styles.begin();
296 vector<CitationStyle>::const_iterator end = valid_styles.end();
297 for (; it != end; ++it) {
298 CitationStyle this_cs = *it;
299 if (this_cs.name == normalized_input) {
305 cs.forceUpperCase &= input[0] == uppercase(input[0]);
306 cs.hasStarredVersion &= input[n] == '*';
312 inline docstring wrapCitation(docstring const & key,
313 docstring const & content, bool for_xhtml)
317 // we have to do the escaping here, because we will ultimately
318 // write this as a raw string, so as not to escape the tags.
319 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
320 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
323 } // anonymous namespace
326 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
328 vector<docstring> ps =
329 getVectorFromString(p, from_ascii("\t"));
330 std::map<docstring, docstring> res;
331 for (docstring const & s: ps) {
333 docstring val = split(s, key, ' ');
339 docstring InsetCitation::generateLabel(bool for_xhtml) const
342 label = complexLabel(for_xhtml);
344 // Fallback to fail-safe
346 label = basicLabel(for_xhtml);
352 docstring InsetCitation::complexLabel(bool for_xhtml) const
354 Buffer const & buf = buffer();
355 // Only start the process off after the buffer is loaded from file.
356 if (!buf.isFullyLoaded())
359 BiblioInfo const & biblist = buf.masterBibInfo();
363 docstring const & key = getParam("key");
365 return _("No citations selected!");
367 string cite_type = getCmdName();
368 bool const uppercase = isUpperCase(cite_type[0]);
370 cite_type[0] = lowercase(cite_type[0]);
371 bool const starred = (cite_type[cite_type.size() - 1] == '*');
373 cite_type = cite_type.substr(0, cite_type.size() - 1);
376 string const alias = buf.masterParams().getCiteAlias(cite_type);
380 // FIXME: allow to add cite macros
382 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
383 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
386 // we only really want the last 'false', to suppress trimming, but
387 // we need to give the other defaults, too, to set it.
388 vector<docstring> keys =
389 getVectorFromString(key, from_ascii(","), false, false);
390 CitationStyle cs = getCitationStyle(buffer().masterParams(),
391 cite_type, buffer().masterParams().citeStyles());
392 bool const qualified = cs.hasQualifiedList
394 || !getParam("pretextlist").empty()
395 || !getParam("posttextlist").empty());
396 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
397 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
400 ci.textBefore = getParam("before");
401 ci.textAfter = getParam("after");
402 ci.forceUpperCase = uppercase;
403 ci.Starred = starred;
404 ci.max_size = UINT_MAX;
405 ci.isQualified = qualified;
407 ci.posttexts = posts;
409 ci.max_key_size = UINT_MAX;
410 ci.context = CiteItem::Export;
412 ci.richtext = for_xhtml;
413 label = biblist.getLabel(keys, buffer(), cite_type, ci);
418 docstring InsetCitation::basicLabel(bool for_xhtml) const
420 docstring keys = getParam("key");
425 // if there is no comma, then everything goes into key
426 // and keys will be empty.
427 keys = split(keys, key, ',');
430 label += wrapCitation(key, key, for_xhtml);
431 } while (!keys.empty());
433 docstring const & after = getParam("after");
435 label += ", " + after;
437 return '[' + label + ']';
440 docstring InsetCitation::screenLabel() const
442 return cache.screen_label;
446 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
448 if (!cache.recalculate && buffer().citeLabelsValid())
450 // The label may have changed, so we have to re-create it.
451 docstring const glabel = generateLabel();
452 cache.recalculate = false;
453 cache.generated_label = glabel;
454 unsigned int const maxLabelChars = 45;
455 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
456 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
460 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
461 UpdateType, TocBackend & backend) const
464 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
465 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
466 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
467 // then we will also need to change that routine.
468 docstring const tocitem = getParam("key");
469 TocBuilder & b = backend.builder("citation");
470 b.pushItem(cpit, tocitem, output_active);
475 int InsetCitation::plaintext(odocstringstream & os,
476 OutputParams const &, size_t) const
478 string const & cmd = getCmdName();
482 docstring const label = generateLabel(false);
488 static docstring const cleanupWhitespace(docstring const & citelist)
490 docstring::const_iterator it = citelist.begin();
491 docstring::const_iterator end = citelist.end();
492 // Paranoia check: make sure that there is no whitespace in here
493 // -- at least not behind commas or at the beginning
495 char_type last = ',';
496 for (; it != end; ++it) {
499 if (*it != ' ' || last != ',')
506 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
508 os << from_ascii("<citation>")
509 << cleanupWhitespace(getParam("key"))
510 << from_ascii("</citation>");
515 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
517 string const & cmd = getCmdName();
521 // have to output this raw, because generateLabel() will include tags
522 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
528 void InsetCitation::toString(odocstream & os) const
530 odocstringstream ods;
531 plaintext(ods, OutputParams(0));
536 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
542 // Have to overwrite the default InsetCommand method in order to check that
543 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
544 // citations and then changes his mind, turning natbib support off. The output
545 // should revert to the default citation command as provided by the citation
546 // engine, e.g. \cite[]{} for the basic engine.
547 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
549 BiblioInfo const & bi = buffer().masterBibInfo();
550 docstring const key = getParam("key");
551 // "keyonly" command: output the plain key and stop.
552 if (getCmdName() == "keyonly") {
553 // Special command to only return the key
554 if (!bi.isBibtex(getParam("key")))
555 // escape chars with bibitems
556 os << escape(cleanupWhitespace(key));
558 os << cleanupWhitespace(key);
561 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
562 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
563 getCmdName(), citation_styles);
565 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
567 // check if we have to do a qualified list
568 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
569 bool const qualified = cs.hasQualifiedList
570 && (!getParam("pretextlist").empty()
571 || !getParam("posttextlist").empty());
573 if (runparams.inulemcmd > 0)
576 os << "\\" << cite_str;
581 ParamInfo const & pinfo = findInfo(string());
582 docstring before = params().prepareCommand(runparams, getParam("before"),
583 pinfo["before"].handling());
584 docstring after = params().prepareCommand(runparams, getParam("after"),
585 pinfo["after"].handling());
586 if (!before.empty() && cs.textBefore) {
588 os << '(' << protectArgument(before, '(', ')')
589 << ")(" << protectArgument(after, '(', ')') << ')';
591 os << '[' << protectArgument(before) << "]["
592 << protectArgument(after) << ']';
593 } else if (!after.empty() && cs.textAfter) {
595 os << '(' << protectArgument(after, '(', ')') << ')';
597 os << '[' << protectArgument(after) << ']';
600 if (!bi.isBibtex(key))
601 // escape chars with bibitems
602 os << '{' << escape(cleanupWhitespace(key)) << '}';
605 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
606 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
607 for (docstring const & k: keys) {
608 docstring bef = params().prepareCommand(runparams, pres[k],
609 pinfo["pretextlist"].handling());
610 docstring aft = params().prepareCommand(runparams, posts[k],
611 pinfo["posttextlist"].handling());
613 os << '[' << protectArgument(bef)
614 << "][" << protectArgument(aft) << ']';
615 else if (!aft.empty())
616 os << '[' << protectArgument(aft) << ']';
617 os << '{' << k << '}';
620 os << '{' << cleanupWhitespace(key) << '}';
623 if (runparams.inulemcmd)
628 string InsetCitation::contextMenuName() const
630 return "context-citation";