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