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>
36 using support::ascii_lowercase;
37 using support::contains;
38 using support::getStringFromVector;
39 using support::getVectorFromString;
43 using support::tokenPos;
52 namespace fs = boost::filesystem;
57 string const getNatbibLabel(Buffer const & buffer,
58 string const & citeType, string const & keyList,
59 string const & before, string const & after,
60 biblio::CiteEngine engine)
62 // Only start the process off after the buffer is loaded from file.
63 if (!buffer.fully_loaded())
67 typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
68 static CachedMap cached_keys;
70 // and cache the timestamp of the bibliography files.
71 static std::map<string, time_t> bibfileStatus;
73 biblio::InfoMap infomap;
75 vector<string> const & bibfilesCache = buffer.getBibfilesCache();
76 // compare the cached timestamps with the actual ones.
78 for (vector<string>::const_iterator it = bibfilesCache.begin();
79 it != bibfilesCache.end(); ++ it) {
82 std::time_t lastw = fs::last_write_time(f);
83 if (lastw != bibfileStatus[f]) {
85 bibfileStatus[f] = lastw;
88 catch (fs::filesystem_error & fserr) {
90 lyxerr << "Couldn't find or read bibtex file "
92 lyxerr[Debug::DEBUG] << "Fs error: "
93 << fserr.what() << endl;
97 // build the keylist only if the bibfiles have been changed
98 if (cached_keys.empty() || bibfileStatus.empty() || changed) {
99 typedef vector<std::pair<string, string> > InfoType;
101 buffer.fillWithBibKeys(bibkeys);
103 InfoType::const_iterator bit = bibkeys.begin();
104 InfoType::const_iterator bend = bibkeys.end();
106 for (; bit != bend; ++bit)
107 infomap[bit->first] = bit->second;
109 cached_keys[&buffer] = infomap;
111 // use the cached keys
112 infomap = cached_keys[&buffer];
117 // the natbib citation-styles
118 // CITET: author (year)
119 // CITEP: (author,year)
120 // CITEALT: author year
121 // CITEALP: author, year
122 // CITEAUTHOR: author
124 // CITEYEARPAR: (year)
125 // jurabib supports these plus
126 // CITE: author/<before field>
128 // We don't currently use the full or forceUCase fields.
129 string cite_type = biblio::asValidLatexCommand(citeType, engine);
130 if (cite_type[0] == 'C')
131 cite_type = string(1, 'c') + cite_type.substr(1);
132 if (cite_type[cite_type.size() - 1] == '*')
133 cite_type = cite_type.substr(0, cite_type.size() - 1);
136 if (!before.empty()) {
137 // In CITET and CITEALT mode, the "before" string is
138 // attached to the label associated with each and every key.
139 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
140 // to the front of the whole only.
141 // In other modes, it is not used at all.
142 if (cite_type == "citet" ||
143 cite_type == "citealt" ||
144 cite_type == "citep" ||
145 cite_type == "citealp" ||
146 cite_type == "citeyearpar")
147 before_str = before + ' ';
148 // In CITE (jurabib), the "before" string is used to attach
149 // the annotator (of legal texts) to the author(s) of the
151 else if (cite_type == "cite")
152 before_str = '/' + before;
156 if (!after.empty()) {
157 // The "after" key is appended only to the end of the whole.
158 after_str = ", " + after;
161 // One day, these might be tunable (as they are in BibTeX).
162 char const op = '('; // opening parenthesis.
163 char const cp = ')'; // closing parenthesis.
164 // puctuation mark separating citation entries.
165 char const * const sep = ";";
167 string const op_str(' ' + string(1, op));
168 string const cp_str(string(1, cp) + ' ');
169 string const sep_str(string(sep) + ' ');
172 vector<string> keys = getVectorFromString(keyList);
173 vector<string>::const_iterator it = keys.begin();
174 vector<string>::const_iterator end = keys.end();
175 for (; it != end; ++it) {
176 // get the bibdata corresponding to the key
177 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
178 string const year(biblio::getYear(infomap, *it));
180 // Something isn't right. Fail safely.
181 if (author.empty() || year.empty())
184 // authors1/<before>; ... ;
185 // authors_last, <after>
186 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
187 if (it == keys.begin())
188 label += author + before_str + sep_str;
190 label += author + sep_str;
192 // (authors1 (<before> year); ... ;
193 // authors_last (<before> year, <after>)
194 } else if (cite_type == "citet") {
196 case biblio::ENGINE_NATBIB_AUTHORYEAR:
197 label += author + op_str + before_str +
200 case biblio::ENGINE_NATBIB_NUMERICAL:
201 label += author + op_str + before_str +
202 '#' + *it + cp + sep_str;
204 case biblio::ENGINE_JURABIB:
205 label += before_str + author + op_str +
208 case biblio::ENGINE_BASIC:
212 // author, year; author, year; ...
213 } else if (cite_type == "citep" ||
214 cite_type == "citealp") {
215 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
216 label += *it + sep_str;
218 label += author + ", " + year + sep_str;
221 // (authors1 <before> year;
222 // authors_last <before> year, <after>)
223 } else if (cite_type == "citealt") {
225 case biblio::ENGINE_NATBIB_AUTHORYEAR:
226 label += author + ' ' + before_str +
229 case biblio::ENGINE_NATBIB_NUMERICAL:
230 label += author + ' ' + before_str +
233 case biblio::ENGINE_JURABIB:
234 label += before_str + author + ' ' +
237 case biblio::ENGINE_BASIC:
241 // author; author; ...
242 } else if (cite_type == "citeauthor") {
243 label += author + sep_str;
246 } else if (cite_type == "citeyear" ||
247 cite_type == "citeyearpar") {
248 label += year + sep_str;
251 label = rtrim(rtrim(label), sep);
253 if (!after_str.empty()) {
254 if (cite_type == "citet") {
255 // insert "after" before last ')'
256 label.insert(label.size() - 1, after_str);
259 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
260 (cite_type == "citeauthor" ||
261 cite_type == "citeyear"));
267 if (!before_str.empty() && (cite_type == "citep" ||
268 cite_type == "citealp" ||
269 cite_type == "citeyearpar")) {
270 label = before_str + label;
273 if (cite_type == "citep" || cite_type == "citeyearpar")
274 label = string(1, op) + label + string(1, cp);
280 string const getBasicLabel(string const & keyList, string const & after)
282 string keys(keyList);
285 if (contains(keys, ',')) {
286 // Final comma allows while loop to cover all keys
287 keys = ltrim(split(keys, label, ',')) + ',';
288 while (contains(keys, ',')) {
290 keys = ltrim(split(keys, key, ','));
297 label += ", " + after;
299 return '[' + label + ']';
305 InsetCitation::InsetCitation(InsetCommandParams const & p)
306 : InsetCommand(p, "citation")
310 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
312 string const before = getSecOptions();
313 string const after = getOptions();
316 biblio::CiteEngine const engine = buffer.params().cite_engine;
317 if (engine != biblio::ENGINE_BASIC) {
318 label = getNatbibLabel(buffer, getCmdName(), getContents(),
319 before, after, engine);
322 // Fallback to fail-safe
324 label = getBasicLabel(getContents(), after);
328 return from_utf8(label);
332 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
334 biblio::CiteEngine const engine = biblio::getEngine(buffer);
335 if (cache.params == params() && cache.engine == engine)
336 return cache.screen_label;
338 // The label has changed, so we have to re-create it.
339 string const before = getSecOptions();
340 string const after = getOptions();
342 docstring const glabel = generateLabel(buffer);
344 unsigned int const maxLabelChars = 45;
346 docstring label = glabel;
347 if (label.size() > maxLabelChars) {
348 label.erase(maxLabelChars-3);
352 cache.engine = engine;
353 cache.params = params();
354 cache.generated_label = glabel;
355 cache.screen_label = label;
361 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
362 OutputParams const &) const
364 if (cache.params == params() &&
365 cache.engine == biblio::getEngine(buffer))
366 os << cache.generated_label;
368 os << generateLabel(buffer);
375 string const cleanupWhitespace(string const & citelist)
377 string::const_iterator it = citelist.begin();
378 string::const_iterator end = citelist.end();
379 // Paranoia check: make sure that there is no whitespace in here
380 // -- at least not behind commas or at the beginning
383 for (; it != end; ++it) {
386 if (*it != ' ' || last != ',')
392 // end anon namyspace
395 int InsetCitation::docbook(Buffer const &, odocstream & os, OutputParams const &) const
399 << from_ascii(cleanupWhitespace(getContents()))
405 int InsetCitation::textString(Buffer const & buf, odocstream & os,
406 OutputParams const & op) const
408 return plaintext(buf, os, op);
412 // Have to overwrite the default InsetCommand method in order to check that
413 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
414 // citations and then changes his mind, turning natbib support off. The output
415 // should revert to \cite[]{}
416 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
417 OutputParams const &) const
419 biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
421 docstring const cite_str = from_utf8(
422 biblio::asValidLatexCommand(getCmdName(), cite_engine));
424 os << "\\" << cite_str;
426 docstring const & before = getParam("before");
427 docstring const & after = getParam("after");
428 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
429 os << '[' << before << "][" << after << ']';
430 else if (!after.empty())
431 os << '[' << after << ']';
434 os << '{' << from_utf8(cleanupWhitespace(getContents())) << '}';
440 void InsetCitation::validate(LaTeXFeatures & features) const
442 switch (features.bufferParams().cite_engine) {
443 case biblio::ENGINE_BASIC:
445 case biblio::ENGINE_NATBIB_AUTHORYEAR:
446 case biblio::ENGINE_NATBIB_NUMERICAL:
447 features.require("natbib");
449 case biblio::ENGINE_JURABIB:
450 features.require("jurabib");
456 void InsetCitation::replaceContents(string const & from, string const & to)
458 if (tokenPos(getContents(), ',', from) != -1) {
459 vector<string> items = getVectorFromString(getContents());
460 replace(items.begin(), items.end(), from, to);
461 setContents(getStringFromVector(items));