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