]> git.lyx.org Git - lyx.git/blob - src/insets/insetcite.C
more unicode filenames
[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
34 namespace lyx {
35
36 using support::ascii_lowercase;
37 using support::contains;
38 using support::FileName;
39 using support::getStringFromVector;
40 using support::getVectorFromString;
41 using support::ltrim;
42 using support::rtrim;
43 using support::split;
44 using support::tokenPos;
45
46 using std::endl;
47 using std::replace;
48 using std::string;
49 using std::ostream;
50 using std::vector;
51 using std::map;
52
53 namespace fs = boost::filesystem;
54
55
56 namespace {
57
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)
62 {
63         // Only start the process off after the buffer is loaded from file.
64         if (!buffer.fully_loaded())
65                 return string();
66
67         // Cache the labels
68         typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
69         static CachedMap cached_keys;
70
71         // and cache the timestamp of the bibliography files.
72         static std::map<FileName, time_t> bibfileStatus;
73
74         biblio::InfoMap infomap;
75
76         vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
77         // compare the cached timestamps with the actual ones.
78         bool changed = false;
79         for (vector<FileName>::const_iterator it = bibfilesCache.begin();
80                         it != bibfilesCache.end(); ++ it) {
81                 FileName const f = *it;
82                 try {
83                         std::time_t lastw = fs::last_write_time(f.toFilesystemEncoding());
84                         if (lastw != bibfileStatus[f]) {
85                                 changed = true;
86                                 bibfileStatus[f] = lastw;
87                         }
88                 }
89                 catch (fs::filesystem_error & fserr) {
90                         changed = true;
91                         lyxerr << "Couldn't find or read bibtex file "
92                                << f << endl;
93                         lyxerr[Debug::DEBUG] << "Fs error: "
94                                              << fserr.what() << endl;
95                 }
96         }
97
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;
101                 InfoType bibkeys;
102                 buffer.fillWithBibKeys(bibkeys);
103
104                 InfoType::const_iterator bit  = bibkeys.begin();
105                 InfoType::const_iterator bend = bibkeys.end();
106
107                 for (; bit != bend; ++bit)
108                         infomap[bit->first] = bit->second;
109
110                 cached_keys[&buffer] = infomap;
111         } else
112                 // use the cached keys
113                 infomap = cached_keys[&buffer];
114
115         if (infomap.empty())
116                 return string();
117
118         // the natbib citation-styles
119         // CITET:       author (year)
120         // CITEP:       (author,year)
121         // CITEALT:     author year
122         // CITEALP:     author, year
123         // CITEAUTHOR:  author
124         // CITEYEAR:    year
125         // CITEYEARPAR: (year)
126         // jurabib supports these plus
127         // CITE:        author/<before field>
128
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);
135
136         string before_str;
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
151                 // first reference.
152                 else if (cite_type == "cite")
153                         before_str = '/' + before;
154         }
155
156         string after_str;
157         if (!after.empty()) {
158                 // The "after" key is appended only to the end of the whole.
159                 after_str = ", " + after;
160         }
161
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 = ";";
167
168         string const op_str(' ' + string(1, op));
169         string const cp_str(string(1, cp) + ' ');
170         string const sep_str(string(sep) + ' ');
171
172         string label;
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));
180
181                 // Something isn't right. Fail safely.
182                 if (author.empty() || year.empty())
183                         return string();
184
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;
190                         else
191                                 label += author + sep_str;
192
193                 // (authors1 (<before> year);  ... ;
194                 //  authors_last (<before> year, <after>)
195                 } else if (cite_type == "citet") {
196                         switch (engine) {
197                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
198                                 label += author + op_str + before_str +
199                                         year + cp + sep_str;
200                                 break;
201                         case biblio::ENGINE_NATBIB_NUMERICAL:
202                                 label += author + op_str + before_str +
203                                         '#' + *it + cp + sep_str;
204                                 break;
205                         case biblio::ENGINE_JURABIB:
206                                 label += before_str + author + op_str +
207                                         year + cp + sep_str;
208                                 break;
209                         case biblio::ENGINE_BASIC:
210                                 break;
211                         }
212
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;
218                         } else {
219                                 label += author + ", " + year + sep_str;
220                         }
221
222                 // (authors1 <before> year;
223                 //  authors_last <before> year, <after>)
224                 } else if (cite_type == "citealt") {
225                         switch (engine) {
226                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
227                                 label += author + ' ' + before_str +
228                                         year + sep_str;
229                                 break;
230                         case biblio::ENGINE_NATBIB_NUMERICAL:
231                                 label += author + ' ' + before_str +
232                                         '#' + *it + sep_str;
233                                 break;
234                         case biblio::ENGINE_JURABIB:
235                                 label += before_str + author + ' ' +
236                                         year + sep_str;
237                                 break;
238                         case biblio::ENGINE_BASIC:
239                                 break;
240                         }
241
242                 // author; author; ...
243                 } else if (cite_type == "citeauthor") {
244                         label += author + sep_str;
245
246                 // year; year; ...
247                 } else if (cite_type == "citeyear" ||
248                            cite_type == "citeyearpar") {
249                         label += year + sep_str;
250                 }
251         }
252         label = rtrim(rtrim(label), sep);
253
254         if (!after_str.empty()) {
255                 if (cite_type == "citet") {
256                         // insert "after" before last ')'
257                         label.insert(label.size() - 1, after_str);
258                 } else {
259                         bool const add =
260                                 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
261                                   (cite_type == "citeauthor" ||
262                                    cite_type == "citeyear"));
263                         if (add)
264                                 label += after_str;
265                 }
266         }
267
268         if (!before_str.empty() && (cite_type == "citep" ||
269                                     cite_type == "citealp" ||
270                                     cite_type == "citeyearpar")) {
271                 label = before_str + label;
272         }
273
274         if (cite_type == "citep" || cite_type == "citeyearpar")
275                 label = string(1, op) + label + string(1, cp);
276
277         return label;
278 }
279
280
281 string const getBasicLabel(string const & keyList, string const & after)
282 {
283         string keys(keyList);
284         string label;
285
286         if (contains(keys, ',')) {
287                 // Final comma allows while loop to cover all keys
288                 keys = ltrim(split(keys, label, ',')) + ',';
289                 while (contains(keys, ',')) {
290                         string key;
291                         keys = ltrim(split(keys, key, ','));
292                         label += ", " + key;
293                 }
294         } else
295                 label = keys;
296
297         if (!after.empty())
298                 label += ", " + after;
299
300         return '[' + label + ']';
301 }
302
303 } // anon namespace
304
305
306 InsetCitation::InsetCitation(InsetCommandParams const & p)
307         : InsetCommand(p, "citation")
308 {}
309
310
311 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
312 {
313         string const before = getSecOptions();
314         string const after  = getOptions();
315
316         string label;
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);
321         }
322
323         // Fallback to fail-safe
324         if (label.empty()) {
325                 label = getBasicLabel(getContents(), after);
326         }
327
328         // FIXME UNICODE
329         return from_utf8(label);
330 }
331
332
333 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
334 {
335         biblio::CiteEngine const engine = biblio::getEngine(buffer);
336         if (cache.params == params() && cache.engine == engine)
337                 return cache.screen_label;
338
339         // The label has changed, so we have to re-create it.
340         string const before = getSecOptions();
341         string const after  = getOptions();
342
343         docstring const glabel = generateLabel(buffer);
344
345         unsigned int const maxLabelChars = 45;
346
347         docstring label = glabel;
348         if (label.size() > maxLabelChars) {
349                 label.erase(maxLabelChars-3);
350                 label += "...";
351         }
352
353         cache.engine  = engine;
354         cache.params = params();
355         cache.generated_label = glabel;
356         cache.screen_label = label;
357
358         return label;
359 }
360
361
362 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
363                              OutputParams const &) const
364 {
365         if (cache.params == params() &&
366             cache.engine == biblio::getEngine(buffer))
367                 os << cache.generated_label;
368         else
369                 os << generateLabel(buffer);
370         return 0;
371 }
372
373
374 namespace {
375
376 string const cleanupWhitespace(string const & citelist)
377 {
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
382         string result;
383         char last = ',';
384         for (; it != end; ++it) {
385                 if (*it != ' ')
386                         last = *it;
387                 if (*it != ' ' || last != ',')
388                         result += *it;
389         }
390         return result;
391 }
392
393 // end anon namyspace
394 }
395
396 int InsetCitation::docbook(Buffer const &, odocstream & os, OutputParams const &) const
397 {
398         os << "<citation>"
399            << from_ascii(cleanupWhitespace(getContents()))
400            << "</citation>";
401         return 0;
402 }
403
404
405 int InsetCitation::textString(Buffer const & buf, odocstream & os,
406                        OutputParams const & op) const
407 {
408         return plaintext(buf, os, op);
409 }
410
411
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
418 {
419         biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
420         // FIXME UNICODE
421         docstring const cite_str = from_utf8(
422                 biblio::asValidLatexCommand(getCmdName(), cite_engine));
423
424         os << "\\" << cite_str;
425
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 << ']';
432
433         // FIXME UNICODE
434         os << '{' << from_utf8(cleanupWhitespace(getContents())) << '}';
435
436         return 0;
437 }
438
439
440 void InsetCitation::validate(LaTeXFeatures & features) const
441 {
442         switch (features.bufferParams().cite_engine) {
443         case biblio::ENGINE_BASIC:
444                 break;
445         case biblio::ENGINE_NATBIB_AUTHORYEAR:
446         case biblio::ENGINE_NATBIB_NUMERICAL:
447                 features.require("natbib");
448                 break;
449         case biblio::ENGINE_JURABIB:
450                 features.require("jurabib");
451                 break;
452         }
453 }
454
455
456 void InsetCitation::replaceContents(string const & from, string const & to)
457 {
458         if (tokenPos(getContents(), ',', from) != -1) {
459                 vector<string> items = getVectorFromString(getContents());
460                 replace(items.begin(), items.end(), from, to);
461                 setContents(getStringFromVector(items));
462         }
463 }
464
465
466 } // namespace lyx