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::FileName;
39 using support::getStringFromVector;
40 using support::getVectorFromString;
44 using support::tokenPos;
53 namespace fs = boost::filesystem;
58 string const getNatbibLabel(Buffer const & buffer,
59 string const & citeType, string const & keyList,
60 string const & before, string 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.empty() || bibfileStatus.empty() || changed) {
100 typedef vector<std::pair<string, string> > 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);
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 string const op_str(' ' + string(1, op));
169 string const cp_str(string(1, cp) + ' ');
170 string const sep_str(string(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 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
179 string 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:
202 label += author + op_str + before_str +
203 '#' + *it + cp + sep_str;
205 case biblio::ENGINE_JURABIB:
206 label += before_str + author + op_str +
209 case biblio::ENGINE_BASIC:
213 // author, year; author, year; ...
214 } else if (cite_type == "citep" ||
215 cite_type == "citealp") {
216 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
217 label += *it + sep_str;
219 label += author + ", " + year + sep_str;
222 // (authors1 <before> year;
223 // authors_last <before> year, <after>)
224 } else if (cite_type == "citealt") {
226 case biblio::ENGINE_NATBIB_AUTHORYEAR:
227 label += author + ' ' + before_str +
230 case biblio::ENGINE_NATBIB_NUMERICAL:
231 label += author + ' ' + before_str +
234 case biblio::ENGINE_JURABIB:
235 label += before_str + author + ' ' +
238 case biblio::ENGINE_BASIC:
242 // author; author; ...
243 } else if (cite_type == "citeauthor") {
244 label += author + sep_str;
247 } else if (cite_type == "citeyear" ||
248 cite_type == "citeyearpar") {
249 label += year + sep_str;
252 label = rtrim(rtrim(label), sep);
254 if (!after_str.empty()) {
255 if (cite_type == "citet") {
256 // insert "after" before last ')'
257 label.insert(label.size() - 1, after_str);
260 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
261 (cite_type == "citeauthor" ||
262 cite_type == "citeyear"));
268 if (!before_str.empty() && (cite_type == "citep" ||
269 cite_type == "citealp" ||
270 cite_type == "citeyearpar")) {
271 label = before_str + label;
274 if (cite_type == "citep" || cite_type == "citeyearpar")
275 label = string(1, op) + label + string(1, cp);
281 string const getBasicLabel(string const & keyList, string const & after)
283 string keys(keyList);
286 if (contains(keys, ',')) {
287 // Final comma allows while loop to cover all keys
288 keys = ltrim(split(keys, label, ',')) + ',';
289 while (contains(keys, ',')) {
291 keys = ltrim(split(keys, key, ','));
298 label += ", " + after;
300 return '[' + label + ']';
306 InsetCitation::InsetCitation(InsetCommandParams const & p)
307 : InsetCommand(p, "citation")
311 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
313 string const before = getSecOptions();
314 string const after = getOptions();
317 biblio::CiteEngine const engine = buffer.params().cite_engine;
318 if (engine != biblio::ENGINE_BASIC) {
319 label = getNatbibLabel(buffer, getCmdName(), getContents(),
320 before, after, engine);
323 // Fallback to fail-safe
325 label = getBasicLabel(getContents(), after);
329 return from_utf8(label);
333 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
335 biblio::CiteEngine const engine = biblio::getEngine(buffer);
336 if (cache.params == params() && cache.engine == engine)
337 return cache.screen_label;
339 // The label has changed, so we have to re-create it.
340 string const before = getSecOptions();
341 string const after = getOptions();
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
365 if (cache.params == params() &&
366 cache.engine == biblio::getEngine(buffer))
367 os << cache.generated_label;
369 os << generateLabel(buffer);
376 string const cleanupWhitespace(string const & citelist)
378 string::const_iterator it = citelist.begin();
379 string::const_iterator end = citelist.end();
380 // Paranoia check: make sure that there is no whitespace in here
381 // -- at least not behind commas or at the beginning
384 for (; it != end; ++it) {
387 if (*it != ' ' || last != ',')
393 // end anon namyspace
396 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));