]> git.lyx.org Git - lyx.git/blob - src/insets/insetcite.C
This commit cleans up everything related to singleton. The other important change...
[lyx.git] / src / insets / insetcite.C
1 /**
2  * \file insetcite.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "insetcite.h"
15
16 #include "buffer.h"
17 #include "bufferparams.h"
18 #include "debug.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "LaTeXFeatures.h"
22
23 #include "frontends/controllers/biblio.h"
24
25 #include "support/fs_extras.h"
26 #include "support/lstrings.h"
27
28 #include <algorithm>
29
30 #include <boost/filesystem/operations.hpp>
31 #include <boost/filesystem/exception.hpp>
32
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;
41
42 using std::endl;
43 using std::replace;
44 using std::string;
45 using std::ostream;
46 using std::vector;
47 using std::map;
48
49 namespace biblio = lyx::biblio;
50 namespace fs = boost::filesystem;
51
52
53 namespace {
54
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)
59 {
60         // Only start the process off after the buffer is loaded from file.
61         if (!buffer.fully_loaded())
62                 return string();
63
64         // Cache the labels
65         typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
66         static CachedMap cached_keys;
67
68         // and cache the timestamp of the bibliography files.
69         static std::map<string, time_t> bibfileStatus;
70
71         biblio::InfoMap infomap;
72
73         vector<string> const & bibfilesCache = buffer.getBibfilesCache();
74         // compare the cached timestamps with the actual ones.
75         bool changed = false;
76         for (vector<string>::const_iterator it = bibfilesCache.begin();
77                         it != bibfilesCache.end(); ++ it) {
78                 string const f = *it;
79                 try {
80                         std::time_t lastw = fs::last_write_time(f);
81                         if (lastw != bibfileStatus[f]) {
82                                 changed = true;
83                                 bibfileStatus[f] = lastw;
84                         }
85                 }
86                 catch (fs::filesystem_error & fserr) {
87                         changed = true;
88                         lyxerr << "Couldn't find or read bibtex file "
89                                << f << endl;
90                         lyxerr[Debug::DEBUG] << "Fs error: "
91                                              << fserr.what() << endl;
92                 }
93         }
94
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;
98                 InfoType bibkeys;
99                 buffer.fillWithBibKeys(bibkeys);
100
101                 InfoType::const_iterator bit  = bibkeys.begin();
102                 InfoType::const_iterator bend = bibkeys.end();
103
104                 for (; bit != bend; ++bit)
105                         infomap[bit->first] = bit->second;
106
107                 cached_keys[&buffer] = infomap;
108         } else
109                 // use the cached keys
110                 infomap = cached_keys[&buffer];
111
112         if (infomap.empty())
113                 return string();
114
115         // the natbib citation-styles
116         // CITET:       author (year)
117         // CITEP:       (author,year)
118         // CITEALT:     author year
119         // CITEALP:     author, year
120         // CITEAUTHOR:  author
121         // CITEYEAR:    year
122         // CITEYEARPAR: (year)
123         // jurabib supports these plus
124         // CITE:        author/<before field>
125
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);
132
133         string before_str;
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
148                 // first reference.
149                 else if (cite_type == "cite")
150                         before_str = '/' + before;
151         }
152
153         string after_str;
154         if (!after.empty()) {
155                 // The "after" key is appended only to the end of the whole.
156                 after_str = ", " + after;
157         }
158
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 = ";";
164
165         string const op_str(' ' + string(1, op));
166         string const cp_str(string(1, cp) + ' ');
167         string const sep_str(string(sep) + ' ');
168
169         string label;
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));
177
178                 // Something isn't right. Fail safely.
179                 if (author.empty() || year.empty())
180                         return string();
181
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;
187                         else
188                                 label += author + sep_str;
189
190                 // (authors1 (<before> year);  ... ;
191                 //  authors_last (<before> year, <after>)
192                 } else if (cite_type == "citet") {
193                         switch (engine) {
194                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
195                                 label += author + op_str + before_str +
196                                         year + cp + sep_str;
197                                 break;
198                         case biblio::ENGINE_NATBIB_NUMERICAL:
199                                 label += author + op_str + before_str +
200                                         '#' + *it + cp + sep_str;
201                                 break;
202                         case biblio::ENGINE_JURABIB:
203                                 label += before_str + author + op_str +
204                                         year + cp + sep_str;
205                                 break;
206                         case biblio::ENGINE_BASIC:
207                                 break;
208                         }
209
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;
215                         } else {
216                                 label += author + ", " + year + sep_str;
217                         }
218
219                 // (authors1 <before> year;
220                 //  authors_last <before> year, <after>)
221                 } else if (cite_type == "citealt") {
222                         switch (engine) {
223                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
224                                 label += author + ' ' + before_str +
225                                         year + sep_str;
226                                 break;
227                         case biblio::ENGINE_NATBIB_NUMERICAL:
228                                 label += author + ' ' + before_str +
229                                         '#' + *it + sep_str;
230                                 break;
231                         case biblio::ENGINE_JURABIB:
232                                 label += before_str + author + ' ' +
233                                         year + sep_str;
234                                 break;
235                         case biblio::ENGINE_BASIC:
236                                 break;
237                         }
238
239                 // author; author; ...
240                 } else if (cite_type == "citeauthor") {
241                         label += author + sep_str;
242
243                 // year; year; ...
244                 } else if (cite_type == "citeyear" ||
245                            cite_type == "citeyearpar") {
246                         label += year + sep_str;
247                 }
248         }
249         label = rtrim(rtrim(label), sep);
250
251         if (!after_str.empty()) {
252                 if (cite_type == "citet") {
253                         // insert "after" before last ')'
254                         label.insert(label.size() - 1, after_str);
255                 } else {
256                         bool const add =
257                                 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
258                                   (cite_type == "citeauthor" ||
259                                    cite_type == "citeyear"));
260                         if (add)
261                                 label += after_str;
262                 }
263         }
264
265         if (!before_str.empty() && (cite_type == "citep" ||
266                                     cite_type == "citealp" ||
267                                     cite_type == "citeyearpar")) {
268                 label = before_str + label;
269         }
270
271         if (cite_type == "citep" || cite_type == "citeyearpar")
272                 label = string(1, op) + label + string(1, cp);
273
274         return label;
275 }
276
277
278 string const getBasicLabel(string const & keyList, string const & after)
279 {
280         string keys(keyList);
281         string label;
282
283         if (contains(keys, ',')) {
284                 // Final comma allows while loop to cover all keys
285                 keys = ltrim(split(keys, label, ',')) + ',';
286                 while (contains(keys, ',')) {
287                         string key;
288                         keys = ltrim(split(keys, key, ','));
289                         label += ", " + key;
290                 }
291         } else
292                 label = keys;
293
294         if (!after.empty())
295                 label += ", " + after;
296
297         return '[' + label + ']';
298 }
299
300 } // anon namespace
301
302
303 InsetCitation::InsetCitation(InsetCommandParams const & p)
304         : InsetCommand(p, "citation")
305 {}
306
307
308 string const InsetCitation::generateLabel(Buffer const & buffer) const
309 {
310         string const before = getSecOptions();
311         string const after  = getOptions();
312
313         string label;
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);
318         }
319
320         // Fallback to fail-safe
321         if (label.empty()) {
322                 label = getBasicLabel(getContents(), after);
323         }
324
325         return label;
326 }
327
328
329 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
330 {
331         biblio::CiteEngine const engine = biblio::getEngine(buffer);
332         if (cache.params == params() && cache.engine == engine)
333                 return cache.screen_label;
334
335         // The label has changed, so we have to re-create it.
336         string const before = getSecOptions();
337         string const after  = getOptions();
338
339         string const glabel = generateLabel(buffer);
340
341         unsigned int const maxLabelChars = 45;
342
343         string label = glabel;
344         if (label.size() > maxLabelChars) {
345                 label.erase(maxLabelChars-3);
346                 label += "...";
347         }
348
349         cache.engine  = engine;
350         cache.params = params();
351         cache.generated_label = glabel;
352         cache.screen_label = label;
353
354         return label;
355 }
356
357
358 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, OutputParams const &) const
359 {
360         if (cache.params == params() &&
361             cache.engine == biblio::getEngine(buffer))
362                 os << cache.generated_label;
363         else
364                 os << generateLabel(buffer);
365         return 0;
366 }
367
368
369 namespace {
370
371 string const cleanupWhitespace(string const & citelist)
372 {
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
377         string result;
378         char last = ',';
379         for (; it != end; ++it) {
380                 if (*it != ' ')
381                         last = *it;
382                 if (*it != ' ' || last != ',')
383                         result += *it;
384         }
385         return result;
386 }
387
388 // end anon namyspace
389 }
390
391 int InsetCitation::docbook(Buffer const &, ostream & os, OutputParams const &) const
392 {
393         os << "<citation>" << cleanupWhitespace(getContents()) << "</citation>";
394         return 0;
395 }
396
397
398 int InsetCitation::textString(Buffer const & buf, ostream & os,
399                        OutputParams const & op) const
400 {
401         return plaintext(buf, os, op);
402 }
403
404
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
411 {
412         biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
413         string const cite_str =
414                 biblio::asValidLatexCommand(getCmdName(), cite_engine);
415
416         os << "\\" << cite_str;
417
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 << ']';
424
425         os << '{' << cleanupWhitespace(getContents()) << '}';
426
427         return 0;
428 }
429
430
431 void InsetCitation::validate(LaTeXFeatures & features) const
432 {
433         switch (features.bufferParams().cite_engine) {
434         case biblio::ENGINE_BASIC:
435                 break;
436         case biblio::ENGINE_NATBIB_AUTHORYEAR:
437         case biblio::ENGINE_NATBIB_NUMERICAL:
438                 features.require("natbib");
439                 break;
440         case biblio::ENGINE_JURABIB:
441                 features.require("jurabib");
442                 break;
443         }
444 }
445
446
447 void InsetCitation::replaceContents(string const & from, string const & to)
448 {
449         if (tokenPos(getContents(), ',', from) != -1) {
450                 vector<string> items = getVectorFromString(getContents());
451                 replace(items.begin(), items.end(), from, to);
452                 setContents(getStringFromVector(items));
453         }
454 }