]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Differentiate InsetCite
[features.git] / src / insets / InsetCitation.cpp
1 /**
2  * \file InsetCitation.cpp
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 "InsetCitation.h"
15
16 #include "BiblioInfo.h"
17 #include "Buffer.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "DispatchResult.h"
22 #include "FuncCode.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "LaTeXFeatures.h"
26 #include "output_xhtml.h"
27 #include "ParIterator.h"
28 #include "texstream.h"
29 #include "TocBackend.h"
30
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/FileNameList.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36
37 #include <algorithm>
38 #include <climits>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44
45 ParamInfo InsetCitation::param_info_;
46
47
48 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
49         : InsetCommand(buf, p)
50 {
51         buffer().removeBiblioTempFiles();
52 }
53
54
55 InsetCitation::~InsetCitation()
56 {
57         if (isBufferLoaded())
58                 buffer().removeBiblioTempFiles();
59 }
60
61
62 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
63 {
64         // standard cite does only take one argument if jurabib is
65         // not used, but jurabib extends this to two arguments, so
66         // we have to allow both here. InsetCitation takes care that
67         // LaTeX output is nevertheless correct.
68         if (param_info_.empty()) {
69                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
70                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
71                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
72         }
73         return param_info_;
74 }
75
76
77 namespace {
78
79 vector<string> const init_possible_cite_commands()
80 {
81         char const * const possible[] = {
82                 "cite", "nocite", "citet", "citep", "citealt", "citealp",
83                 "citeauthor", "citeyear", "citeyearpar",
84                 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
85                 "Citet",  "Citep",  "Citealt",  "Citealp",  "Citeauthor",
86                 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
87                 "fullcite",
88                 "footcite", "footcitet", "footcitep", "footcitealt",
89                 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
90                 "citefield", "citetitle", "cite*"
91         };
92         size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
93
94         return vector<string>(possible, possible + size_possible);
95 }
96
97
98 vector<string> const & possibleCiteCommands()
99 {
100         static vector<string> const possible = init_possible_cite_commands();
101         return possible;
102 }
103
104
105 } // anon namespace
106
107
108 // FIXME: use the citeCommands provided by the TextClass
109 // instead of possibleCiteCommands defined in this file.
110 bool InsetCitation::isCompatibleCommand(string const & cmd)
111 {
112         vector<string> const & possibles = possibleCiteCommands();
113         vector<string>::const_iterator const end = possibles.end();
114         return find(possibles.begin(), end, cmd) != end;
115 }
116
117
118 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
119 {
120         if (cmd.action() == LFUN_INSET_MODIFY) {
121                 buffer().removeBiblioTempFiles();
122                 cache.recalculate = true;
123         }
124         InsetCommand::doDispatch(cur, cmd);
125 }
126
127
128 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
129         FuncStatus & status) const
130 {
131         switch (cmd.action()) {
132         // Handle the alias case
133         case LFUN_INSET_MODIFY:
134                 if (cmd.getArg(0) == "changetype") {
135                         string cmdname = getCmdName();
136                         string const alias = buffer().params().getCiteAlias(cmdname);
137                         if (!alias.empty())
138                                 cmdname = alias;
139                         string const newtype = cmd.getArg(1);
140                         status.setEnabled(isCompatibleCommand(newtype));
141                         status.setOnOff(newtype == cmdname);
142                 }
143                 status.setEnabled(true);
144                 return true;
145         default:
146                 return InsetCommand::getStatus(cur, cmd, status);
147         }
148 }
149
150
151 bool InsetCitation::addKey(string const & key)
152 {
153         docstring const ukey = from_utf8(key);
154         docstring const & curkeys = getParam("key");
155         if (curkeys.empty()) {
156                 setParam("key", ukey);
157                 cache.recalculate = true;
158                 return true;
159         }
160
161         vector<docstring> keys = getVectorFromString(curkeys);
162         vector<docstring>::const_iterator it = keys.begin();
163         vector<docstring>::const_iterator en = keys.end();
164         for (; it != en; ++it) {
165                 if (*it == ukey) {
166                         LYXERR0("Key " << key << " already present.");
167                         return false;
168                 }
169         }
170         keys.push_back(ukey);
171         setParam("key", getStringFromVector(keys));
172         cache.recalculate = true;
173         return true;
174 }
175
176
177 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
178 {
179         Buffer const & buf = bv.buffer();
180         // Only after the buffer is loaded from file...
181         if (!buf.isFullyLoaded())
182                 return docstring();
183
184         BiblioInfo const & bi = buf.masterBibInfo();
185         if (bi.empty())
186                 return _("No bibliography defined!");
187
188         docstring const & key = getParam("key");
189         if (key.empty())
190                 return _("No citations selected!");
191
192         vector<docstring> keys = getVectorFromString(key);
193         if (keys.size() == 1)
194                 return bi.getInfo(keys[0], buffer(), true);
195
196         docstring tip;
197         tip += "<ol>";
198         for (docstring const & key : keys) {
199                 docstring const key_info = bi.getInfo(key, buffer(), true);
200                 if (key_info.empty())
201                         continue;
202                 tip += "<li>" + key_info + "</li>";
203         }
204         tip += "</ol>";
205         return tip;
206 }
207
208
209 namespace {
210
211
212 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
213                                   vector<CitationStyle> const & valid_styles)
214 {
215         CitationStyle cs = valid_styles[0];
216         cs.forceUpperCase = false;
217         cs.fullAuthorList = false;
218         if (!InsetCitation::isCompatibleCommand(input))
219                 return cs;
220
221         string normalized_input = input;
222         string::size_type const n = input.size() - 1;
223         if (isUpperCase(input[0]))
224                 normalized_input[0] = lowercase(input[0]);
225         if (input[n] == '*')
226                 normalized_input = normalized_input.substr(0, n);
227
228         string const alias = bp.getCiteAlias(normalized_input);
229         if (!alias.empty())
230                 normalized_input = alias;
231
232         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
233         vector<CitationStyle>::const_iterator end = valid_styles.end();
234         for (; it != end; ++it) {
235                 CitationStyle this_cs = *it;
236                 if (this_cs.name == normalized_input) {
237                         cs = *it;
238                         break;
239                 }
240         }
241
242         cs.forceUpperCase &= input[0] == uppercase(input[0]);
243         cs.fullAuthorList &= input[n] == '*';
244
245         return cs;
246 }
247
248
249 inline docstring wrapCitation(docstring const & key,
250                 docstring const & content, bool for_xhtml)
251 {
252         if (!for_xhtml)
253                 return content;
254         // we have to do the escaping here, because we will ultimately
255         // write this as a raw string, so as not to escape the tags.
256         return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
257                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
258 }
259
260 } // anonymous namespace
261
262 docstring InsetCitation::generateLabel(bool for_xhtml) const
263 {
264         docstring label;
265         label = complexLabel(for_xhtml);
266
267         // Fallback to fail-safe
268         if (label.empty())
269                 label = basicLabel(for_xhtml);
270
271         return label;
272 }
273
274
275 docstring InsetCitation::complexLabel(bool for_xhtml) const
276 {
277         Buffer const & buf = buffer();
278         // Only start the process off after the buffer is loaded from file.
279         if (!buf.isFullyLoaded())
280                 return docstring();
281
282         BiblioInfo const & biblist = buf.masterBibInfo();
283         if (biblist.empty())
284                 return docstring();
285
286         docstring const & key = getParam("key");
287         if (key.empty())
288                 return _("No citations selected!");
289
290         // We don't currently use the full or forceUCase fields.
291         string cite_type = getCmdName();
292         if (isUpperCase(cite_type[0]))
293                 // If we were going to use them, this would mean ForceUCase
294                 cite_type[0] = lowercase(cite_type[0]);
295         if (cite_type[cite_type.size() - 1] == '*')
296                 // and this would mean FULL
297                 cite_type = cite_type.substr(0, cite_type.size() - 1);
298
299         // handle alias
300         string const alias = buf.params().getCiteAlias(cite_type);
301         if (!alias.empty())
302                 cite_type = alias;
303
304         docstring const & before = getParam("before");
305         docstring const & after = getParam("after");
306
307         // FIXME: allow to add cite macros
308         /*
309         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
310         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
311         */
312         docstring label;
313         vector<docstring> keys = getVectorFromString(key);
314         label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
315         return label;
316 }
317
318
319 docstring InsetCitation::basicLabel(bool for_xhtml) const
320 {
321         docstring keys = getParam("key");
322         docstring label;
323
324         docstring key;
325         do {
326                 // if there is no comma, then everything goes into key
327                 // and keys will be empty.
328                 keys = trim(split(keys, key, ','));
329                 key = trim(key);
330                 if (!label.empty())
331                         label += ", ";
332                 label += wrapCitation(key, key, for_xhtml);
333         } while (!keys.empty());
334
335         docstring const & after = getParam("after");
336         if (!after.empty())
337                 label += ", " + after;
338
339         return '[' + label + ']';
340 }
341
342 docstring InsetCitation::screenLabel() const
343 {
344         return cache.screen_label;
345 }
346
347
348 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
349 {
350         if (!cache.recalculate && buffer().citeLabelsValid())
351                 return;
352         // The label may have changed, so we have to re-create it.
353         docstring const glabel = generateLabel();
354         cache.recalculate = false;
355         cache.generated_label = glabel;
356         unsigned int const maxLabelChars = 45;
357         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
358         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
359 }
360
361
362 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
363                                                          UpdateType) const
364 {
365         // NOTE
366         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
367         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
368         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
369         // then we will also need to change that routine.
370         docstring const tocitem = getParam("key");
371         shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
372         toc->push_back(TocItem(cpit, 0, tocitem, output_active));
373 }
374
375
376 int InsetCitation::plaintext(odocstringstream & os,
377        OutputParams const &, size_t) const
378 {
379         string const & cmd = getCmdName();
380         if (cmd == "nocite")
381                 return 0;
382
383         docstring const label = generateLabel(false);
384         os << label;
385         return label.size();
386 }
387
388
389 static docstring const cleanupWhitespace(docstring const & citelist)
390 {
391         docstring::const_iterator it  = citelist.begin();
392         docstring::const_iterator end = citelist.end();
393         // Paranoia check: make sure that there is no whitespace in here
394         // -- at least not behind commas or at the beginning
395         docstring result;
396         char_type last = ',';
397         for (; it != end; ++it) {
398                 if (*it != ' ')
399                         last = *it;
400                 if (*it != ' ' || last != ',')
401                         result += *it;
402         }
403         return result;
404 }
405
406
407 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
408 {
409         os << from_ascii("<citation>")
410            << cleanupWhitespace(getParam("key"))
411            << from_ascii("</citation>");
412         return 0;
413 }
414
415
416 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
417 {
418         string const & cmd = getCmdName();
419         if (cmd == "nocite")
420                 return docstring();
421
422         // have to output this raw, because generateLabel() will include tags
423         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
424
425         return docstring();
426 }
427
428
429 void InsetCitation::toString(odocstream & os) const
430 {
431         odocstringstream ods;
432         plaintext(ods, OutputParams(0));
433         os << ods.str();
434 }
435
436
437 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
438 {
439         os += screenLabel();
440 }
441
442
443 // Have to overwrite the default InsetCommand method in order to check that
444 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
445 // citations and then changes his mind, turning natbib support off. The output
446 // should revert to the default citation command as provided by the citation
447 // engine, e.g. \cite[]{} for the basic engine.
448 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
449 {
450         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
451         CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
452         BiblioInfo const & bi = buffer().masterBibInfo();
453         // FIXME UNICODE
454         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
455
456         if (runparams.inulemcmd > 0)
457                 os << "\\mbox{";
458
459         os << "\\" << cite_str;
460
461         docstring const & before = getParam("before");
462         docstring const & after  = getParam("after");
463         if (!before.empty() && cs.textBefore)
464                 os << '[' << before << "][" << after << ']';
465         else if (!after.empty() && cs.textAfter)
466                 os << '[' << after << ']';
467
468         if (!bi.isBibtex(getParam("key")))
469                 // escape chars with bibitems
470                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
471         else
472                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
473
474         if (runparams.inulemcmd)
475                 os << "}";
476 }
477
478
479 string InsetCitation::contextMenuName() const
480 {
481         return "context-citation";
482 }
483
484
485 } // namespace lyx