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/fs_extras.h"
27 #include "support/lstrings.h"
29 #include <boost/filesystem/operations.hpp>
31 using lyx::support::ascii_lowercase;
32 using lyx::support::contains;
33 using lyx::support::getVectorFromString;
34 using lyx::support::ltrim;
35 using lyx::support::rtrim;
36 using lyx::support::split;
44 namespace biblio = lyx::biblio;
45 namespace fs = boost::filesystem;
50 string const getNatbibLabel(Buffer const & buffer,
51 string const & citeType, string const & keyList,
52 string const & before, string const & after,
53 biblio::CiteEngine engine)
55 // Only start the process off after the buffer is loaded from file.
56 if (!buffer.fully_loaded())
60 typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
61 static CachedMap cached_keys;
63 // and cache the timestamp of the bibliography files.
64 static std::map<string, time_t> bibfileStatus;
66 biblio::InfoMap infomap;
68 vector<string> const & bibfilesCache = buffer.getBibfilesCache();
69 // compare the cached timestamps with the actual ones.
71 for (vector<string>::const_iterator it = bibfilesCache.begin();
72 it != bibfilesCache.end(); ++ it) {
74 if (!fs::exists(f) || !fs::is_readable(fs::path(f).branch_path())) {
75 lyxerr << "Couldn't find or read bibtex file " << f << endl;
77 } else if (bibfileStatus[f] != fs::last_write_time(f)) {
79 bibfileStatus[f] = fs::last_write_time(f);
83 // build the keylist only if the bibfiles have been changed
84 if (cached_keys.empty() || bibfileStatus.empty() || changed) {
85 typedef vector<std::pair<string, string> > InfoType;
87 buffer.fillWithBibKeys(bibkeys);
89 InfoType::const_iterator bit = bibkeys.begin();
90 InfoType::const_iterator bend = bibkeys.end();
92 for (; bit != bend; ++bit)
93 infomap[bit->first] = bit->second;
95 cached_keys[&buffer] = infomap;
97 // use the cached keys
98 infomap = cached_keys[&buffer];
103 // the natbib citation-styles
104 // CITET: author (year)
105 // CITEP: (author,year)
106 // CITEALT: author year
107 // CITEALP: author, year
108 // CITEAUTHOR: author
110 // CITEYEARPAR: (year)
111 // jurabib supports these plus
112 // CITE: author/<before field>
114 // We don't currently use the full or forceUCase fields.
115 string cite_type = biblio::asValidLatexCommand(citeType, engine);
116 if (cite_type[0] == 'C')
117 cite_type = string(1, 'c') + cite_type.substr(1);
118 if (cite_type[cite_type.size() - 1] == '*')
119 cite_type = cite_type.substr(0, cite_type.size() - 1);
122 if (!before.empty()) {
123 // In CITET and CITEALT mode, the "before" string is
124 // attached to the label associated with each and every key.
125 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
126 // to the front of the whole only.
127 // In other modes, it is not used at all.
128 if (cite_type == "citet" ||
129 cite_type == "citealt" ||
130 cite_type == "citep" ||
131 cite_type == "citealp" ||
132 cite_type == "citeyearpar")
133 before_str = before + ' ';
134 // In CITE (jurabib), the "before" string is used to attach
135 // the annotator (of legal texts) to the author(s) of the
137 else if (cite_type == "cite")
138 before_str = '/' + before;
142 if (!after.empty()) {
143 // The "after" key is appended only to the end of the whole.
144 after_str = ", " + after;
147 // One day, these might be tunable (as they are in BibTeX).
148 char const op = '('; // opening parenthesis.
149 char const cp = ')'; // closing parenthesis.
150 // puctuation mark separating citation entries.
151 char const * const sep = ";";
153 string const op_str(' ' + string(1, op));
154 string const cp_str(string(1, cp) + ' ');
155 string const sep_str(string(sep) + ' ');
158 vector<string> keys = getVectorFromString(keyList);
159 vector<string>::const_iterator it = keys.begin();
160 vector<string>::const_iterator end = keys.end();
161 for (; it != end; ++it) {
162 // get the bibdata corresponding to the key
163 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
164 string const year(biblio::getYear(infomap, *it));
166 // Something isn't right. Fail safely.
167 if (author.empty() || year.empty())
170 // authors1/<before>; ... ;
171 // authors_last, <after>
172 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
173 if (it == keys.begin())
174 label += author + before_str + sep_str;
176 label += author + sep_str;
178 // (authors1 (<before> year); ... ;
179 // authors_last (<before> year, <after>)
180 } else if (cite_type == "citet") {
182 case biblio::ENGINE_NATBIB_AUTHORYEAR:
183 label += author + op_str + before_str +
186 case biblio::ENGINE_NATBIB_NUMERICAL:
187 label += author + op_str + before_str +
188 '#' + *it + cp + sep_str;
190 case biblio::ENGINE_JURABIB:
191 label += before_str + author + op_str +
194 case biblio::ENGINE_BASIC:
198 // author, year; author, year; ...
199 } else if (cite_type == "citep" ||
200 cite_type == "citealp") {
201 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
202 label += *it + sep_str;
204 label += author + ", " + year + sep_str;
207 // (authors1 <before> year;
208 // authors_last <before> year, <after>)
209 } else if (cite_type == "citealt") {
211 case biblio::ENGINE_NATBIB_AUTHORYEAR:
212 label += author + ' ' + before_str +
215 case biblio::ENGINE_NATBIB_NUMERICAL:
216 label += author + ' ' + before_str +
219 case biblio::ENGINE_JURABIB:
220 label += before_str + author + ' ' +
223 case biblio::ENGINE_BASIC:
227 // author; author; ...
228 } else if (cite_type == "citeauthor") {
229 label += author + sep_str;
232 } else if (cite_type == "citeyear" ||
233 cite_type == "citeyearpar") {
234 label += year + sep_str;
237 label = rtrim(rtrim(label), sep);
239 if (!after_str.empty()) {
240 if (cite_type == "citet") {
241 // insert "after" before last ')'
242 label.insert(label.size() - 1, after_str);
245 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
246 (cite_type == "citeauthor" ||
247 cite_type == "citeyear"));
253 if (!before_str.empty() && (cite_type == "citep" ||
254 cite_type == "citealp" ||
255 cite_type == "citeyearpar")) {
256 label = before_str + label;
259 if (cite_type == "citep" || cite_type == "citeyearpar")
260 label = string(1, op) + label + string(1, cp);
266 string const getBasicLabel(string const & keyList, string const & after)
268 string keys(keyList);
271 if (contains(keys, ',')) {
272 // Final comma allows while loop to cover all keys
273 keys = ltrim(split(keys, label, ',')) + ',';
274 while (contains(keys, ',')) {
276 keys = ltrim(split(keys, key, ','));
283 label += ", " + after;
285 return '[' + label + ']';
291 InsetCitation::InsetCitation(InsetCommandParams const & p)
292 : InsetCommand(p, "citation")
296 string const InsetCitation::generateLabel(Buffer const & buffer) const
298 string const before = getSecOptions();
299 string const after = getOptions();
302 biblio::CiteEngine const engine = buffer.params().cite_engine;
303 if (engine != biblio::ENGINE_BASIC) {
304 label = getNatbibLabel(buffer, getCmdName(), getContents(),
305 before, after, engine);
308 // Fallback to fail-safe
310 label = getBasicLabel(getContents(), after);
317 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
319 biblio::CiteEngine const engine = biblio::getEngine(buffer);
320 if (cache.params == params() && cache.engine == engine)
321 return cache.screen_label;
323 // The label has changed, so we have to re-create it.
324 string const before = getSecOptions();
325 string const after = getOptions();
327 string const glabel = generateLabel(buffer);
329 unsigned int const maxLabelChars = 45;
331 string label = glabel;
332 if (label.size() > maxLabelChars) {
333 label.erase(maxLabelChars-3);
337 cache.engine = engine;
338 cache.params = params();
339 cache.generated_label = glabel;
340 cache.screen_label = label;
346 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, OutputParams const &) const
348 if (cache.params == params() &&
349 cache.engine == biblio::getEngine(buffer))
350 os << cache.generated_label;
352 os << generateLabel(buffer);
359 string const cleanupWhitespace(string const & citelist)
361 string::const_iterator it = citelist.begin();
362 string::const_iterator end = citelist.end();
363 // Paranoia check: make sure that there is no whitespace in here
364 // -- at least not behind commas or at the beginning
367 for (; it != end; ++it) {
370 if (*it != ' ' || last != ',')
376 // end anon namyspace
379 int InsetCitation::docbook(Buffer const &, ostream & os, OutputParams const &) const
381 os << "<citation>" << cleanupWhitespace(getContents()) << "</citation>";
386 int InsetCitation::textString(Buffer const & buf, ostream & os,
387 OutputParams const & op) const
389 return plaintext(buf, os, op);
393 // Have to overwrite the default InsetCommand method in order to check that
394 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
395 // citations and then changes his mind, turning natbib support off. The output
396 // should revert to \cite[]{}
397 int InsetCitation::latex(Buffer const & buffer, ostream & os,
398 OutputParams const &) const
400 biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
401 string const cite_str =
402 biblio::asValidLatexCommand(getCmdName(), cite_engine);
404 os << "\\" << cite_str;
406 string const before = getSecOptions();
407 string const after = getOptions();
408 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
409 os << '[' << before << "][" << after << ']';
410 else if (!after.empty())
411 os << '[' << after << ']';
413 os << '{' << cleanupWhitespace(getContents()) << '}';
419 void InsetCitation::validate(LaTeXFeatures & features) const
421 switch (features.bufferParams().cite_engine) {
422 case biblio::ENGINE_BASIC:
424 case biblio::ENGINE_NATBIB_AUTHORYEAR:
425 case biblio::ENGINE_NATBIB_NUMERICAL:
426 features.require("natbib");
428 case biblio::ENGINE_JURABIB:
429 features.require("jurabib");