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 "BufferParams.h"
18 #include "support/debug.h"
19 #include "DispatchResult.h"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
23 #include "support/lstrings.h"
24 #include "support/docstream.h"
25 #include "support/FileNameList.h"
34 using support::FileName;
35 using support::FileNameList;
36 using support::getStringFromVector;
37 using support::getVectorFromString;
39 using support::prefixIs;
42 using support::tokenPos;
46 vector<string> const init_possible_cite_commands()
48 char const * const possible[] = {
49 "cite", "citet", "citep", "citealt", "citealp",
50 "citeauthor", "citeyear", "citeyearpar",
51 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
52 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
53 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
55 "footcite", "footcitet", "footcitep", "footcitealt",
56 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
57 "citefield", "citetitle", "cite*"
59 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
61 return vector<string>(possible, possible + size_possible);
65 vector<string> const & possible_cite_commands()
67 static vector<string> const possible = init_possible_cite_commands();
72 //FIXME See the header for the issue.
73 string const default_cite_command(biblio::CiteEngine engine)
77 case biblio::ENGINE_BASIC:
80 case biblio::ENGINE_NATBIB_AUTHORYEAR:
83 case biblio::ENGINE_NATBIB_NUMERICAL:
86 case biblio::ENGINE_JURABIB:
95 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
97 string const default_str = default_cite_command(engine);
98 if (!InsetCitation::isCompatibleCommand(input))
103 case biblio::ENGINE_BASIC:
104 output = default_str;
107 case biblio::ENGINE_NATBIB_AUTHORYEAR:
108 case biblio::ENGINE_NATBIB_NUMERICAL:
109 if (input == "cite" || input == "citefield" ||
110 input == "citetitle" || input == "cite*")
111 output = default_str;
112 else if (prefixIs(input, "foot"))
113 output = input.substr(4);
118 case biblio::ENGINE_JURABIB: {
119 // Jurabib does not support the 'uppercase' natbib style.
121 output = string(1, 'c') + input.substr(1);
125 // Jurabib does not support the 'full' natbib style.
126 string::size_type const n = output.size() - 1;
127 if (output != "cite*" && output[n] == '*')
128 output = output.substr(0, n);
138 docstring const getNatbibLabel(Buffer const & buffer,
139 string const & citeType, docstring const & keyList,
140 docstring const & before, docstring const & after,
141 biblio::CiteEngine engine)
143 // Only start the process off after the buffer is loaded from file.
144 if (!buffer.isFullyLoaded())
148 typedef std::map<Buffer const *, BiblioInfo> CachedMap;
149 static CachedMap cached_keys;
151 // and cache the timestamp of the bibliography files.
152 static std::map<FileName, time_t> bibfileStatus;
156 FileNameList const & bibfilesCache = buffer.getBibfilesCache();
157 // compare the cached timestamps with the actual ones.
158 bool changed = false;
159 for (FileNameList::const_iterator it = bibfilesCache.begin();
160 it != bibfilesCache.end(); ++ it) {
161 FileName const f = *it;
162 std::time_t lastw = f.lastModified();
163 if (lastw != bibfileStatus[f]) {
165 bibfileStatus[f] = lastw;
169 // build the list only if the bibfiles have been changed
170 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
171 biblist.fillWithBibKeys(&buffer);
172 cached_keys[&buffer] = biblist;
174 // use the cached keys
175 biblist = cached_keys[&buffer];
181 // the natbib citation-styles
182 // CITET: author (year)
183 // CITEP: (author,year)
184 // CITEALT: author year
185 // CITEALP: author, year
186 // CITEAUTHOR: author
188 // CITEYEARPAR: (year)
189 // jurabib supports these plus
190 // CITE: author/<before field>
192 // We don't currently use the full or forceUCase fields.
193 string cite_type = asValidLatexCommand(citeType, engine);
194 if (cite_type[0] == 'C')
195 //If we were going to use them, this would mean ForceUCase
196 cite_type = string(1, 'c') + cite_type.substr(1);
197 if (cite_type[cite_type.size() - 1] == '*')
198 //and this would mean FULL
199 cite_type = cite_type.substr(0, cite_type.size() - 1);
201 docstring before_str;
202 if (!before.empty()) {
203 // In CITET and CITEALT mode, the "before" string is
204 // attached to the label associated with each and every key.
205 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
206 // to the front of the whole only.
207 // In other modes, it is not used at all.
208 if (cite_type == "citet" ||
209 cite_type == "citealt" ||
210 cite_type == "citep" ||
211 cite_type == "citealp" ||
212 cite_type == "citeyearpar")
213 before_str = before + ' ';
214 // In CITE (jurabib), the "before" string is used to attach
215 // the annotator (of legal texts) to the author(s) of the
217 else if (cite_type == "cite")
218 before_str = '/' + before;
222 if (!after.empty()) {
223 // The "after" key is appended only to the end of the whole.
224 after_str = ", " + after;
227 // One day, these might be tunable (as they are in BibTeX).
228 char const op = '('; // opening parenthesis.
229 char const cp = ')'; // closing parenthesis.
230 // puctuation mark separating citation entries.
231 char const * const sep = ";";
233 docstring const op_str = ' ' + docstring(1, op);
234 docstring const cp_str = docstring(1, cp) + ' ';
235 docstring const sep_str = from_ascii(sep) + ' ';
238 vector<docstring> keys = getVectorFromString(keyList);
239 vector<docstring>::const_iterator it = keys.begin();
240 vector<docstring>::const_iterator end = keys.end();
241 for (; it != end; ++it) {
242 // get the bibdata corresponding to the key
243 docstring const author(biblist.getAbbreviatedAuthor(*it));
244 docstring const year(biblist.getYear(*it));
246 // Something isn't right. Fail safely.
247 if (author.empty() || year.empty())
250 // authors1/<before>; ... ;
251 // authors_last, <after>
252 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
253 if (it == keys.begin())
254 label += author + before_str + sep_str;
256 label += author + sep_str;
258 // (authors1 (<before> year); ... ;
259 // authors_last (<before> year, <after>)
260 } else if (cite_type == "citet") {
262 case biblio::ENGINE_NATBIB_AUTHORYEAR:
263 label += author + op_str + before_str +
266 case biblio::ENGINE_NATBIB_NUMERICAL:
267 label += author + op_str + before_str + '#' + *it + cp + sep_str;
269 case biblio::ENGINE_JURABIB:
270 label += before_str + author + op_str +
273 case biblio::ENGINE_BASIC:
277 // author, year; author, year; ...
278 } else if (cite_type == "citep" ||
279 cite_type == "citealp") {
280 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
281 label += *it + sep_str;
283 label += author + ", " + year + sep_str;
286 // (authors1 <before> year;
287 // authors_last <before> year, <after>)
288 } else if (cite_type == "citealt") {
290 case biblio::ENGINE_NATBIB_AUTHORYEAR:
291 label += author + ' ' + before_str +
294 case biblio::ENGINE_NATBIB_NUMERICAL:
295 label += author + ' ' + before_str + '#' + *it + sep_str;
297 case biblio::ENGINE_JURABIB:
298 label += before_str + author + ' ' +
301 case biblio::ENGINE_BASIC:
305 // author; author; ...
306 } else if (cite_type == "citeauthor") {
307 label += author + sep_str;
310 } else if (cite_type == "citeyear" ||
311 cite_type == "citeyearpar") {
312 label += year + sep_str;
315 label = rtrim(rtrim(label), sep);
317 if (!after_str.empty()) {
318 if (cite_type == "citet") {
319 // insert "after" before last ')'
320 label.insert(label.size() - 1, after_str);
323 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
324 (cite_type == "citeauthor" ||
325 cite_type == "citeyear"));
331 if (!before_str.empty() && (cite_type == "citep" ||
332 cite_type == "citealp" ||
333 cite_type == "citeyearpar")) {
334 label = before_str + label;
337 if (cite_type == "citep" || cite_type == "citeyearpar")
338 label = op + label + cp;
344 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
346 using support::contains;
348 docstring keys = keyList;
351 if (contains(keys, ',')) {
352 // Final comma allows while loop to cover all keys
353 keys = ltrim(split(keys, label, ',')) + ',';
354 while (contains(keys, ',')) {
356 keys = ltrim(split(keys, key, ','));
363 label += ", " + after;
365 return '[' + label + ']';
371 InsetCitation::InsetCitation(InsetCommandParams const & p)
372 : InsetCommand(p, "citation")
376 CommandInfo const * InsetCitation::findInfo(std::string const & /* cmdName */)
378 // standard cite does only take one argument if jurabib is
379 // not used, but jurabib extends this to two arguments, so
380 // we have to allow both here. InsetCitation takes care that
381 // LaTeX output is nevertheless correct.
382 static const char * const paramnames[] =
383 {"after", "before", "key", ""};
384 static const bool isoptional[] = {true, true, false};
385 static const CommandInfo info = {3, paramnames, isoptional};
390 bool InsetCitation::isCompatibleCommand(std::string const & cmd)
392 vector<string> const & possibles = possible_cite_commands();
393 vector<string>::const_iterator const end = possibles.end();
394 return std::find(possibles.begin(), end, cmd) != end;
398 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
400 docstring const before = getParam("before");
401 docstring const after = getParam("after");
404 biblio::CiteEngine const engine = buffer.params().getEngine();
405 if (engine != biblio::ENGINE_BASIC) {
406 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
407 before, after, engine);
410 // Fallback to fail-safe
412 label = getBasicLabel(getParam("key"), after);
418 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
420 biblio::CiteEngine const engine = buffer.params().getEngine();
421 if (cache.params == params() && cache.engine == engine)
422 return cache.screen_label;
424 // The label has changed, so we have to re-create it.
425 docstring const glabel = generateLabel(buffer);
427 unsigned int const maxLabelChars = 45;
429 docstring label = glabel;
430 if (label.size() > maxLabelChars) {
431 label.erase(maxLabelChars-3);
435 cache.engine = engine;
436 cache.params = params();
437 cache.generated_label = glabel;
438 cache.screen_label = label;
444 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
445 OutputParams const &) const
449 if (cache.params == params() &&
450 cache.engine == buffer.params().getEngine())
451 str = cache.generated_label;
453 str = generateLabel(buffer);
460 static docstring const cleanupWhitespace(docstring const & citelist)
462 docstring::const_iterator it = citelist.begin();
463 docstring::const_iterator end = citelist.end();
464 // Paranoia check: make sure that there is no whitespace in here
465 // -- at least not behind commas or at the beginning
467 char_type last = ',';
468 for (; it != end; ++it) {
471 if (*it != ' ' || last != ',')
478 int InsetCitation::docbook(Buffer const &, odocstream & os,
479 OutputParams const &) const
481 os << from_ascii("<citation>")
482 << cleanupWhitespace(getParam("key"))
483 << from_ascii("</citation>");
488 int InsetCitation::textString(Buffer const & buf, odocstream & os,
489 OutputParams const & op) const
491 return plaintext(buf, os, op);
495 // Have to overwrite the default InsetCommand method in order to check that
496 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
497 // citations and then changes his mind, turning natbib support off. The output
498 // should revert to \cite[]{}
499 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
500 OutputParams const &) const
502 biblio::CiteEngine cite_engine = buffer.params().getEngine();
504 docstring const cite_str = from_utf8(
505 asValidLatexCommand(getCmdName(), cite_engine));
507 os << "\\" << cite_str;
509 docstring const & before = getParam("before");
510 docstring const & after = getParam("after");
511 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
512 os << '[' << before << "][" << after << ']';
513 else if (!after.empty())
514 os << '[' << after << ']';
516 os << '{' << cleanupWhitespace(getParam("key")) << '}';
522 void InsetCitation::validate(LaTeXFeatures & features) const
524 switch (features.bufferParams().getEngine()) {
525 case biblio::ENGINE_BASIC:
527 case biblio::ENGINE_NATBIB_AUTHORYEAR:
528 case biblio::ENGINE_NATBIB_NUMERICAL:
529 features.require("natbib");
531 case biblio::ENGINE_JURABIB:
532 features.require("jurabib");