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"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "DispatchResult.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
23 #include "output_xhtml.h"
24 #include "ParIterator.h"
25 #include "TocBackend.h"
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/FileNameList.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
36 using namespace lyx::support;
40 ParamInfo InsetCitation::param_info_;
43 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
44 : InsetCommand(buf, p, "citation")
48 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
50 // standard cite does only take one argument if jurabib is
51 // not used, but jurabib extends this to two arguments, so
52 // we have to allow both here. InsetCitation takes care that
53 // LaTeX output is nevertheless correct.
54 if (param_info_.empty()) {
55 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
56 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
57 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
65 vector<string> const init_possible_cite_commands()
67 char const * const possible[] = {
68 "cite", "nocite", "citet", "citep", "citealt", "citealp",
69 "citeauthor", "citeyear", "citeyearpar",
70 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
71 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
72 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
74 "footcite", "footcitet", "footcitep", "footcitealt",
75 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
76 "citefield", "citetitle", "cite*"
78 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
80 return vector<string>(possible, possible + size_possible);
84 vector<string> const & possibleCiteCommands()
86 static vector<string> const possible = init_possible_cite_commands();
94 bool InsetCitation::isCompatibleCommand(string const & cmd)
96 vector<string> const & possibles = possibleCiteCommands();
97 vector<string>::const_iterator const end = possibles.end();
98 return find(possibles.begin(), end, cmd) != end;
102 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
104 Buffer const & buf = bv.buffer();
105 // Only after the buffer is loaded from file...
106 if (!buf.isFullyLoaded())
109 BiblioInfo const & bi = buf.masterBibInfo();
111 return _("No bibliography defined!");
113 docstring const & key = getParam("key");
115 return _("No citations selected!");
117 vector<docstring> keys = getVectorFromString(key);
118 vector<docstring>::const_iterator it = keys.begin();
119 vector<docstring>::const_iterator en = keys.end();
121 for (; it != en; ++it) {
122 docstring const key_info = bi.getInfo(*it, buffer());
123 if (key_info.empty())
127 tip += wrap(key_info, -4);
135 // FIXME See the header for the issue.
136 string defaultCiteCommand(CiteEngine engine)
143 case ENGINE_NATBIB_AUTHORYEAR:
146 case ENGINE_NATBIB_NUMERICAL:
157 string asValidLatexCommand(string const & input, CiteEngine const engine)
159 string const default_str = defaultCiteCommand(engine);
160 if (!InsetCitation::isCompatibleCommand(input))
166 if (input == "nocite")
169 output = default_str;
172 case ENGINE_NATBIB_AUTHORYEAR:
173 case ENGINE_NATBIB_NUMERICAL:
174 if (input == "cite" || input == "citefield"
175 || input == "citetitle" || input == "cite*")
176 output = default_str;
177 else if (prefixIs(input, "foot"))
178 output = input.substr(4);
183 case ENGINE_JURABIB: {
184 // Jurabib does not support the 'uppercase' natbib style.
186 output = string(1, 'c') + input.substr(1);
190 // Jurabib does not support the 'full' natbib style.
191 string::size_type const n = output.size() - 1;
192 if (output != "cite*" && output[n] == '*')
193 output = output.substr(0, n);
203 inline docstring wrapCitation(docstring const & key,
204 docstring const & content, bool for_xhtml)
208 // we have to do the escaping here, because we will ultimately
209 // write this as a raw string, so as not to escape the tags.
210 return "<a href='#" + key + "'>" + html::htmlize(content) + "</a>";
213 } // anonymous namespace
215 docstring InsetCitation::generateLabel(bool for_xhtml) const
218 label = complexLabel(for_xhtml);
220 // Fallback to fail-safe
222 label = basicLabel(for_xhtml);
228 docstring InsetCitation::complexLabel(bool for_xhtml) const
230 Buffer const & buf = buffer();
231 // Only start the process off after the buffer is loaded from file.
232 if (!buf.isFullyLoaded())
235 BiblioInfo const & biblist = buf.masterBibInfo();
239 // the natbib citation-styles
240 // CITET: author (year)
241 // CITEP: (author,year)
242 // CITEALT: author year
243 // CITEALP: author, year
244 // CITEAUTHOR: author
246 // CITEYEARPAR: (year)
247 // jurabib supports these plus
248 // CITE: author/<before field>
250 CiteEngine const engine = buffer().params().citeEngine();
251 // We don't currently use the full or forceUCase fields.
252 string cite_type = asValidLatexCommand(getCmdName(), engine);
253 if (cite_type[0] == 'C')
254 // If we were going to use them, this would mean ForceUCase
255 cite_type = string(1, 'c') + cite_type.substr(1);
256 if (cite_type[cite_type.size() - 1] == '*')
257 // and this would mean FULL
258 cite_type = cite_type.substr(0, cite_type.size() - 1);
260 docstring const & before = getParam("before");
261 docstring before_str;
262 if (!before.empty()) {
263 // In CITET and CITEALT mode, the "before" string is
264 // attached to the label associated with each and every key.
265 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
266 // to the front of the whole only.
267 // In other modes, it is not used at all.
268 if (cite_type == "citet" ||
269 cite_type == "citealt" ||
270 cite_type == "citep" ||
271 cite_type == "citealp" ||
272 cite_type == "citeyearpar")
273 before_str = before + ' ';
274 // In CITE (jurabib), the "before" string is used to attach
275 // the annotator (of legal texts) to the author(s) of the
277 else if (cite_type == "cite")
278 before_str = '/' + before;
281 docstring const & after = getParam("after");
283 // The "after" key is appended only to the end of the whole.
284 if (cite_type == "nocite")
285 after_str = " (" + _("not cited") + ')';
286 else if (!after.empty()) {
287 after_str = ", " + after;
290 // One day, these might be tunable (as they are in BibTeX).
291 char op, cp; // opening and closing parenthesis.
292 const char * sep; // punctuation mark separating citation entries.
293 if (engine == ENGINE_BASIC) {
303 docstring const op_str = ' ' + docstring(1, op);
304 docstring const cp_str = docstring(1, cp) + ' ';
305 docstring const sep_str = from_ascii(sep) + ' ';
308 vector<docstring> keys = getVectorFromString(getParam("key"));
309 vector<docstring>::const_iterator it = keys.begin();
310 vector<docstring>::const_iterator end = keys.end();
311 for (; it != end; ++it) {
312 // get the bibdata corresponding to the key
313 docstring const author = biblist.getAbbreviatedAuthor(*it);
314 docstring const year = biblist.getYear(*it, for_xhtml);
315 docstring const citenum = for_xhtml ? biblist.getCiteNumber(*it) : *it;
317 if (author.empty() || year.empty())
318 // We can't construct a "complex" label without that info.
322 // authors1/<before>; ... ;
323 // authors_last, <after>
324 if (cite_type == "cite") {
325 if (engine == ENGINE_BASIC) {
326 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
327 } else if (engine == ENGINE_JURABIB) {
328 if (it == keys.begin())
329 label += wrapCitation(*it, author, for_xhtml) + before_str + sep_str;
331 label += wrapCitation(*it, author, for_xhtml) + sep_str;
335 else if (cite_type == "nocite") {
336 label += *it + sep_str;
338 // (authors1 (<before> year); ... ;
339 // authors_last (<before> year, <after>)
340 else if (cite_type == "citet") {
342 case ENGINE_NATBIB_AUTHORYEAR:
343 label += author + op_str + before_str +
344 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
346 case ENGINE_NATBIB_NUMERICAL:
347 label += author + op_str + before_str +
348 wrapCitation(*it, citenum, for_xhtml) + cp + sep_str;
351 label += before_str + author + op_str +
352 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
358 // author, year; author, year; ...
359 else if (cite_type == "citep" ||
360 cite_type == "citealp") {
361 if (engine == ENGINE_NATBIB_NUMERICAL) {
362 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
364 label += wrapCitation(*it, author + ", " + year, for_xhtml) + sep_str;
368 // (authors1 <before> year;
369 // authors_last <before> year, <after>)
370 else if (cite_type == "citealt") {
372 case ENGINE_NATBIB_AUTHORYEAR:
373 label += author + ' ' + before_str +
374 wrapCitation(*it, year, for_xhtml) + sep_str;
376 case ENGINE_NATBIB_NUMERICAL:
377 label += author + ' ' + before_str + '#' +
378 wrapCitation(*it, citenum, for_xhtml) + sep_str;
381 label += before_str +
382 wrapCitation(*it, author + ' ' + year, for_xhtml) + sep_str;
390 // author; author; ...
391 else if (cite_type == "citeauthor") {
392 label += wrapCitation(*it, author, for_xhtml) + sep_str;
395 else if (cite_type == "citeyear" ||
396 cite_type == "citeyearpar") {
397 label += wrapCitation(*it, year, for_xhtml) + sep_str;
400 label = rtrim(rtrim(label), sep);
402 if (!after_str.empty()) {
403 if (cite_type == "citet") {
404 // insert "after" before last ')'
405 label.insert(label.size() - 1, after_str);
408 !(engine == ENGINE_NATBIB_NUMERICAL &&
409 (cite_type == "citeauthor" ||
410 cite_type == "citeyear"));
416 if (!before_str.empty() && (cite_type == "citep" ||
417 cite_type == "citealp" ||
418 cite_type == "citeyearpar")) {
419 label = before_str + label;
422 if (cite_type == "citep" || cite_type == "citeyearpar" ||
423 (cite_type == "cite" && engine == ENGINE_BASIC) )
424 label = op + label + cp;
430 docstring InsetCitation::basicLabel(bool for_xhtml) const
432 docstring keys = getParam("key");
437 // if there is no comma, then everything goes into key
438 // and keys will be empty.
439 keys = trim(split(keys, key, ','));
443 label += wrapCitation(key, key, for_xhtml);
444 } while (!keys.empty());
446 docstring const & after = getParam("after");
448 label += ", " + after;
450 return '[' + label + ']';
453 docstring InsetCitation::screenLabel() const
455 return cache.screen_label;
459 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
461 CiteEngine const engine = buffer().params().citeEngine();
462 if (cache.params == params() && cache.engine == engine)
465 // The label has changed, so we have to re-create it.
466 docstring const glabel = generateLabel();
468 unsigned int const maxLabelChars = 45;
470 docstring label = glabel;
471 if (label.size() > maxLabelChars) {
472 label.erase(maxLabelChars - 3);
476 cache.engine = engine;
477 cache.params = params();
478 cache.generated_label = glabel;
479 cache.screen_label = label;
483 void InsetCitation::addToToc(DocIterator const & cpit)
485 Toc & toc = buffer().tocBackend().toc("citation");
486 toc.push_back(TocItem(cpit, 0, getParam("key")));
490 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
492 os << cache.generated_label;
493 return cache.generated_label.size();
497 static docstring const cleanupWhitespace(docstring const & citelist)
499 docstring::const_iterator it = citelist.begin();
500 docstring::const_iterator end = citelist.end();
501 // Paranoia check: make sure that there is no whitespace in here
502 // -- at least not behind commas or at the beginning
504 char_type last = ',';
505 for (; it != end; ++it) {
508 if (*it != ' ' || last != ',')
515 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
517 os << from_ascii("<citation>")
518 << cleanupWhitespace(getParam("key"))
519 << from_ascii("</citation>");
524 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
526 string const & cmd = getCmdName();
530 // have to output this raw, because generateLabel() will include tags
531 xs << XHTMLStream::NextRaw() << generateLabel(true);
537 void InsetCitation::tocString(odocstream & os) const
539 plaintext(os, OutputParams(0));
543 // Have to overwrite the default InsetCommand method in order to check that
544 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
545 // citations and then changes his mind, turning natbib support off. The output
546 // should revert to \cite[]{}
547 int InsetCitation::latex(odocstream & os, OutputParams const & runparams) const
549 CiteEngine cite_engine = buffer().params().citeEngine();
550 BiblioInfo const & bi = buffer().masterBibInfo();
552 docstring const cite_str = from_utf8(
553 asValidLatexCommand(getCmdName(), cite_engine));
555 if (runparams.inulemcmd)
558 os << "\\" << cite_str;
560 docstring const & before = getParam("before");
561 docstring const & after = getParam("after");
562 if (!before.empty() && cite_engine != ENGINE_BASIC)
563 os << '[' << before << "][" << after << ']';
564 else if (!after.empty())
565 os << '[' << after << ']';
567 if (!bi.isBibtex(getParam("key")))
568 // escape chars with bibitems
569 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
571 os << '{' << cleanupWhitespace(getParam("key")) << '}';
573 if (runparams.inulemcmd)
580 void InsetCitation::validate(LaTeXFeatures & features) const
582 switch (features.bufferParams().citeEngine()) {
585 case ENGINE_NATBIB_AUTHORYEAR:
586 case ENGINE_NATBIB_NUMERICAL:
587 features.require("natbib");
590 features.require("jurabib");
596 docstring InsetCitation::contextMenu(BufferView const &, int, int) const
598 return from_ascii("context-citation");