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"
19 #include "DispatchResult.h"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
23 #include "frontends/controllers/frontend_helpers.h"
25 #include "support/fs_extras.h"
26 #include "support/lstrings.h"
30 #include <boost/filesystem/operations.hpp>
31 #include <boost/filesystem/exception.hpp>
36 using support::ascii_lowercase;
37 using support::contains;
38 using support::FileName;
39 using support::getStringFromVector;
40 using support::getVectorFromString;
44 using support::tokenPos;
53 namespace fs = boost::filesystem;
58 docstring const getNatbibLabel(Buffer const & buffer,
59 string const & citeType, string const & keyList,
60 docstring const & before, docstring const & after,
61 biblio::CiteEngine engine)
63 // Only start the process off after the buffer is loaded from file.
64 if (!buffer.fully_loaded())
68 typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
69 static CachedMap cached_keys;
71 // and cache the timestamp of the bibliography files.
72 static std::map<FileName, time_t> bibfileStatus;
74 biblio::InfoMap infomap;
76 vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
77 // compare the cached timestamps with the actual ones.
79 for (vector<FileName>::const_iterator it = bibfilesCache.begin();
80 it != bibfilesCache.end(); ++ it) {
81 FileName const f = *it;
83 std::time_t lastw = fs::last_write_time(f.toFilesystemEncoding());
84 if (lastw != bibfileStatus[f]) {
86 bibfileStatus[f] = lastw;
89 catch (fs::filesystem_error & fserr) {
91 lyxerr << "Couldn't find or read bibtex file "
93 LYXERR(Debug::DEBUG) << "Fs error: "
94 << fserr.what() << endl;
98 // build the keylist only if the bibfiles have been changed
99 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
100 typedef vector<std::pair<string, docstring> > InfoType;
102 buffer.fillWithBibKeys(bibkeys);
104 InfoType::const_iterator bit = bibkeys.begin();
105 InfoType::const_iterator bend = bibkeys.end();
107 for (; bit != bend; ++bit)
108 infomap[bit->first] = bit->second;
110 cached_keys[&buffer] = infomap;
112 // use the cached keys
113 infomap = cached_keys[&buffer];
118 // the natbib citation-styles
119 // CITET: author (year)
120 // CITEP: (author,year)
121 // CITEALT: author year
122 // CITEALP: author, year
123 // CITEAUTHOR: author
125 // CITEYEARPAR: (year)
126 // jurabib supports these plus
127 // CITE: author/<before field>
129 // We don't currently use the full or forceUCase fields.
130 string cite_type = biblio::asValidLatexCommand(citeType, engine);
131 if (cite_type[0] == 'C')
132 cite_type = string(1, 'c') + cite_type.substr(1);
133 if (cite_type[cite_type.size() - 1] == '*')
134 cite_type = cite_type.substr(0, cite_type.size() - 1);
136 docstring before_str;
137 if (!before.empty()) {
138 // In CITET and CITEALT mode, the "before" string is
139 // attached to the label associated with each and every key.
140 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
141 // to the front of the whole only.
142 // In other modes, it is not used at all.
143 if (cite_type == "citet" ||
144 cite_type == "citealt" ||
145 cite_type == "citep" ||
146 cite_type == "citealp" ||
147 cite_type == "citeyearpar")
148 before_str = before + ' ';
149 // In CITE (jurabib), the "before" string is used to attach
150 // the annotator (of legal texts) to the author(s) of the
152 else if (cite_type == "cite")
153 before_str = '/' + before;
157 if (!after.empty()) {
158 // The "after" key is appended only to the end of the whole.
159 after_str = ", " + after;
162 // One day, these might be tunable (as they are in BibTeX).
163 char const op = '('; // opening parenthesis.
164 char const cp = ')'; // closing parenthesis.
165 // puctuation mark separating citation entries.
166 char const * const sep = ";";
168 docstring const op_str(' ' + docstring(1, op));
169 docstring const cp_str(docstring(1, cp) + ' ');
170 docstring const sep_str(from_ascii(sep) + ' ');
173 vector<string> keys = getVectorFromString(keyList);
174 vector<string>::const_iterator it = keys.begin();
175 vector<string>::const_iterator end = keys.end();
176 for (; it != end; ++it) {
177 // get the bibdata corresponding to the key
178 docstring const author(biblio::getAbbreviatedAuthor(infomap, *it));
179 docstring const year(biblio::getYear(infomap, *it));
181 // Something isn't right. Fail safely.
182 if (author.empty() || year.empty())
185 // authors1/<before>; ... ;
186 // authors_last, <after>
187 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
188 if (it == keys.begin())
189 label += author + before_str + sep_str;
191 label += author + sep_str;
193 // (authors1 (<before> year); ... ;
194 // authors_last (<before> year, <after>)
195 } else if (cite_type == "citet") {
197 case biblio::ENGINE_NATBIB_AUTHORYEAR:
198 label += author + op_str + before_str +
201 case biblio::ENGINE_NATBIB_NUMERICAL:
203 label += author + op_str + before_str +
204 '#' + from_utf8(*it) + cp + sep_str;
206 case biblio::ENGINE_JURABIB:
207 label += before_str + author + op_str +
210 case biblio::ENGINE_BASIC:
214 // author, year; author, year; ...
215 } else if (cite_type == "citep" ||
216 cite_type == "citealp") {
217 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
219 label += from_utf8(*it) + sep_str;
221 label += author + ", " + year + sep_str;
224 // (authors1 <before> year;
225 // authors_last <before> year, <after>)
226 } else if (cite_type == "citealt") {
228 case biblio::ENGINE_NATBIB_AUTHORYEAR:
229 label += author + ' ' + before_str +
232 case biblio::ENGINE_NATBIB_NUMERICAL:
234 label += author + ' ' + before_str +
235 '#' + from_utf8(*it) + sep_str;
237 case biblio::ENGINE_JURABIB:
238 label += before_str + author + ' ' +
241 case biblio::ENGINE_BASIC:
245 // author; author; ...
246 } else if (cite_type == "citeauthor") {
247 label += author + sep_str;
250 } else if (cite_type == "citeyear" ||
251 cite_type == "citeyearpar") {
252 label += year + sep_str;
255 label = rtrim(rtrim(label), sep);
257 if (!after_str.empty()) {
258 if (cite_type == "citet") {
259 // insert "after" before last ')'
260 label.insert(label.size() - 1, after_str);
263 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
264 (cite_type == "citeauthor" ||
265 cite_type == "citeyear"));
271 if (!before_str.empty() && (cite_type == "citep" ||
272 cite_type == "citealp" ||
273 cite_type == "citeyearpar")) {
274 label = before_str + label;
277 if (cite_type == "citep" || cite_type == "citeyearpar")
278 label = op + label + cp;
284 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
286 docstring keys(keyList);
289 if (contains(keys, ',')) {
290 // Final comma allows while loop to cover all keys
291 keys = ltrim(split(keys, label, ',')) + ',';
292 while (contains(keys, ',')) {
294 keys = ltrim(split(keys, key, ','));
301 label += ", " + after;
303 return '[' + label + ']';
309 InsetCitation::InsetCitation(InsetCommandParams const & p)
310 : InsetCommand(p, "citation")
314 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
316 docstring const before = getParam("before");
317 docstring const after = getParam("after");
320 biblio::CiteEngine const engine = buffer.params().getEngine();
321 if (engine != biblio::ENGINE_BASIC) {
323 label = getNatbibLabel(buffer, getCmdName(), to_utf8(getParam("key")),
324 before, after, engine);
327 // Fallback to fail-safe
329 label = getBasicLabel(getParam("key"), after);
336 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
338 biblio::CiteEngine const engine = buffer.params().getEngine();
339 if (cache.params == params() && cache.engine == engine)
340 return cache.screen_label;
342 // The label has changed, so we have to re-create it.
343 docstring const glabel = generateLabel(buffer);
345 unsigned int const maxLabelChars = 45;
347 docstring label = glabel;
348 if (label.size() > maxLabelChars) {
349 label.erase(maxLabelChars-3);
353 cache.engine = engine;
354 cache.params = params();
355 cache.generated_label = glabel;
356 cache.screen_label = label;
362 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
363 OutputParams const &) const
367 if (cache.params == params() &&
368 cache.engine == buffer.params().getEngine())
369 str = cache.generated_label;
371 str = generateLabel(buffer);
380 docstring const cleanupWhitespace(docstring const & citelist)
382 docstring::const_iterator it = citelist.begin();
383 docstring::const_iterator end = citelist.end();
384 // Paranoia check: make sure that there is no whitespace in here
385 // -- at least not behind commas or at the beginning
387 char_type last = ',';
388 for (; it != end; ++it) {
391 if (*it != ' ' || last != ',')
397 // end anon namyspace
400 int InsetCitation::docbook(Buffer const &, odocstream & os,
401 OutputParams const &) const
404 << cleanupWhitespace(getParam("key"))
410 int InsetCitation::textString(Buffer const & buf, odocstream & os,
411 OutputParams const & op) const
413 return plaintext(buf, os, op);
417 // Have to overwrite the default InsetCommand method in order to check that
418 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
419 // citations and then changes his mind, turning natbib support off. The output
420 // should revert to \cite[]{}
421 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
422 OutputParams const &) const
424 biblio::CiteEngine cite_engine = buffer.params().getEngine();
426 docstring const cite_str = from_utf8(
427 biblio::asValidLatexCommand(getCmdName(), cite_engine));
429 os << "\\" << cite_str;
431 docstring const & before = getParam("before");
432 docstring const & after = getParam("after");
433 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
434 os << '[' << before << "][" << after << ']';
435 else if (!after.empty())
436 os << '[' << after << ']';
438 os << '{' << cleanupWhitespace(getParam("key")) << '}';
444 void InsetCitation::validate(LaTeXFeatures & features) const
446 switch (features.bufferParams().getEngine()) {
447 case biblio::ENGINE_BASIC:
449 case biblio::ENGINE_NATBIB_AUTHORYEAR:
450 case biblio::ENGINE_NATBIB_NUMERICAL:
451 features.require("natbib");
453 case biblio::ENGINE_JURABIB:
454 features.require("jurabib");
460 void InsetCitation::replaceContents(string const & from, string const & to)
462 if (tokenPos(getContents(), ',', from) != -1) {
463 vector<string> items = getVectorFromString(getContents());
464 replace(items.begin(), items.end(), from, to);
465 setContents(getStringFromVector(items));