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 "insetcite.h"
17 #include "bufferparams.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "LaTeXFeatures.h"
23 #include "frontends/controllers/biblio.h"
25 #include "support/fs_extras.h"
26 #include "support/lstrings.h"
30 #include <boost/filesystem/operations.hpp>
31 #include <boost/filesystem/exception.hpp>
33 using lyx::support::ascii_lowercase;
34 using lyx::support::contains;
35 using lyx::support::getStringFromVector;
36 using lyx::support::getVectorFromString;
37 using lyx::support::ltrim;
38 using lyx::support::rtrim;
39 using lyx::support::split;
40 using lyx::support::tokenPos;
49 namespace biblio = lyx::biblio;
50 namespace fs = boost::filesystem;
55 string const getNatbibLabel(Buffer const & buffer,
56 string const & citeType, string const & keyList,
57 string const & before, string const & after,
58 biblio::CiteEngine engine)
60 // Only start the process off after the buffer is loaded from file.
61 if (!buffer.fully_loaded())
65 typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
66 static CachedMap cached_keys;
68 // and cache the timestamp of the bibliography files.
69 static std::map<string, time_t> bibfileStatus;
71 biblio::InfoMap infomap;
73 vector<string> const & bibfilesCache = buffer.getBibfilesCache();
74 // compare the cached timestamps with the actual ones.
76 for (vector<string>::const_iterator it = bibfilesCache.begin();
77 it != bibfilesCache.end(); ++ it) {
80 std::time_t lastw = fs::last_write_time(f);
81 if (lastw != bibfileStatus[f]) {
83 bibfileStatus[f] = lastw;
86 catch (fs::filesystem_error & fserr) {
88 lyxerr << "Couldn't find or read bibtex file "
90 lyxerr[Debug::DEBUG] << "Fs error: "
91 << fserr.what() << endl;
95 // build the keylist only if the bibfiles have been changed
96 if (cached_keys.empty() || bibfileStatus.empty() || changed) {
97 typedef vector<std::pair<string, string> > InfoType;
99 buffer.fillWithBibKeys(bibkeys);
101 InfoType::const_iterator bit = bibkeys.begin();
102 InfoType::const_iterator bend = bibkeys.end();
104 for (; bit != bend; ++bit)
105 infomap[bit->first] = bit->second;
107 cached_keys[&buffer] = infomap;
109 // use the cached keys
110 infomap = cached_keys[&buffer];
115 // the natbib citation-styles
116 // CITET: author (year)
117 // CITEP: (author,year)
118 // CITEALT: author year
119 // CITEALP: author, year
120 // CITEAUTHOR: author
122 // CITEYEARPAR: (year)
123 // jurabib supports these plus
124 // CITE: author/<before field>
126 // We don't currently use the full or forceUCase fields.
127 string cite_type = biblio::asValidLatexCommand(citeType, engine);
128 if (cite_type[0] == 'C')
129 cite_type = string(1, 'c') + cite_type.substr(1);
130 if (cite_type[cite_type.size() - 1] == '*')
131 cite_type = cite_type.substr(0, cite_type.size() - 1);
134 if (!before.empty()) {
135 // In CITET and CITEALT mode, the "before" string is
136 // attached to the label associated with each and every key.
137 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
138 // to the front of the whole only.
139 // In other modes, it is not used at all.
140 if (cite_type == "citet" ||
141 cite_type == "citealt" ||
142 cite_type == "citep" ||
143 cite_type == "citealp" ||
144 cite_type == "citeyearpar")
145 before_str = before + ' ';
146 // In CITE (jurabib), the "before" string is used to attach
147 // the annotator (of legal texts) to the author(s) of the
149 else if (cite_type == "cite")
150 before_str = '/' + before;
154 if (!after.empty()) {
155 // The "after" key is appended only to the end of the whole.
156 after_str = ", " + after;
159 // One day, these might be tunable (as they are in BibTeX).
160 char const op = '('; // opening parenthesis.
161 char const cp = ')'; // closing parenthesis.
162 // puctuation mark separating citation entries.
163 char const * const sep = ";";
165 string const op_str(' ' + string(1, op));
166 string const cp_str(string(1, cp) + ' ');
167 string const sep_str(string(sep) + ' ');
170 vector<string> keys = getVectorFromString(keyList);
171 vector<string>::const_iterator it = keys.begin();
172 vector<string>::const_iterator end = keys.end();
173 for (; it != end; ++it) {
174 // get the bibdata corresponding to the key
175 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
176 string const year(biblio::getYear(infomap, *it));
178 // Something isn't right. Fail safely.
179 if (author.empty() || year.empty())
182 // authors1/<before>; ... ;
183 // authors_last, <after>
184 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
185 if (it == keys.begin())
186 label += author + before_str + sep_str;
188 label += author + sep_str;
190 // (authors1 (<before> year); ... ;
191 // authors_last (<before> year, <after>)
192 } else if (cite_type == "citet") {
194 case biblio::ENGINE_NATBIB_AUTHORYEAR:
195 label += author + op_str + before_str +
198 case biblio::ENGINE_NATBIB_NUMERICAL:
199 label += author + op_str + before_str +
200 '#' + *it + cp + sep_str;
202 case biblio::ENGINE_JURABIB:
203 label += before_str + author + op_str +
206 case biblio::ENGINE_BASIC:
210 // author, year; author, year; ...
211 } else if (cite_type == "citep" ||
212 cite_type == "citealp") {
213 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
214 label += *it + sep_str;
216 label += author + ", " + year + sep_str;
219 // (authors1 <before> year;
220 // authors_last <before> year, <after>)
221 } else if (cite_type == "citealt") {
223 case biblio::ENGINE_NATBIB_AUTHORYEAR:
224 label += author + ' ' + before_str +
227 case biblio::ENGINE_NATBIB_NUMERICAL:
228 label += author + ' ' + before_str +
231 case biblio::ENGINE_JURABIB:
232 label += before_str + author + ' ' +
235 case biblio::ENGINE_BASIC:
239 // author; author; ...
240 } else if (cite_type == "citeauthor") {
241 label += author + sep_str;
244 } else if (cite_type == "citeyear" ||
245 cite_type == "citeyearpar") {
246 label += year + sep_str;
249 label = rtrim(rtrim(label), sep);
251 if (!after_str.empty()) {
252 if (cite_type == "citet") {
253 // insert "after" before last ')'
254 label.insert(label.size() - 1, after_str);
257 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
258 (cite_type == "citeauthor" ||
259 cite_type == "citeyear"));
265 if (!before_str.empty() && (cite_type == "citep" ||
266 cite_type == "citealp" ||
267 cite_type == "citeyearpar")) {
268 label = before_str + label;
271 if (cite_type == "citep" || cite_type == "citeyearpar")
272 label = string(1, op) + label + string(1, cp);
278 string const getBasicLabel(string const & keyList, string const & after)
280 string keys(keyList);
283 if (contains(keys, ',')) {
284 // Final comma allows while loop to cover all keys
285 keys = ltrim(split(keys, label, ',')) + ',';
286 while (contains(keys, ',')) {
288 keys = ltrim(split(keys, key, ','));
295 label += ", " + after;
297 return '[' + label + ']';
303 InsetCitation::InsetCitation(InsetCommandParams const & p)
304 : InsetCommand(p, "citation")
308 string const InsetCitation::generateLabel(Buffer const & buffer) const
310 string const before = getSecOptions();
311 string const after = getOptions();
314 biblio::CiteEngine const engine = buffer.params().cite_engine;
315 if (engine != biblio::ENGINE_BASIC) {
316 label = getNatbibLabel(buffer, getCmdName(), getContents(),
317 before, after, engine);
320 // Fallback to fail-safe
322 label = getBasicLabel(getContents(), after);
329 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
331 biblio::CiteEngine const engine = biblio::getEngine(buffer);
332 if (cache.params == params() && cache.engine == engine)
333 return cache.screen_label;
335 // The label has changed, so we have to re-create it.
336 string const before = getSecOptions();
337 string const after = getOptions();
339 string const glabel = generateLabel(buffer);
341 unsigned int const maxLabelChars = 45;
343 string label = glabel;
344 if (label.size() > maxLabelChars) {
345 label.erase(maxLabelChars-3);
349 cache.engine = engine;
350 cache.params = params();
351 cache.generated_label = glabel;
352 cache.screen_label = label;
358 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, OutputParams const &) const
360 if (cache.params == params() &&
361 cache.engine == biblio::getEngine(buffer))
362 os << cache.generated_label;
364 os << generateLabel(buffer);
371 string const cleanupWhitespace(string const & citelist)
373 string::const_iterator it = citelist.begin();
374 string::const_iterator end = citelist.end();
375 // Paranoia check: make sure that there is no whitespace in here
376 // -- at least not behind commas or at the beginning
379 for (; it != end; ++it) {
382 if (*it != ' ' || last != ',')
388 // end anon namyspace
391 int InsetCitation::docbook(Buffer const &, ostream & os, OutputParams const &) const
393 os << "<citation>" << cleanupWhitespace(getContents()) << "</citation>";
398 int InsetCitation::textString(Buffer const & buf, ostream & os,
399 OutputParams const & op) const
401 return plaintext(buf, os, op);
405 // Have to overwrite the default InsetCommand method in order to check that
406 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
407 // citations and then changes his mind, turning natbib support off. The output
408 // should revert to \cite[]{}
409 int InsetCitation::latex(Buffer const & buffer, ostream & os,
410 OutputParams const &) const
412 biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
413 string const cite_str =
414 biblio::asValidLatexCommand(getCmdName(), cite_engine);
416 os << "\\" << cite_str;
418 string const before = getSecOptions();
419 string const after = getOptions();
420 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
421 os << '[' << before << "][" << after << ']';
422 else if (!after.empty())
423 os << '[' << after << ']';
425 os << '{' << cleanupWhitespace(getContents()) << '}';
431 void InsetCitation::validate(LaTeXFeatures & features) const
433 switch (features.bufferParams().cite_engine) {
434 case biblio::ENGINE_BASIC:
436 case biblio::ENGINE_NATBIB_AUTHORYEAR:
437 case biblio::ENGINE_NATBIB_NUMERICAL:
438 features.require("natbib");
440 case biblio::ENGINE_JURABIB:
441 features.require("jurabib");
447 void InsetCitation::replaceContents(string const & from, string const & to)
449 if (tokenPos(getContents(), ',', from) != -1) {
450 vector<string> items = getVectorFromString(getContents());
451 replace(items.begin(), items.end(), from, to);
452 setContents(getStringFromVector(items));