]> git.lyx.org Git - lyx.git/blob - src/insets/insetcite.C
Add support for the jurabib package (www.jurabib.org), a package for elegant BibTeX...
[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 "BufferView.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "LaTeXFeatures.h"
22
23 #include "frontends/controllers/biblio.h"
24
25 #include "support/lstrings.h"
26
27 using lyx::support::ascii_lowercase;
28 using lyx::support::contains;
29 using lyx::support::getVectorFromString;
30 using lyx::support::ltrim;
31 using lyx::support::rtrim;
32 using lyx::support::split;
33
34 using std::string;
35 using std::ostream;
36 using std::vector;
37 using std::map;
38
39
40 namespace {
41
42 string const getNatbibLabel(Buffer const & buffer,
43                             string const & citeType, string const & keyList,
44                             string const & before, string const & after,
45                             bool numerical, bool jura)
46 {
47         // Only start the process off after the buffer is loaded from file.
48         if (!buffer.fully_loaded())
49                 return string();
50
51         typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
52         static CachedMap cached_keys;
53
54         // build the keylist
55         typedef vector<std::pair<string, string> > InfoType;
56         InfoType bibkeys;
57         buffer.fillWithBibKeys(bibkeys);
58
59         InfoType::const_iterator bit  = bibkeys.begin();
60         InfoType::const_iterator bend = bibkeys.end();
61
62         biblio::InfoMap infomap;
63         for (; bit != bend; ++bit) {
64                 infomap[bit->first] = bit->second;
65         }
66         if (infomap.empty())
67                 return string();
68
69         cached_keys[&buffer] = infomap;
70
71         // the natbib citation-styles
72         // CITET:       author (year)
73         // CITEP:       (author,year)
74         // CITEALT:     author year
75         // CITEALP:     author, year
76         // CITEAUTHOR:  author
77         // CITEYEAR:    year
78         // CITEYEARPAR: (year)
79         // jurabib supports these plus
80         // CITE:        author/<before field>
81
82         // We don't currently use the full or forceUCase fields.
83         // bool const forceUCase = citeType[0] == 'C';
84         bool const full = citeType[citeType.size() - 1] == '*';
85
86         string const cite_type = full ?
87                 ascii_lowercase(citeType.substr(0, citeType.size() - 1)) :
88                 ascii_lowercase(citeType);
89
90         string before_str;
91         if (!before.empty()) {
92                 // In CITET and CITEALT mode, the "before" string is
93                 // attached to the label associated with each and every key.
94                 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
95                 // to the front of the whole only.
96                 // In other modes, it is not used at all.
97                 if (cite_type == "citet" ||
98                     cite_type == "citealt" ||
99                     cite_type == "citep" ||
100                     cite_type == "citealp" ||
101                     cite_type == "citeyearpar")
102                         before_str = before + ' ';
103                 // In CITE (jurabib), the "before" string is used to attach
104                 // the annotator (of legal texts) to the author(s) of the 
105                 // first reference. 
106                 else if (cite_type == "cite")
107                         before_str = '/' + before;
108         }
109
110         string after_str;
111         if (!after.empty()) {
112                 // The "after" key is appended only to the end of the whole.
113                 after_str = ", " + after;
114         }
115
116         // One day, these might be tunable (as they are in BibTeX).
117         char const op  = '('; // opening parenthesis.
118         char const cp  = ')'; // closing parenthesis.
119         // puctuation mark separating citation entries.
120         char const * const sep = ";";
121
122         string const op_str(' ' + string(1, op));
123         string const cp_str(string(1, cp) + ' ');
124         string const sep_str(string(sep) + ' ');
125
126         string label;
127         vector<string> keys = getVectorFromString(keyList);
128         vector<string>::const_iterator it  = keys.begin();
129         vector<string>::const_iterator end = keys.end();
130         for (; it != end; ++it) {
131                 // get the bibdata corresponding to the key
132                 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
133                 string const year(biblio::getYear(infomap, *it));
134
135                 // Something isn't right. Fail safely.
136                 if (author.empty() || year.empty())
137                         return string();
138
139                 // authors1/<before>;  ... ;
140                 //  authors_last, <after>
141                 if (cite_type == "cite" && jura) {
142                         if (it == keys.begin())
143                                 label += author + before_str + sep_str;
144                         else
145                                 label += author + sep_str;
146                 
147                 // (authors1 (<before> year);  ... ;
148                 //  authors_last (<before> year, <after>)
149                 } else if (cite_type == "citet") {
150                         string const tmp = numerical ? '#' + *it : year;
151                         if (!jura)
152                                 label += author + op_str + before_str + tmp +
153                                 cp + sep_str;
154                         else
155                                 label += before_str + author + op_str + tmp +
156                                 cp + sep_str;
157
158                 // author, year; author, year; ...
159                 } else if (cite_type == "citep" ||
160                            cite_type == "citealp") {
161                         if (numerical) {
162                                 label += *it + sep_str;
163                         } else {
164                                 label += author + ", " + year + sep_str;
165                         }
166
167                 // (authors1 <before> year;
168                 //  authors_last <before> year, <after>)
169                 } else if (cite_type == "citealt") {
170                         string const tmp = numerical ? '#' + *it : year;
171                         if (!jura)
172                                 label += author + ' ' + before_str + tmp + sep_str;
173                         else
174                                 label += before_str + author + ' ' + tmp + sep_str;
175
176                 // author; author; ...
177                 } else if (cite_type == "citeauthor") {
178                         label += author + sep_str;
179
180                 // year; year; ...
181                 } else if (cite_type == "citeyear" ||
182                            cite_type == "citeyearpar") {
183                         label += year + sep_str;
184                 }
185         }
186         label = rtrim(rtrim(label), sep);
187
188         if (!after_str.empty()) {
189                 if (cite_type == "citet") {
190                         // insert "after" before last ')'
191                         label.insert(label.size() - 1, after_str);
192                 } else {
193                         bool const add = !(numerical &&
194                                            (cite_type == "citeauthor" ||
195                                             cite_type == "citeyear"));
196                         if (add)
197                                 label += after_str;
198                 }
199         }
200
201         if (!before_str.empty() && (cite_type == "citep" ||
202                                     cite_type == "citealp" ||
203                                     cite_type == "citeyearpar")) {
204                 label = before_str + label;
205         }
206
207         if (cite_type == "citep" || cite_type == "citeyearpar")
208                 label = string(1, op) + label + string(1, cp);
209
210         return label;
211 }
212
213
214 string const getBasicLabel(string const & keyList, string const & after)
215 {
216         string keys(keyList);
217         string label;
218
219         if (contains(keys, ',')) {
220                 // Final comma allows while loop to cover all keys
221                 keys = ltrim(split(keys, label, ',')) + ',';
222                 while (contains(keys, ',')) {
223                         string key;
224                         keys = ltrim(split(keys, key, ','));
225                         label += ", " + key;
226                 }
227         } else
228                 label = keys;
229
230         if (!after.empty())
231                 label += ", " + after;
232
233         return '[' + label + ']';
234 }
235
236 } // anon namespace
237
238
239 InsetCitation::InsetCitation(InsetCommandParams const & p)
240         : InsetCommand(p, "citation")
241 {}
242
243
244 string const InsetCitation::generateLabel(Buffer const & buffer) const
245 {
246         string const before = getSecOptions();
247         string const after  = getOptions();
248
249         string label;
250         if (buffer.params().use_natbib || buffer.params().use_jurabib) {
251                 string cmd = getCmdName();
252                 if (buffer.params().use_natbib && cmd == "cite") {
253                         // We may be "upgrading" from an older LyX version.
254                         // If, however, we use "cite" because the necessary
255                         // author/year info is not present in the biblio
256                         // database, then getNatbibLabel will exit gracefully
257                         // and we'll call getBasicLabel.
258                         if (buffer.params().use_numerical_citations)
259                                 cmd = "citep";
260                         else
261                                 cmd = "citet";
262                 }
263                 label = getNatbibLabel(buffer, cmd, getContents(),
264                                        before, after,
265                                        buffer.params().use_numerical_citations,
266                                        buffer.params().use_jurabib);
267         }
268
269         // Fallback to fail-safe
270         if (label.empty()) {
271                 label = getBasicLabel(getContents(), after);
272         }
273
274         return label;
275 }
276
277
278 InsetCitation::Cache::Style InsetCitation::getStyle(Buffer const & buffer) const
279 {
280         Cache::Style style = Cache::BASIC;
281
282         if (buffer.params().use_natbib) {
283                 if (buffer.params().use_numerical_citations) {
284                         style = Cache::NATBIB_NUM;
285                 } else {
286                         style = Cache::NATBIB_AY;
287                 }
288         }
289         
290         if (buffer.params().use_jurabib)
291                 style = Cache::JURABIB;
292
293         return style;
294 }
295
296
297 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
298 {
299         Cache::Style const style = getStyle(buffer);
300         if (cache.params == params() && cache.style == style)
301                 return cache.screen_label;
302
303         // The label has changed, so we have to re-create it.
304         string const before = getSecOptions();
305         string const after  = getOptions();
306
307         string const glabel = generateLabel(buffer);
308
309         unsigned int const maxLabelChars = 45;
310
311         string label = glabel;
312         if (label.size() > maxLabelChars) {
313                 label.erase(maxLabelChars-3);
314                 label += "...";
315         }
316
317         cache.style  = style;
318         cache.params = params();
319         cache.generated_label = glabel;
320         cache.screen_label = label;
321
322         return label;
323 }
324
325
326 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, int) const
327 {
328         if (cache.params == params() && cache.style == getStyle(buffer))
329                 os << cache.generated_label;
330         else
331                 os << generateLabel(buffer);
332         return 0;
333 }
334
335
336 // Have to overwrite the default InsetCommand method in order to check that
337 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
338 // citations and then changes his mind, turning natbib support off. The output
339 // should revert to \cite[]{}
340 int InsetCitation::latex(Buffer const & buffer, ostream & os,
341                          OutputParams const &) const
342 {
343         os << "\\";
344         if (buffer.params().use_natbib)
345                 os << getCmdName();
346         else if (buffer.params().use_jurabib) {
347                 // jurabib does not (yet) support "force upper case" 
348                 // and "full author name". Fallback.
349                 string cmd = getCmdName();
350                 if (cmd[0] == 'C')
351                         cmd[0] = 'c';
352                 size_t n = cmd.size() - 1;
353                 if (cmd[n] == '*')
354                         cmd = cmd.substr(0,n);
355                 os << cmd;
356         } else
357                 os << "cite";
358
359         string const before = getSecOptions();
360         string const after  = getOptions();
361         if (!before.empty() 
362                 && (buffer.params().use_natbib || buffer.params().use_jurabib))
363                 os << '[' << before << "][" << after << ']';
364         else if (!after.empty())
365                 os << '[' << after << ']';
366
367         string::const_iterator it  = getContents().begin();
368         string::const_iterator end = getContents().end();
369         // Paranoia check: make sure that there is no whitespace in here
370         string content;
371         char last = ',';
372         for (; it != end; ++it) {
373                 if (*it != ' ')
374                         last = *it;
375                 if (*it != ' ' || last != ',')
376                         content += *it;
377         }
378
379         os << '{' << content << '}';
380
381         return 0;
382 }
383
384
385 void InsetCitation::validate(LaTeXFeatures & features) const
386 {
387         if (features.bufferParams().use_natbib)
388                 features.require("natbib");
389         else if (features.bufferParams().use_jurabib)
390                 features.require("jurabib");
391 }