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);
154 InsetCommand::doDispatch(cur, cmd);
159 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
160 FuncStatus & status) const
162 switch (cmd.action()) {
163 // Handle the alias case
164 case LFUN_INSET_MODIFY:
165 if (cmd.getArg(0) == "changetype") {
166 string cmdname = getCmdName();
168 buffer().masterParams().getCiteAlias(cmdname);
171 if (suffixIs(cmdname, "*"))
172 cmdname = rtrim(cmdname, "*");
173 string const newtype = cmd.getArg(1);
174 status.setEnabled(isCompatibleCommand(newtype));
175 status.setOnOff(newtype == cmdname);
177 if (cmd.getArg(0) == "toggleparam") {
178 string cmdname = getCmdName();
180 buffer().masterParams().getCiteAlias(cmdname);
183 vector<CitationStyle> citation_styles =
184 buffer().masterParams().citeStyles();
185 CitationStyle cs = getCitationStyle(buffer().masterParams(),
186 cmdname, citation_styles);
187 if (cmd.getArg(1) == "star") {
188 status.setEnabled(cs.hasStarredVersion);
189 status.setOnOff(suffixIs(cmdname, "*"));
191 else if (cmd.getArg(1) == "casing") {
192 status.setEnabled(cs.forceUpperCase);
193 status.setOnOff(isUpperCase(cmdname[0]));
198 return InsetCommand::getStatus(cur, cmd, status);
203 bool InsetCitation::addKey(string const & key)
205 docstring const ukey = from_utf8(key);
206 docstring const & curkeys = getParam("key");
207 if (curkeys.empty()) {
208 setParam("key", ukey);
209 cache.recalculate = true;
213 vector<docstring> keys = getVectorFromString(curkeys);
214 vector<docstring>::const_iterator it = keys.begin();
215 vector<docstring>::const_iterator en = keys.end();
216 for (; it != en; ++it) {
218 LYXERR0("Key " << key << " already present.");
222 keys.push_back(ukey);
223 setParam("key", getStringFromVector(keys));
224 cache.recalculate = true;
229 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
231 Buffer const & buf = bv.buffer();
232 // Only after the buffer is loaded from file...
233 if (!buf.isFullyLoaded())
236 BiblioInfo const & bi = buf.masterBibInfo();
238 return _("No bibliography defined!");
240 docstring const & key = getParam("key");
242 return _("No citations selected!");
246 vector<docstring> keys = getVectorFromString(key);
247 if (keys.size() == 1)
248 return bi.getInfo(keys[0], buffer(), ci);
253 for (docstring const & key : keys) {
254 docstring const key_info = bi.getInfo(key, buffer(), ci);
255 // limit to reasonable size.
256 if (count > 9 && keys.size() > 11) {
257 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
259 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
263 if (key_info.empty())
265 tip += "<li>" + key_info + "</li>";
275 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
276 vector<CitationStyle> const & valid_styles)
278 CitationStyle cs = valid_styles[0];
279 cs.forceUpperCase = false;
280 cs.hasStarredVersion = false;
282 string normalized_input = input;
283 string::size_type const n = input.size() - 1;
284 if (isUpperCase(input[0]))
285 normalized_input[0] = lowercase(input[0]);
287 normalized_input = normalized_input.substr(0, n);
289 string const alias = bp.getCiteAlias(normalized_input);
291 normalized_input = alias;
293 vector<CitationStyle>::const_iterator it = valid_styles.begin();
294 vector<CitationStyle>::const_iterator end = valid_styles.end();
295 for (; it != end; ++it) {
296 CitationStyle this_cs = *it;
297 if (this_cs.name == normalized_input) {
303 cs.forceUpperCase &= input[0] == uppercase(input[0]);
304 cs.hasStarredVersion &= input[n] == '*';
310 inline docstring wrapCitation(docstring const & key,
311 docstring const & content, bool for_xhtml)
315 // we have to do the escaping here, because we will ultimately
316 // write this as a raw string, so as not to escape the tags.
317 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
318 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
321 } // anonymous namespace
324 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
326 vector<docstring> ps =
327 getVectorFromString(p, from_ascii("\t"));
328 std::map<docstring, docstring> res;
329 for (docstring const & s: ps) {
331 docstring val = split(s, key, ' ');
337 docstring InsetCitation::generateLabel(bool for_xhtml) const
340 label = complexLabel(for_xhtml);
342 // Fallback to fail-safe
344 label = basicLabel(for_xhtml);
350 docstring InsetCitation::complexLabel(bool for_xhtml) const
352 Buffer const & buf = buffer();
353 // Only start the process off after the buffer is loaded from file.
354 if (!buf.isFullyLoaded())
357 BiblioInfo const & biblist = buf.masterBibInfo();
361 docstring const & key = getParam("key");
363 return _("No citations selected!");
365 string cite_type = getCmdName();
366 bool const uppercase = isUpperCase(cite_type[0]);
368 cite_type[0] = lowercase(cite_type[0]);
369 bool const starred = (cite_type[cite_type.size() - 1] == '*');
371 cite_type = cite_type.substr(0, cite_type.size() - 1);
374 string const alias = buf.masterParams().getCiteAlias(cite_type);
378 // FIXME: allow to add cite macros
380 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
381 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
384 vector<docstring> keys = getVectorFromString(key);
385 CitationStyle cs = getCitationStyle(buffer().masterParams(),
386 cite_type, buffer().masterParams().citeStyles());
387 bool const qualified = cs.hasQualifiedList
389 || !getParam("pretextlist").empty()
390 || !getParam("posttextlist").empty());
391 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
392 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
395 ci.textBefore = getParam("before");
396 ci.textAfter = getParam("after");
397 ci.forceUpperCase = uppercase;
398 ci.Starred = starred;
399 ci.max_size = UINT_MAX;
400 ci.isQualified = qualified;
402 ci.posttexts = posts;
404 ci.max_key_size = UINT_MAX;
405 ci.context = CiteItem::Export;
407 ci.richtext = for_xhtml;
408 label = biblist.getLabel(keys, buffer(), cite_type, ci);
413 docstring InsetCitation::basicLabel(bool for_xhtml) const
415 docstring keys = getParam("key");
420 // if there is no comma, then everything goes into key
421 // and keys will be empty.
422 keys = trim(split(keys, key, ','));
426 label += wrapCitation(key, key, for_xhtml);
427 } while (!keys.empty());
429 docstring const & after = getParam("after");
431 label += ", " + after;
433 return '[' + label + ']';
436 docstring InsetCitation::screenLabel() const
438 return cache.screen_label;
442 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
444 if (!cache.recalculate && buffer().citeLabelsValid())
446 // The label may have changed, so we have to re-create it.
447 docstring const glabel = generateLabel();
448 cache.recalculate = false;
449 cache.generated_label = glabel;
450 unsigned int const maxLabelChars = 45;
451 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
452 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
456 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
457 UpdateType, TocBackend & backend) const
460 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
461 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
462 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
463 // then we will also need to change that routine.
464 docstring const tocitem = getParam("key");
465 TocBuilder & b = backend.builder("citation");
466 b.pushItem(cpit, tocitem, output_active);
471 int InsetCitation::plaintext(odocstringstream & os,
472 OutputParams const &, size_t) const
474 string const & cmd = getCmdName();
478 docstring const label = generateLabel(false);
484 static docstring const cleanupWhitespace(docstring const & citelist)
486 docstring::const_iterator it = citelist.begin();
487 docstring::const_iterator end = citelist.end();
488 // Paranoia check: make sure that there is no whitespace in here
489 // -- at least not behind commas or at the beginning
491 char_type last = ',';
492 for (; it != end; ++it) {
495 if (*it != ' ' || last != ',')
502 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
504 os << from_ascii("<citation>")
505 << cleanupWhitespace(getParam("key"))
506 << from_ascii("</citation>");
511 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
513 string const & cmd = getCmdName();
517 // have to output this raw, because generateLabel() will include tags
518 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
524 void InsetCitation::toString(odocstream & os) const
526 odocstringstream ods;
527 plaintext(ods, OutputParams(0));
532 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
538 // Have to overwrite the default InsetCommand method in order to check that
539 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
540 // citations and then changes his mind, turning natbib support off. The output
541 // should revert to the default citation command as provided by the citation
542 // engine, e.g. \cite[]{} for the basic engine.
543 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
545 BiblioInfo const & bi = buffer().masterBibInfo();
546 docstring const key = getParam("key");
547 // "keyonly" command: output the plain key and stop.
548 if (getCmdName() == "keyonly") {
549 // Special command to only return the key
550 if (!bi.isBibtex(getParam("key")))
551 // escape chars with bibitems
552 os << escape(cleanupWhitespace(key));
554 os << cleanupWhitespace(key);
557 vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
558 CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
559 getCmdName(), citation_styles);
561 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
563 // check if we have to do a qualified list
564 vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
565 bool const qualified = cs.hasQualifiedList
566 && (!getParam("pretextlist").empty()
567 || !getParam("posttextlist").empty());
569 if (runparams.inulemcmd > 0)
572 os << "\\" << cite_str;
577 docstring before = params().prepareCommand(runparams, getParam("before"),
578 param_info_["before"].handling());
579 docstring after = params().prepareCommand(runparams, getParam("after"),
580 param_info_["after"].handling());
581 if (!before.empty() && cs.textBefore) {
583 os << '(' << protectArgument(before, '(', ')')
584 << ")(" << protectArgument(after, '(', ')') << ')';
586 os << '[' << protectArgument(before) << "]["
587 << protectArgument(after) << ']';
588 } else if (!after.empty() && cs.textAfter) {
590 os << '(' << protectArgument(after, '(', ')') << ')';
592 os << '[' << protectArgument(after) << ']';
595 if (!bi.isBibtex(key))
596 // escape chars with bibitems
597 os << '{' << escape(cleanupWhitespace(key)) << '}';
600 map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
601 map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
602 for (docstring const & k: keys) {
603 docstring bef = params().prepareCommand(runparams, pres[k],
604 param_info_["pretextlist"].handling());
605 docstring aft = params().prepareCommand(runparams, posts[k],
606 param_info_["posttextlist"].handling());
608 os << '[' << protectArgument(bef)
609 << "][" << protectArgument(aft) << ']';
610 else if (!aft.empty())
611 os << '[' << protectArgument(aft) << ']';
612 os << '{' << k << '}';
615 os << '{' << cleanupWhitespace(key) << '}';
618 if (runparams.inulemcmd)
623 string InsetCitation::contextMenuName() const
625 return "context-citation";