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