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"
30 using namespace lyx::support;
36 vector<string> const init_possible_cite_commands()
38 char const * const possible[] = {
39 "cite", "citet", "citep", "citealt", "citealp",
40 "citeauthor", "citeyear", "citeyearpar",
41 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
42 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
43 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
45 "footcite", "footcitet", "footcitep", "footcitealt",
46 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
47 "citefield", "citetitle", "cite*"
49 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
51 return vector<string>(possible, possible + size_possible);
55 vector<string> const & possible_cite_commands()
57 static vector<string> const possible = init_possible_cite_commands();
62 //FIXME See the header for the issue.
63 string const default_cite_command(biblio::CiteEngine engine)
67 case biblio::ENGINE_BASIC:
70 case biblio::ENGINE_NATBIB_AUTHORYEAR:
73 case biblio::ENGINE_NATBIB_NUMERICAL:
76 case biblio::ENGINE_JURABIB:
85 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
87 string const default_str = default_cite_command(engine);
88 if (!InsetCitation::isCompatibleCommand(input))
93 case biblio::ENGINE_BASIC:
97 case biblio::ENGINE_NATBIB_AUTHORYEAR:
98 case biblio::ENGINE_NATBIB_NUMERICAL:
99 if (input == "cite" || input == "citefield" ||
100 input == "citetitle" || input == "cite*")
101 output = default_str;
102 else if (prefixIs(input, "foot"))
103 output = input.substr(4);
108 case biblio::ENGINE_JURABIB: {
109 // Jurabib does not support the 'uppercase' natbib style.
111 output = string(1, 'c') + input.substr(1);
115 // Jurabib does not support the 'full' natbib style.
116 string::size_type const n = output.size() - 1;
117 if (output != "cite*" && output[n] == '*')
118 output = output.substr(0, n);
128 docstring const getNatbibLabel(Buffer const & buffer,
129 string const & citeType, docstring const & keyList,
130 docstring const & before, docstring const & after,
131 biblio::CiteEngine engine)
133 // Only start the process off after the buffer is loaded from file.
134 if (!buffer.isFullyLoaded())
138 typedef std::map<Buffer const *, BiblioInfo> CachedMap;
139 static CachedMap cached_keys;
141 // and cache the timestamp of the bibliography files.
142 static std::map<FileName, time_t> bibfileStatus;
146 FileNameList const & bibfilesCache = buffer.getBibfilesCache();
147 // compare the cached timestamps with the actual ones.
148 bool changed = false;
149 for (FileNameList::const_iterator it = bibfilesCache.begin();
150 it != bibfilesCache.end(); ++ it) {
151 FileName const f = *it;
152 std::time_t lastw = f.lastModified();
153 if (lastw != bibfileStatus[f]) {
155 bibfileStatus[f] = lastw;
159 // build the list only if the bibfiles have been changed
160 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
161 biblist.fillWithBibKeys(&buffer);
162 cached_keys[&buffer] = biblist;
164 // use the cached keys
165 biblist = cached_keys[&buffer];
171 // the natbib citation-styles
172 // CITET: author (year)
173 // CITEP: (author,year)
174 // CITEALT: author year
175 // CITEALP: author, year
176 // CITEAUTHOR: author
178 // CITEYEARPAR: (year)
179 // jurabib supports these plus
180 // CITE: author/<before field>
182 // We don't currently use the full or forceUCase fields.
183 string cite_type = asValidLatexCommand(citeType, engine);
184 if (cite_type[0] == 'C')
185 //If we were going to use them, this would mean ForceUCase
186 cite_type = string(1, 'c') + cite_type.substr(1);
187 if (cite_type[cite_type.size() - 1] == '*')
188 //and this would mean FULL
189 cite_type = cite_type.substr(0, cite_type.size() - 1);
191 docstring before_str;
192 if (!before.empty()) {
193 // In CITET and CITEALT mode, the "before" string is
194 // attached to the label associated with each and every key.
195 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
196 // to the front of the whole only.
197 // In other modes, it is not used at all.
198 if (cite_type == "citet" ||
199 cite_type == "citealt" ||
200 cite_type == "citep" ||
201 cite_type == "citealp" ||
202 cite_type == "citeyearpar")
203 before_str = before + ' ';
204 // In CITE (jurabib), the "before" string is used to attach
205 // the annotator (of legal texts) to the author(s) of the
207 else if (cite_type == "cite")
208 before_str = '/' + before;
212 if (!after.empty()) {
213 // The "after" key is appended only to the end of the whole.
214 after_str = ", " + after;
217 // One day, these might be tunable (as they are in BibTeX).
218 char const op = '('; // opening parenthesis.
219 char const cp = ')'; // closing parenthesis.
220 // puctuation mark separating citation entries.
221 char const * const sep = ";";
223 docstring const op_str = ' ' + docstring(1, op);
224 docstring const cp_str = docstring(1, cp) + ' ';
225 docstring const sep_str = from_ascii(sep) + ' ';
228 vector<docstring> keys = getVectorFromString(keyList);
229 vector<docstring>::const_iterator it = keys.begin();
230 vector<docstring>::const_iterator end = keys.end();
231 for (; it != end; ++it) {
232 // get the bibdata corresponding to the key
233 docstring const author(biblist.getAbbreviatedAuthor(*it));
234 docstring const year(biblist.getYear(*it));
236 // Something isn't right. Fail safely.
237 if (author.empty() || year.empty())
240 // authors1/<before>; ... ;
241 // authors_last, <after>
242 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
243 if (it == keys.begin())
244 label += author + before_str + sep_str;
246 label += author + sep_str;
248 // (authors1 (<before> year); ... ;
249 // authors_last (<before> year, <after>)
250 } else if (cite_type == "citet") {
252 case biblio::ENGINE_NATBIB_AUTHORYEAR:
253 label += author + op_str + before_str +
256 case biblio::ENGINE_NATBIB_NUMERICAL:
257 label += author + op_str + before_str + '#' + *it + cp + sep_str;
259 case biblio::ENGINE_JURABIB:
260 label += before_str + author + op_str +
263 case biblio::ENGINE_BASIC:
267 // author, year; author, year; ...
268 } else if (cite_type == "citep" ||
269 cite_type == "citealp") {
270 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
271 label += *it + sep_str;
273 label += author + ", " + year + sep_str;
276 // (authors1 <before> year;
277 // authors_last <before> year, <after>)
278 } else if (cite_type == "citealt") {
280 case biblio::ENGINE_NATBIB_AUTHORYEAR:
281 label += author + ' ' + before_str +
284 case biblio::ENGINE_NATBIB_NUMERICAL:
285 label += author + ' ' + before_str + '#' + *it + sep_str;
287 case biblio::ENGINE_JURABIB:
288 label += before_str + author + ' ' +
291 case biblio::ENGINE_BASIC:
295 // author; author; ...
296 } else if (cite_type == "citeauthor") {
297 label += author + sep_str;
300 } else if (cite_type == "citeyear" ||
301 cite_type == "citeyearpar") {
302 label += year + sep_str;
305 label = rtrim(rtrim(label), sep);
307 if (!after_str.empty()) {
308 if (cite_type == "citet") {
309 // insert "after" before last ')'
310 label.insert(label.size() - 1, after_str);
313 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
314 (cite_type == "citeauthor" ||
315 cite_type == "citeyear"));
321 if (!before_str.empty() && (cite_type == "citep" ||
322 cite_type == "citealp" ||
323 cite_type == "citeyearpar")) {
324 label = before_str + label;
327 if (cite_type == "citep" || cite_type == "citeyearpar")
328 label = op + label + cp;
334 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
336 using support::contains;
338 docstring keys = keyList;
341 if (contains(keys, ',')) {
342 // Final comma allows while loop to cover all keys
343 keys = ltrim(split(keys, label, ',')) + ',';
344 while (contains(keys, ',')) {
346 keys = ltrim(split(keys, key, ','));
353 label += ", " + after;
355 return '[' + label + ']';
361 InsetCitation::InsetCitation(InsetCommandParams const & p)
362 : InsetCommand(p, "citation")
366 CommandInfo const * InsetCitation::findInfo(std::string const & /* cmdName */)
368 // standard cite does only take one argument if jurabib is
369 // not used, but jurabib extends this to two arguments, so
370 // we have to allow both here. InsetCitation takes care that
371 // LaTeX output is nevertheless correct.
372 static const char * const paramnames[] =
373 {"after", "before", "key", ""};
374 static const bool isoptional[] = {true, true, false};
375 static const CommandInfo info = {3, paramnames, isoptional};
380 bool InsetCitation::isCompatibleCommand(std::string const & cmd)
382 vector<string> const & possibles = possible_cite_commands();
383 vector<string>::const_iterator const end = possibles.end();
384 return std::find(possibles.begin(), end, cmd) != end;
388 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
390 docstring const before = getParam("before");
391 docstring const after = getParam("after");
394 biblio::CiteEngine const engine = buffer.params().getEngine();
395 if (engine != biblio::ENGINE_BASIC) {
396 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
397 before, after, engine);
400 // Fallback to fail-safe
402 label = getBasicLabel(getParam("key"), after);
408 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
410 biblio::CiteEngine const engine = buffer.params().getEngine();
411 if (cache.params == params() && cache.engine == engine)
412 return cache.screen_label;
414 // The label has changed, so we have to re-create it.
415 docstring const glabel = generateLabel(buffer);
417 unsigned int const maxLabelChars = 45;
419 docstring label = glabel;
420 if (label.size() > maxLabelChars) {
421 label.erase(maxLabelChars-3);
425 cache.engine = engine;
426 cache.params = params();
427 cache.generated_label = glabel;
428 cache.screen_label = label;
434 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
435 OutputParams const &) const
439 if (cache.params == params() &&
440 cache.engine == buffer.params().getEngine())
441 str = cache.generated_label;
443 str = generateLabel(buffer);
450 static docstring const cleanupWhitespace(docstring const & citelist)
452 docstring::const_iterator it = citelist.begin();
453 docstring::const_iterator end = citelist.end();
454 // Paranoia check: make sure that there is no whitespace in here
455 // -- at least not behind commas or at the beginning
457 char_type last = ',';
458 for (; it != end; ++it) {
461 if (*it != ' ' || last != ',')
468 int InsetCitation::docbook(Buffer const &, odocstream & os,
469 OutputParams const &) const
471 os << from_ascii("<citation>")
472 << cleanupWhitespace(getParam("key"))
473 << from_ascii("</citation>");
478 int InsetCitation::textString(Buffer const & buf, odocstream & os,
479 OutputParams const & op) const
481 return plaintext(buf, os, op);
485 // Have to overwrite the default InsetCommand method in order to check that
486 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
487 // citations and then changes his mind, turning natbib support off. The output
488 // should revert to \cite[]{}
489 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
490 OutputParams const &) const
492 biblio::CiteEngine cite_engine = buffer.params().getEngine();
494 docstring const cite_str = from_utf8(
495 asValidLatexCommand(getCmdName(), cite_engine));
497 os << "\\" << cite_str;
499 docstring const & before = getParam("before");
500 docstring const & after = getParam("after");
501 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
502 os << '[' << before << "][" << after << ']';
503 else if (!after.empty())
504 os << '[' << after << ']';
506 os << '{' << cleanupWhitespace(getParam("key")) << '}';
512 void InsetCitation::validate(LaTeXFeatures & features) const
514 switch (features.bufferParams().getEngine()) {
515 case biblio::ENGINE_BASIC:
517 case biblio::ENGINE_NATBIB_AUTHORYEAR:
518 case biblio::ENGINE_NATBIB_NUMERICAL:
519 features.require("natbib");
521 case biblio::ENGINE_JURABIB:
522 features.require("jurabib");