]> git.lyx.org Git - lyx.git/blob - src/insets/insetcite.C
make dispatch_result_t ctor of DispatchResult explicit
[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)
219 {}
220
221
222 // InsetCitation::InsetCitation(InsetCommandParams const & p, bool)
223 //      : InsetCommand(p, false)
224 // {}
225
226
227 InsetCitation::~InsetCitation()
228 {
229         InsetCommandMailer mailer("citation", *this);
230         mailer.hideDialog();
231 }
232
233
234 string const InsetCitation::generateLabel(Buffer const & buffer) const
235 {
236         string const before = string();
237         string const after  = getOptions();
238
239         string label;
240         if (buffer.params().use_natbib) {
241                 string cmd = getCmdName();
242                 if (cmd == "cite") {
243                         // We may be "upgrading" from an older LyX version.
244                         // If, however, we use "cite" because the necessary
245                         // author/year info is not present in the biblio
246                         // database, then getNatbibLabel will exit gracefully
247                         // and we'll call getBasicLabel.
248                         if (buffer.params().use_numerical_citations)
249                                 cmd = "citep";
250                         else
251                                 cmd = "citet";
252                 }
253                 label = getNatbibLabel(buffer, cmd, getContents(),
254                                        before, after,
255                                        buffer.params().use_numerical_citations);
256         }
257
258         // Fallback to fail-safe
259         if (label.empty()) {
260                 label = getBasicLabel(getContents(), after);
261         }
262
263         return label;
264 }
265
266
267 InsetCitation::Cache::Style InsetCitation::getStyle(Buffer const & buffer) const
268 {
269         Cache::Style style = Cache::BASIC;
270
271         if (buffer.params().use_natbib) {
272                 if (buffer.params().use_numerical_citations) {
273                         style = Cache::NATBIB_NUM;
274                 } else {
275                         style = Cache::NATBIB_AY;
276                 }
277         }
278
279         return style;
280 }
281
282
283 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
284 {
285         Cache::Style const style = getStyle(buffer);
286         if (cache.params == params() && cache.style == style)
287                 return cache.screen_label;
288
289         // The label has changed, so we have to re-create it.
290         string const before = string();
291         string const after  = getOptions();
292
293         string const glabel = generateLabel(buffer);
294
295         unsigned int const maxLabelChars = 45;
296
297         string label = glabel;
298         if (label.size() > maxLabelChars) {
299                 label.erase(maxLabelChars-3);
300                 label += "...";
301         }
302
303         cache.style  = style;
304         cache.params = params();
305         cache.generated_label = glabel;
306         cache.screen_label = label;
307
308         return label;
309 }
310
311
312 DispatchResult
313 InsetCitation::priv_dispatch(FuncRequest const & cmd,
314                              idx_type & idx, pos_type & pos)
315 {
316         switch (cmd.action) {
317         case LFUN_INSET_EDIT:
318                 InsetCommandMailer("citation", *this).showDialog(cmd.view());
319                 return DispatchResult(DISPATCHED);
320
321         default:
322                 return InsetCommand::priv_dispatch(cmd, idx, pos);
323         }
324 }
325
326
327 int InsetCitation::ascii(Buffer const & buffer, ostream & os, int) const
328 {
329         if (cache.params == params() && cache.style == getStyle(buffer))
330                 os << cache.generated_label;
331         else
332                 os << generateLabel(buffer);
333         return 0;
334 }
335
336
337 // Have to overwrite the default InsetCommand method in order to check that
338 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
339 // citations and then changes his mind, turning natbib support off. The output
340 // should revert to \cite[]{}
341 int InsetCitation::latex(Buffer const & buffer, ostream & os,
342                          LatexRunParams const &) const
343 {
344         os << "\\";
345         if (buffer.params().use_natbib)
346                 os << getCmdName();
347         else
348                 os << "cite";
349
350 #warning What is this code supposed to do? (Lgb)
351 // my guess is that this is just waiting for when we support before,
352 // so it's a oneliner. But this is very silly ! - jbl
353
354 #if 1
355         // The current strange code
356
357         string const before = string();
358         string const after  = getOptions();
359         if (!before.empty() && buffer.params().use_natbib)
360                 os << '[' << before << "][" << after << ']';
361         else if (!after.empty())
362                 os << '[' << after << ']';
363 #else
364         // and the cleaned up equvalent, should it just be changed? (Lgb)
365         string const after  = getOptions();
366         if (!after.empty())
367                 os << '[' << after << ']';
368 #endif
369         string::const_iterator it  = getContents().begin();
370         string::const_iterator end = getContents().end();
371         // Paranoia check: make sure that there is no whitespace in here
372         string content;
373         char last = ',';
374         for (; it != end; ++it) {
375                 if (*it != ' ')
376                         last = *it;
377                 if (*it != ' ' || last != ',')
378                         content += *it;
379         }
380
381         os << '{' << content << '}';
382
383         return 0;
384 }
385
386
387 void InsetCitation::validate(LaTeXFeatures & features) const
388 {
389         if (features.bufferParams().use_natbib)
390                 features.require("natbib");
391 }