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