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"
18 #include "BufferView.h"
20 #include "dispatchresult.h"
21 #include "funcrequest.h"
22 #include "LaTeXFeatures.h"
24 #include "frontends/controllers/biblio.h"
26 #include "support/lstrings.h"
28 #include <boost/filesystem/operations.hpp>
30 using lyx::support::ascii_lowercase;
31 using lyx::support::contains;
32 using lyx::support::getVectorFromString;
33 using lyx::support::ltrim;
34 using lyx::support::rtrim;
35 using lyx::support::split;
43 namespace biblio = lyx::biblio;
44 namespace fs = boost::filesystem;
49 string const getNatbibLabel(Buffer const & buffer,
50 string const & citeType, string const & keyList,
51 string const & before, string const & after,
52 biblio::CiteEngine engine)
54 // Only start the process off after the buffer is loaded from file.
55 if (!buffer.fully_loaded())
59 typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
60 static CachedMap cached_keys;
62 // and cache the timestamp of the bibliography files.
63 static std::map<string, time_t> bibfileStatus;
65 biblio::InfoMap infomap;
67 vector<string> const & bibfilesCache = buffer.getBibfilesCache();
68 // compare the cached timestamps with the actual ones.
70 for (vector<string>::const_iterator it = bibfilesCache.begin();
71 it != bibfilesCache.end(); ++ it) {
74 lyxerr << "Couldn't find bibtex file " << f << endl;
76 } else if (bibfileStatus[f] != fs::last_write_time(f)) {
78 bibfileStatus[f] = fs::last_write_time(f);
82 // build the keylist only if the bibfiles have been changed
83 if (cached_keys.empty() || bibfileStatus.empty() || changed) {
84 typedef vector<std::pair<string, string> > InfoType;
86 buffer.fillWithBibKeys(bibkeys);
88 InfoType::const_iterator bit = bibkeys.begin();
89 InfoType::const_iterator bend = bibkeys.end();
91 for (; bit != bend; ++bit)
92 infomap[bit->first] = bit->second;
94 cached_keys[&buffer] = infomap;
96 // use the cached keys
97 infomap = cached_keys[&buffer];
102 // the natbib citation-styles
103 // CITET: author (year)
104 // CITEP: (author,year)
105 // CITEALT: author year
106 // CITEALP: author, year
107 // CITEAUTHOR: author
109 // CITEYEARPAR: (year)
110 // jurabib supports these plus
111 // CITE: author/<before field>
113 // We don't currently use the full or forceUCase fields.
114 string cite_type = biblio::asValidLatexCommand(citeType, engine);
115 if (cite_type[0] == 'C')
116 cite_type = string(1, 'c') + cite_type.substr(1);
117 if (cite_type[cite_type.size() - 1] == '*')
118 cite_type = cite_type.substr(0, cite_type.size() - 1);
121 if (!before.empty()) {
122 // In CITET and CITEALT mode, the "before" string is
123 // attached to the label associated with each and every key.
124 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
125 // to the front of the whole only.
126 // In other modes, it is not used at all.
127 if (cite_type == "citet" ||
128 cite_type == "citealt" ||
129 cite_type == "citep" ||
130 cite_type == "citealp" ||
131 cite_type == "citeyearpar")
132 before_str = before + ' ';
133 // In CITE (jurabib), the "before" string is used to attach
134 // the annotator (of legal texts) to the author(s) of the
136 else if (cite_type == "cite")
137 before_str = '/' + before;
141 if (!after.empty()) {
142 // The "after" key is appended only to the end of the whole.
143 after_str = ", " + after;
146 // One day, these might be tunable (as they are in BibTeX).
147 char const op = '('; // opening parenthesis.
148 char const cp = ')'; // closing parenthesis.
149 // puctuation mark separating citation entries.
150 char const * const sep = ";";
152 string const op_str(' ' + string(1, op));
153 string const cp_str(string(1, cp) + ' ');
154 string const sep_str(string(sep) + ' ');
157 vector<string> keys = getVectorFromString(keyList);
158 vector<string>::const_iterator it = keys.begin();
159 vector<string>::const_iterator end = keys.end();
160 for (; it != end; ++it) {
161 // get the bibdata corresponding to the key
162 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
163 string const year(biblio::getYear(infomap, *it));
165 // Something isn't right. Fail safely.
166 if (author.empty() || year.empty())
169 // authors1/<before>; ... ;
170 // authors_last, <after>
171 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
172 if (it == keys.begin())
173 label += author + before_str + sep_str;
175 label += author + sep_str;
177 // (authors1 (<before> year); ... ;
178 // authors_last (<before> year, <after>)
179 } else if (cite_type == "citet") {
181 case biblio::ENGINE_NATBIB_AUTHORYEAR:
182 label += author + op_str + before_str +
185 case biblio::ENGINE_NATBIB_NUMERICAL:
186 label += author + op_str + before_str +
187 '#' + *it + cp + sep_str;
189 case biblio::ENGINE_JURABIB:
190 label += before_str + author + op_str +
193 case biblio::ENGINE_BASIC:
197 // author, year; author, year; ...
198 } else if (cite_type == "citep" ||
199 cite_type == "citealp") {
200 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
201 label += *it + sep_str;
203 label += author + ", " + year + sep_str;
206 // (authors1 <before> year;
207 // authors_last <before> year, <after>)
208 } else if (cite_type == "citealt") {
210 case biblio::ENGINE_NATBIB_AUTHORYEAR:
211 label += author + ' ' + before_str +
214 case biblio::ENGINE_NATBIB_NUMERICAL:
215 label += author + ' ' + before_str +
218 case biblio::ENGINE_JURABIB:
219 label += before_str + author + ' ' +
222 case biblio::ENGINE_BASIC:
226 // author; author; ...
227 } else if (cite_type == "citeauthor") {
228 label += author + sep_str;
231 } else if (cite_type == "citeyear" ||
232 cite_type == "citeyearpar") {
233 label += year + sep_str;
236 label = rtrim(rtrim(label), sep);
238 if (!after_str.empty()) {
239 if (cite_type == "citet") {
240 // insert "after" before last ')'
241 label.insert(label.size() - 1, after_str);
244 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
245 (cite_type == "citeauthor" ||
246 cite_type == "citeyear"));
252 if (!before_str.empty() && (cite_type == "citep" ||
253 cite_type == "citealp" ||
254 cite_type == "citeyearpar")) {
255 label = before_str + label;
258 if (cite_type == "citep" || cite_type == "citeyearpar")
259 label = string(1, op) + label + string(1, cp);
265 string const getBasicLabel(string const & keyList, string const & after)
267 string keys(keyList);
270 if (contains(keys, ',')) {
271 // Final comma allows while loop to cover all keys
272 keys = ltrim(split(keys, label, ',')) + ',';
273 while (contains(keys, ',')) {
275 keys = ltrim(split(keys, key, ','));
282 label += ", " + after;
284 return '[' + label + ']';
290 InsetCitation::InsetCitation(InsetCommandParams const & p)
291 : InsetCommand(p, "citation")
295 string const InsetCitation::generateLabel(Buffer const & buffer) const
297 string const before = getSecOptions();
298 string const after = getOptions();
301 biblio::CiteEngine const engine = buffer.params().cite_engine;
302 if (engine != biblio::ENGINE_BASIC) {
303 label = getNatbibLabel(buffer, getCmdName(), getContents(),
304 before, after, engine);
307 // Fallback to fail-safe
309 label = getBasicLabel(getContents(), after);
316 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
318 biblio::CiteEngine const engine = biblio::getEngine(buffer);
319 if (cache.params == params() && cache.engine == engine)
320 return cache.screen_label;
322 // The label has changed, so we have to re-create it.
323 string const before = getSecOptions();
324 string const after = getOptions();
326 string const glabel = generateLabel(buffer);
328 unsigned int const maxLabelChars = 45;
330 string label = glabel;
331 if (label.size() > maxLabelChars) {
332 label.erase(maxLabelChars-3);
336 cache.engine = engine;
337 cache.params = params();
338 cache.generated_label = glabel;
339 cache.screen_label = label;
345 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, OutputParams const &) const
347 if (cache.params == params() &&
348 cache.engine == biblio::getEngine(buffer))
349 os << cache.generated_label;
351 os << generateLabel(buffer);
358 string const cleanupWhitespace(string const & citelist)
360 string::const_iterator it = citelist.begin();
361 string::const_iterator end = citelist.end();
362 // Paranoia check: make sure that there is no whitespace in here
363 // -- at least not behind commas or at the beginning
366 for (; it != end; ++it) {
369 if (*it != ' ' || last != ',')
375 // end anon namyspace
378 int InsetCitation::docbook(Buffer const &, ostream & os, OutputParams const &) const
380 os << "<citation>" << cleanupWhitespace(getContents()) << "</citation>";
385 int InsetCitation::textString(Buffer const & buf, ostream & os,
386 OutputParams const & op) const
388 return plaintext(buf, os, op);
392 // Have to overwrite the default InsetCommand method in order to check that
393 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
394 // citations and then changes his mind, turning natbib support off. The output
395 // should revert to \cite[]{}
396 int InsetCitation::latex(Buffer const & buffer, ostream & os,
397 OutputParams const &) const
399 biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
400 string const cite_str =
401 biblio::asValidLatexCommand(getCmdName(), cite_engine);
403 os << "\\" << cite_str;
405 string const before = getSecOptions();
406 string const after = getOptions();
407 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
408 os << '[' << before << "][" << after << ']';
409 else if (!after.empty())
410 os << '[' << after << ']';
412 os << '{' << cleanupWhitespace(getContents()) << '}';
418 void InsetCitation::validate(LaTeXFeatures & features) const
420 switch (features.bufferParams().cite_engine) {
421 case biblio::ENGINE_BASIC:
423 case biblio::ENGINE_NATBIB_AUTHORYEAR:
424 case biblio::ENGINE_NATBIB_NUMERICAL:
425 features.require("natbib");
427 case biblio::ENGINE_JURABIB:
428 features.require("jurabib");