]> git.lyx.org Git - lyx.git/blob - src/insets/insetcite.C
support for second \cite option.
[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)
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
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         }
102
103         string after_str;
104         if (!after.empty()) {
105                 // The "after" key is appended only to the end of the whole.
106                 after_str = ", " + after;
107         }
108
109         // One day, these might be tunable (as they are in BibTeX).
110         char const op  = '('; // opening parenthesis.
111         char const cp  = ')'; // closing parenthesis.
112         // puctuation mark separating citation entries.
113         char const * const sep = ";";
114
115         string const op_str(' ' + string(1, op));
116         string const cp_str(string(1, cp) + ' ');
117         string const sep_str(string(sep) + ' ');
118
119         string label;
120         vector<string> keys = getVectorFromString(keyList);
121         vector<string>::const_iterator it  = keys.begin();
122         vector<string>::const_iterator end = keys.end();
123         for (; it != end; ++it) {
124                 // get the bibdata corresponding to the key
125                 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
126                 string const year(biblio::getYear(infomap, *it));
127
128                 // Something isn't right. Fail safely.
129                 if (author.empty() || year.empty())
130                         return string();
131
132                 // (authors1 (<before> year);  ... ;
133                 //  authors_last (<before> year, <after>)
134                 if (cite_type == "citet") {
135                         string const tmp = numerical ? '#' + *it : year;
136                         label += author + op_str + before_str + tmp +
137                                 cp + sep_str;
138
139                 // author, year; author, year; ...
140                 } else if (cite_type == "citep" ||
141                            cite_type == "citealp") {
142                         if (numerical) {
143                                 label += *it + sep_str;
144                         } else {
145                                 label += author + ", " + year + sep_str;
146                         }
147
148                 // (authors1 <before> year;
149                 //  authors_last <before> year, <after>)
150                 } else if (cite_type == "citealt") {
151                         string const tmp = numerical ? '#' + *it : year;
152                         label += author + ' ' + before_str + tmp + sep_str;
153
154                 // author; author; ...
155                 } else if (cite_type == "citeauthor") {
156                         label += author + sep_str;
157
158                 // year; year; ...
159                 } else if (cite_type == "citeyear" ||
160                            cite_type == "citeyearpar") {
161                         label += year + sep_str;
162                 }
163         }
164         label = rtrim(rtrim(label), sep);
165
166         if (!after_str.empty()) {
167                 if (cite_type == "citet") {
168                         // insert "after" before last ')'
169                         label.insert(label.size() - 1, after_str);
170                 } else {
171                         bool const add = !(numerical &&
172                                            (cite_type == "citeauthor" ||
173                                             cite_type == "citeyear"));
174                         if (add)
175                                 label += after_str;
176                 }
177         }
178
179         if (!before_str.empty() && (cite_type == "citep" ||
180                                     cite_type == "citealp" ||
181                                     cite_type == "citeyearpar")) {
182                 label = before_str + label;
183         }
184
185         if (cite_type == "citep" || cite_type == "citeyearpar")
186                 label = string(1, op) + label + string(1, cp);
187
188         return label;
189 }
190
191
192 string const getBasicLabel(string const & keyList, string const & after)
193 {
194         string keys(keyList);
195         string label;
196
197         if (contains(keys, ',')) {
198                 // Final comma allows while loop to cover all keys
199                 keys = ltrim(split(keys, label, ',')) + ',';
200                 while (contains(keys, ',')) {
201                         string key;
202                         keys = ltrim(split(keys, key, ','));
203                         label += ", " + key;
204                 }
205         } else
206                 label = keys;
207
208         if (!after.empty())
209                 label += ", " + after;
210
211         return '[' + label + ']';
212 }
213
214 } // anon namespace
215
216
217 InsetCitation::InsetCitation(InsetCommandParams const & p)
218         : InsetCommand(p, "citation")
219 {}
220
221
222 string const InsetCitation::generateLabel(Buffer const & buffer) const
223 {
224         string const before = getSecOptions();
225         string const after  = getOptions();
226
227         string label;
228         if (buffer.params().use_natbib) {
229                 string cmd = getCmdName();
230                 if (cmd == "cite") {
231                         // We may be "upgrading" from an older LyX version.
232                         // If, however, we use "cite" because the necessary
233                         // author/year info is not present in the biblio
234                         // database, then getNatbibLabel will exit gracefully
235                         // and we'll call getBasicLabel.
236                         if (buffer.params().use_numerical_citations)
237                                 cmd = "citep";
238                         else
239                                 cmd = "citet";
240                 }
241                 label = getNatbibLabel(buffer, cmd, getContents(),
242                                        before, after,
243                                        buffer.params().use_numerical_citations);
244         }
245
246         // Fallback to fail-safe
247         if (label.empty()) {
248                 label = getBasicLabel(getContents(), after);
249         }
250
251         return label;
252 }
253
254
255 InsetCitation::Cache::Style InsetCitation::getStyle(Buffer const & buffer) const
256 {
257         Cache::Style style = Cache::BASIC;
258
259         if (buffer.params().use_natbib) {
260                 if (buffer.params().use_numerical_citations) {
261                         style = Cache::NATBIB_NUM;
262                 } else {
263                         style = Cache::NATBIB_AY;
264                 }
265         }
266
267         return style;
268 }
269
270
271 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
272 {
273         Cache::Style const style = getStyle(buffer);
274         if (cache.params == params() && cache.style == style)
275                 return cache.screen_label;
276
277         // The label has changed, so we have to re-create it.
278         string const before = getSecOptions();
279         string const after  = getOptions();
280
281         string const glabel = generateLabel(buffer);
282
283         unsigned int const maxLabelChars = 45;
284
285         string label = glabel;
286         if (label.size() > maxLabelChars) {
287                 label.erase(maxLabelChars-3);
288                 label += "...";
289         }
290
291         cache.style  = style;
292         cache.params = params();
293         cache.generated_label = glabel;
294         cache.screen_label = label;
295
296         return label;
297 }
298
299
300 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, int) const
301 {
302         if (cache.params == params() && cache.style == getStyle(buffer))
303                 os << cache.generated_label;
304         else
305                 os << generateLabel(buffer);
306         return 0;
307 }
308
309
310 // Have to overwrite the default InsetCommand method in order to check that
311 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
312 // citations and then changes his mind, turning natbib support off. The output
313 // should revert to \cite[]{}
314 int InsetCitation::latex(Buffer const & buffer, ostream & os,
315                          OutputParams const &) const
316 {
317         os << "\\";
318         if (buffer.params().use_natbib)
319                 os << getCmdName();
320         else
321                 os << "cite";
322
323         string const before = getSecOptions();
324         string const after  = getOptions();
325         if (!before.empty() && buffer.params().use_natbib)
326                 os << '[' << before << "][" << after << ']';
327         else if (!after.empty())
328                 os << '[' << after << ']';
329
330         string::const_iterator it  = getContents().begin();
331         string::const_iterator end = getContents().end();
332         // Paranoia check: make sure that there is no whitespace in here
333         string content;
334         char last = ',';
335         for (; it != end; ++it) {
336                 if (*it != ' ')
337                         last = *it;
338                 if (*it != ' ' || last != ',')
339                         content += *it;
340         }
341
342         os << '{' << content << '}';
343
344         return 0;
345 }
346
347
348 void InsetCitation::validate(LaTeXFeatures & features) const
349 {
350         if (features.bufferParams().use_natbib)
351                 features.require("natbib");
352 }