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 buffer().removeBiblioTempFiles();
62 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
64 // standard cite does only take one argument, but biblatex, jurabib
65 // and natbib extend this to two arguments, so
66 // we have to allow both here. InsetCitation takes care that
67 // LaTeX output is nevertheless correct.
68 if (param_info_.empty()) {
69 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
70 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
71 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
72 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL);
73 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL);
79 // We allow any command here, since we fall back to cite
80 // anyway if a command is not allowed by a style
81 bool InsetCitation::isCompatibleCommand(string const &)
87 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
88 vector<CitationStyle> const & valid_styles) const
90 CitationStyle cs = valid_styles[0];
91 cs.forceUpperCase = false;
92 cs.hasStarredVersion = false;
94 string normalized_input = input;
95 string::size_type const n = input.size() - 1;
96 if (isUpperCase(input[0]))
97 normalized_input[0] = lowercase(input[0]);
99 normalized_input = normalized_input.substr(0, n);
101 string const alias = bp.getCiteAlias(normalized_input);
103 normalized_input = alias;
105 vector<CitationStyle>::const_iterator it = valid_styles.begin();
106 vector<CitationStyle>::const_iterator end = valid_styles.end();
107 for (; it != end; ++it) {
108 CitationStyle this_cs = *it;
109 if (this_cs.name == normalized_input) {
119 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
121 switch (cmd.action()) {
122 case LFUN_INSET_MODIFY: {
123 buffer().removeBiblioTempFiles();
124 cache.recalculate = true;
125 if (cmd.getArg(0) == "toggleparam") {
126 string cmdname = getCmdName();
128 buffer().masterParams().getCiteAlias(cmdname);
131 string const par = cmd.getArg(1);
132 string newcmdname = cmdname;
134 if (suffixIs(cmdname, "*"))
135 newcmdname = rtrim(cmdname, "*");
137 newcmdname = cmdname + "*";
138 } else if (par == "casing") {
139 if (isUpperCase(cmdname[0]))
140 newcmdname[0] = lowercase(cmdname[0]);
142 newcmdname[0] = uppercase(newcmdname[0]);
144 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
148 InsetCommand::doDispatch(cur, cmd);
153 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
154 FuncStatus & status) const
156 switch (cmd.action()) {
157 // Handle the alias case
158 case LFUN_INSET_MODIFY:
159 if (cmd.getArg(0) == "changetype") {
160 string cmdname = getCmdName();
162 buffer().masterParams().getCiteAlias(cmdname);
165 if (suffixIs(cmdname, "*"))
166 cmdname = rtrim(cmdname, "*");
167 string const newtype = cmd.getArg(1);
168 status.setEnabled(isCompatibleCommand(newtype));
169 status.setOnOff(newtype == cmdname);
171 if (cmd.getArg(0) == "toggleparam") {
172 string cmdname = getCmdName();
174 buffer().masterParams().getCiteAlias(cmdname);
177 vector<CitationStyle> citation_styles =
178 buffer().masterParams().citeStyles();
179 CitationStyle cs = getCitationStyle(buffer().masterParams(),
180 cmdname, citation_styles);
181 if (cmd.getArg(1) == "star") {
182 status.setEnabled(cs.hasStarredVersion);
183 status.setOnOff(suffixIs(cmdname, "*"));
185 else if (cmd.getArg(1) == "casing") {
186 status.setEnabled(cs.forceUpperCase);
187 status.setOnOff(isUpperCase(cmdname[0]));
192 return InsetCommand::getStatus(cur, cmd, status);
197 bool InsetCitation::addKey(string const & key)
199 docstring const ukey = from_utf8(key);
200 docstring const & curkeys = getParam("key");
201 if (curkeys.empty()) {
202 setParam("key", ukey);
203 cache.recalculate = true;
207 vector<docstring> keys = getVectorFromString(curkeys);
208 vector<docstring>::const_iterator it = keys.begin();
209 vector<docstring>::const_iterator en = keys.end();
210 for (; it != en; ++it) {
212 LYXERR0("Key " << key << " already present.");
216 keys.push_back(ukey);
217 setParam("key", getStringFromVector(keys));
218 cache.recalculate = true;
223 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
225 Buffer const & buf = bv.buffer();
226 // Only after the buffer is loaded from file...
227 if (!buf.isFullyLoaded())
230 BiblioInfo const & bi = buf.masterBibInfo();
232 return _("No bibliography defined!");
234 docstring const & key = getParam("key");
236 return _("No citations selected!");
240 vector<docstring> keys = getVectorFromString(key);
241 if (keys.size() == 1)
242 return bi.getInfo(keys[0], buffer(), ci);
247 for (docstring const & key : keys) {
248 docstring const key_info = bi.getInfo(key, buffer(), ci);
249 // limit to reasonable size.
250 if (count > 9 && keys.size() > 11) {
251 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
253 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
257 if (key_info.empty())
259 tip += "<li>" + key_info + "</li>";
269 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
270 vector<CitationStyle> const & valid_styles)
272 CitationStyle cs = valid_styles[0];
273 cs.forceUpperCase = false;
274 cs.hasStarredVersion = false;
276 string normalized_input = input;
277 string::size_type const n = input.size() - 1;
278 if (isUpperCase(input[0]))
279 normalized_input[0] = lowercase(input[0]);
281 normalized_input = normalized_input.substr(0, n);
283 string const alias = bp.getCiteAlias(normalized_input);
285 normalized_input = alias;
287 vector<CitationStyle>::const_iterator it = valid_styles.begin();
288 vector<CitationStyle>::const_iterator end = valid_styles.end();
289 for (; it != end; ++it) {
290 CitationStyle this_cs = *it;
291 if (this_cs.name == normalized_input) {
297 cs.forceUpperCase &= input[0] == uppercase(input[0]);
298 cs.hasStarredVersion &= input[n] == '*';
304 inline docstring wrapCitation(docstring const & key,
305 docstring const & content, bool for_xhtml)
309 // we have to do the escaping here, because we will ultimately
310 // write this as a raw string, so as not to escape the tags.
311 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
312 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
315 docstring protectArgument(docstring & arg, char const l = '[',
318 if (contains(arg, l) || contains(arg, r))
320 arg = '{' + arg + '}';
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 vector<docstring> keys = getVectorFromString(key);
388 CitationStyle cs = getCitationStyle(buffer().masterParams(),
389 cite_type, buffer().masterParams().citeStyles());
390 bool const qualified = cs.hasQualifiedList
392 || !getParam("pretextlist").empty()
393 || !getParam("posttextlist").empty());
394 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
395 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
398 ci.textBefore = getParam("before");
399 ci.textAfter = getParam("after");
400 ci.forceUpperCase = uppercase;
401 ci.Starred = starred;
402 ci.max_size = UINT_MAX;
403 ci.isQualified = qualified;
405 ci.posttexts = posts;
407 ci.max_key_size = UINT_MAX;
408 ci.context = CiteItem::Export;
410 ci.richtext = for_xhtml;
411 label = biblist.getLabel(keys, buffer(), cite_type, ci);
416 docstring InsetCitation::basicLabel(bool for_xhtml) const
418 docstring keys = getParam("key");
423 // if there is no comma, then everything goes into key
424 // and keys will be empty.
425 keys = trim(split(keys, key, ','));
429 label += wrapCitation(key, key, for_xhtml);
430 } while (!keys.empty());
432 docstring const & after = getParam("after");
434 label += ", " + after;
436 return '[' + label + ']';
439 docstring InsetCitation::screenLabel() const
441 return cache.screen_label;
445 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
447 if (!cache.recalculate && buffer().citeLabelsValid())
449 // The label may have changed, so we have to re-create it.
450 docstring const glabel = generateLabel();
451 cache.recalculate = false;
452 cache.generated_label = glabel;
453 unsigned int const maxLabelChars = 45;
454 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
455 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
459 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
460 UpdateType, TocBackend & backend) const
463 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
464 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
465 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
466 // then we will also need to change that routine.
467 docstring const tocitem = getParam("key");
468 TocBuilder & b = backend.builder("citation");
469 b.pushItem(cpit, tocitem, output_active);
474 int InsetCitation::plaintext(odocstringstream & os,
475 OutputParams const &, size_t) const
477 string const & cmd = getCmdName();
481 docstring const label = generateLabel(false);
487 static docstring const cleanupWhitespace(docstring const & citelist)
489 docstring::const_iterator it = citelist.begin();
490 docstring::const_iterator end = citelist.end();
491 // Paranoia check: make sure that there is no whitespace in here
492 // -- at least not behind commas or at the beginning
494 char_type last = ',';
495 for (; it != end; ++it) {
498 if (*it != ' ' || last != ',')
505 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
507 os << from_ascii("<citation>")
508 << cleanupWhitespace(getParam("key"))
509 << from_ascii("</citation>");
514 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
516 string const & cmd = getCmdName();
520 // have to output this raw, because generateLabel() will include tags
521 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
527 void InsetCitation::toString(odocstream & os) const
529 odocstringstream ods;
530 plaintext(ods, OutputParams(0));
535 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
541 // Have to overwrite the default InsetCommand method in order to check that
542 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
543 // citations and then changes his mind, turning natbib support off. The output
544 // should revert to the default citation command as provided by the citation
545 // engine, e.g. \cite[]{} for the basic engine.
546 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
548 BiblioInfo const & bi = buffer().masterBibInfo();
549 docstring const key = getParam("key");
550 // "keyonly" command: output the plain key and stop.
551 if (getCmdName() == "keyonly") {
552 // Special command to only return the key
553 if (!bi.isBibtex(getParam("key")))
554 // escape chars with bibitems
555 os << escape(cleanupWhitespace(key));
557 os << cleanupWhitespace(key);
560 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
561 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
562 getCmdName(), citation_styles);
564 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
566 // check if we have to do a qualified list
567 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
568 bool const qualified = cs.hasQualifiedList
569 && (!getParam("pretextlist").empty()
570 || !getParam("posttextlist").empty());
572 if (runparams.inulemcmd > 0)
575 os << "\\" << cite_str;
580 docstring before = getParam("before");
581 docstring after = getParam("after");
582 if (!before.empty() && cs.textBefore) {
584 os << '(' << protectArgument(before, '(', ')')
585 << ")(" << protectArgument(after, '(', ')') << ')';
587 os << '[' << protectArgument(before) << "]["
588 << protectArgument(after) << ']';
589 } else if (!after.empty() && cs.textAfter) {
591 os << '(' << protectArgument(after, '(', ')') << ')';
593 os << '[' << protectArgument(after) << ']';
596 if (!bi.isBibtex(key))
597 // escape chars with bibitems
598 os << '{' << escape(cleanupWhitespace(key)) << '}';
601 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
602 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
603 for (docstring const & k: keys) {
604 docstring bef = pres[k];
605 docstring aft = posts[k];
607 os << '[' << protectArgument(bef)
608 << "][" << protectArgument(aft) << ']';
609 else if (!aft.empty())
610 os << '[' << protectArgument(aft) << ']';
611 os << '{' << k << '}';
614 os << '{' << cleanupWhitespace(key) << '}';
617 if (runparams.inulemcmd)
622 string InsetCitation::contextMenuName() const
624 return "context-citation";