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 ParamInfo::HANDLING_LATEXIFY);
71 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
72 ParamInfo::HANDLING_LATEXIFY);
73 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
74 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
75 ParamInfo::HANDLING_LATEXIFY);
76 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
77 ParamInfo::HANDLING_LATEXIFY);
78 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
84 // We allow any command here, since we fall back to cite
85 // anyway if a command is not allowed by a style
86 bool InsetCitation::isCompatibleCommand(string const &)
92 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
93 vector<CitationStyle> const & valid_styles) const
95 CitationStyle cs = valid_styles[0];
96 cs.forceUpperCase = false;
97 cs.hasStarredVersion = false;
99 string normalized_input = input;
100 string::size_type const n = input.size() - 1;
101 if (isUpperCase(input[0]))
102 normalized_input[0] = lowercase(input[0]);
104 normalized_input = normalized_input.substr(0, n);
106 string const alias = bp.getCiteAlias(normalized_input);
108 normalized_input = alias;
110 vector<CitationStyle>::const_iterator it = valid_styles.begin();
111 vector<CitationStyle>::const_iterator end = valid_styles.end();
112 for (; it != end; ++it) {
113 CitationStyle this_cs = *it;
114 if (this_cs.name == normalized_input) {
124 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
126 switch (cmd.action()) {
127 case LFUN_INSET_MODIFY: {
128 buffer().removeBiblioTempFiles();
129 cache.recalculate = true;
130 if (cmd.getArg(0) == "toggleparam") {
131 string cmdname = getCmdName();
133 buffer().masterParams().getCiteAlias(cmdname);
136 string const par = cmd.getArg(1);
137 string newcmdname = cmdname;
139 if (suffixIs(cmdname, "*"))
140 newcmdname = rtrim(cmdname, "*");
142 newcmdname = cmdname + "*";
143 } else if (par == "casing") {
144 if (isUpperCase(cmdname[0]))
145 newcmdname[0] = lowercase(cmdname[0]);
147 newcmdname[0] = uppercase(newcmdname[0]);
149 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
153 InsetCommand::doDispatch(cur, cmd);
158 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
159 FuncStatus & status) const
161 switch (cmd.action()) {
162 // Handle the alias case
163 case LFUN_INSET_MODIFY:
164 if (cmd.getArg(0) == "changetype") {
165 string cmdname = getCmdName();
167 buffer().masterParams().getCiteAlias(cmdname);
170 if (suffixIs(cmdname, "*"))
171 cmdname = rtrim(cmdname, "*");
172 string const newtype = cmd.getArg(1);
173 status.setEnabled(isCompatibleCommand(newtype));
174 status.setOnOff(newtype == cmdname);
176 if (cmd.getArg(0) == "toggleparam") {
177 string cmdname = getCmdName();
179 buffer().masterParams().getCiteAlias(cmdname);
182 vector<CitationStyle> citation_styles =
183 buffer().masterParams().citeStyles();
184 CitationStyle cs = getCitationStyle(buffer().masterParams(),
185 cmdname, citation_styles);
186 if (cmd.getArg(1) == "star") {
187 status.setEnabled(cs.hasStarredVersion);
188 status.setOnOff(suffixIs(cmdname, "*"));
190 else if (cmd.getArg(1) == "casing") {
191 status.setEnabled(cs.forceUpperCase);
192 status.setOnOff(isUpperCase(cmdname[0]));
197 return InsetCommand::getStatus(cur, cmd, status);
202 bool InsetCitation::addKey(string const & key)
204 docstring const ukey = from_utf8(key);
205 docstring const & curkeys = getParam("key");
206 if (curkeys.empty()) {
207 setParam("key", ukey);
208 cache.recalculate = true;
212 vector<docstring> keys = getVectorFromString(curkeys);
213 vector<docstring>::const_iterator it = keys.begin();
214 vector<docstring>::const_iterator en = keys.end();
215 for (; it != en; ++it) {
217 LYXERR0("Key " << key << " already present.");
221 keys.push_back(ukey);
222 setParam("key", getStringFromVector(keys));
223 cache.recalculate = true;
228 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
230 Buffer const & buf = bv.buffer();
231 // Only after the buffer is loaded from file...
232 if (!buf.isFullyLoaded())
235 BiblioInfo const & bi = buf.masterBibInfo();
237 return _("No bibliography defined!");
239 docstring const & key = getParam("key");
241 return _("No citations selected!");
245 vector<docstring> keys = getVectorFromString(key);
246 if (keys.size() == 1)
247 return bi.getInfo(keys[0], buffer(), ci);
252 for (docstring const & key : keys) {
253 docstring const key_info = bi.getInfo(key, buffer(), ci);
254 // limit to reasonable size.
255 if (count > 9 && keys.size() > 11) {
256 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
258 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
262 if (key_info.empty())
264 tip += "<li>" + key_info + "</li>";
274 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
275 vector<CitationStyle> const & valid_styles)
277 CitationStyle cs = valid_styles[0];
278 cs.forceUpperCase = false;
279 cs.hasStarredVersion = false;
281 string normalized_input = input;
282 string::size_type const n = input.size() - 1;
283 if (isUpperCase(input[0]))
284 normalized_input[0] = lowercase(input[0]);
286 normalized_input = normalized_input.substr(0, n);
288 string const alias = bp.getCiteAlias(normalized_input);
290 normalized_input = alias;
292 vector<CitationStyle>::const_iterator it = valid_styles.begin();
293 vector<CitationStyle>::const_iterator end = valid_styles.end();
294 for (; it != end; ++it) {
295 CitationStyle this_cs = *it;
296 if (this_cs.name == normalized_input) {
302 cs.forceUpperCase &= input[0] == uppercase(input[0]);
303 cs.hasStarredVersion &= input[n] == '*';
309 inline docstring wrapCitation(docstring const & key,
310 docstring const & content, bool for_xhtml)
314 // we have to do the escaping here, because we will ultimately
315 // write this as a raw string, so as not to escape the tags.
316 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
317 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
320 } // anonymous namespace
323 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
325 vector<docstring> ps =
326 getVectorFromString(p, from_ascii("\t"));
327 std::map<docstring, docstring> res;
328 for (docstring const & s: ps) {
330 docstring val = split(s, key, ' ');
336 docstring InsetCitation::generateLabel(bool for_xhtml) const
339 label = complexLabel(for_xhtml);
341 // Fallback to fail-safe
343 label = basicLabel(for_xhtml);
349 docstring InsetCitation::complexLabel(bool for_xhtml) const
351 Buffer const & buf = buffer();
352 // Only start the process off after the buffer is loaded from file.
353 if (!buf.isFullyLoaded())
356 BiblioInfo const & biblist = buf.masterBibInfo();
360 docstring const & key = getParam("key");
362 return _("No citations selected!");
364 string cite_type = getCmdName();
365 bool const uppercase = isUpperCase(cite_type[0]);
367 cite_type[0] = lowercase(cite_type[0]);
368 bool const starred = (cite_type[cite_type.size() - 1] == '*');
370 cite_type = cite_type.substr(0, cite_type.size() - 1);
373 string const alias = buf.masterParams().getCiteAlias(cite_type);
377 // FIXME: allow to add cite macros
379 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
380 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
383 vector<docstring> keys = getVectorFromString(key);
384 CitationStyle cs = getCitationStyle(buffer().masterParams(),
385 cite_type, buffer().masterParams().citeStyles());
386 bool const qualified = cs.hasQualifiedList
388 || !getParam("pretextlist").empty()
389 || !getParam("posttextlist").empty());
390 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
391 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
394 ci.textBefore = getParam("before");
395 ci.textAfter = getParam("after");
396 ci.forceUpperCase = uppercase;
397 ci.Starred = starred;
398 ci.max_size = UINT_MAX;
399 ci.isQualified = qualified;
401 ci.posttexts = posts;
403 ci.max_key_size = UINT_MAX;
404 ci.context = CiteItem::Export;
406 ci.richtext = for_xhtml;
407 label = biblist.getLabel(keys, buffer(), cite_type, ci);
412 docstring InsetCitation::basicLabel(bool for_xhtml) const
414 docstring keys = getParam("key");
419 // if there is no comma, then everything goes into key
420 // and keys will be empty.
421 keys = trim(split(keys, key, ','));
425 label += wrapCitation(key, key, for_xhtml);
426 } while (!keys.empty());
428 docstring const & after = getParam("after");
430 label += ", " + after;
432 return '[' + label + ']';
435 docstring InsetCitation::screenLabel() const
437 return cache.screen_label;
441 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
443 if (!cache.recalculate && buffer().citeLabelsValid())
445 // The label may have changed, so we have to re-create it.
446 docstring const glabel = generateLabel();
447 cache.recalculate = false;
448 cache.generated_label = glabel;
449 unsigned int const maxLabelChars = 45;
450 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
451 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
455 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
456 UpdateType, TocBackend & backend) const
459 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
460 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
461 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
462 // then we will also need to change that routine.
463 docstring const tocitem = getParam("key");
464 TocBuilder & b = backend.builder("citation");
465 b.pushItem(cpit, tocitem, output_active);
470 int InsetCitation::plaintext(odocstringstream & os,
471 OutputParams const &, size_t) const
473 string const & cmd = getCmdName();
477 docstring const label = generateLabel(false);
483 static docstring const cleanupWhitespace(docstring const & citelist)
485 docstring::const_iterator it = citelist.begin();
486 docstring::const_iterator end = citelist.end();
487 // Paranoia check: make sure that there is no whitespace in here
488 // -- at least not behind commas or at the beginning
490 char_type last = ',';
491 for (; it != end; ++it) {
494 if (*it != ' ' || last != ',')
501 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
503 os << from_ascii("<citation>")
504 << cleanupWhitespace(getParam("key"))
505 << from_ascii("</citation>");
510 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
512 string const & cmd = getCmdName();
516 // have to output this raw, because generateLabel() will include tags
517 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
523 void InsetCitation::toString(odocstream & os) const
525 odocstringstream ods;
526 plaintext(ods, OutputParams(0));
531 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
537 // Have to overwrite the default InsetCommand method in order to check that
538 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
539 // citations and then changes his mind, turning natbib support off. The output
540 // should revert to the default citation command as provided by the citation
541 // engine, e.g. \cite[]{} for the basic engine.
542 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
544 BiblioInfo const & bi = buffer().masterBibInfo();
545 docstring const key = getParam("key");
546 // "keyonly" command: output the plain key and stop.
547 if (getCmdName() == "keyonly") {
548 // Special command to only return the key
549 if (!bi.isBibtex(getParam("key")))
550 // escape chars with bibitems
551 os << escape(cleanupWhitespace(key));
553 os << cleanupWhitespace(key);
556 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
557 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
558 getCmdName(), citation_styles);
560 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
562 // check if we have to do a qualified list
563 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
564 bool const qualified = cs.hasQualifiedList
565 && (!getParam("pretextlist").empty()
566 || !getParam("posttextlist").empty());
568 if (runparams.inulemcmd > 0)
571 os << "\\" << cite_str;
576 docstring before = params().prepareCommand(runparams, getParam("before"),
577 param_info_["before"].handling());
578 docstring after = params().prepareCommand(runparams, getParam("after"),
579 param_info_["after"].handling());
580 if (!before.empty() && cs.textBefore) {
582 os << '(' << protectArgument(before, '(', ')')
583 << ")(" << protectArgument(after, '(', ')') << ')';
585 os << '[' << protectArgument(before) << "]["
586 << protectArgument(after) << ']';
587 } else if (!after.empty() && cs.textAfter) {
589 os << '(' << protectArgument(after, '(', ')') << ')';
591 os << '[' << protectArgument(after) << ']';
594 if (!bi.isBibtex(key))
595 // escape chars with bibitems
596 os << '{' << escape(cleanupWhitespace(key)) << '}';
599 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
600 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
601 for (docstring const & k: keys) {
602 docstring bef = params().prepareCommand(runparams, pres[k],
603 param_info_["pretextlist"].handling());
604 docstring aft = params().prepareCommand(runparams, posts[k],
605 param_info_["posttextlist"].handling());
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";