]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Circumvent odd stmary font metrics (part of #9990).
[lyx.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         vector<docstring>::const_iterator it = keys.begin();
169         vector<docstring>::const_iterator en = keys.end();
170         docstring tip;
171         for (; it != en; ++it) {
172                 docstring const key_info = bi.getInfo(*it, buffer());
173                 if (key_info.empty())
174                         continue;
175                 if (!tip.empty())
176                         tip += "\n";
177                 tip += wrap(key_info, -4);
178         }
179         return tip;
180 }
181
182
183 namespace {
184
185
186 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const & valid_styles)
187 {
188         CitationStyle cs = valid_styles[0];
189         cs.forceUpperCase = false;
190         cs.fullAuthorList = false;
191         if (!InsetCitation::isCompatibleCommand(input))
192                 return cs;
193
194         string normalized_input = input;
195         string::size_type const n = input.size() - 1;
196         if (input[0] == 'C')
197                 normalized_input[0] = 'c';
198         if (input[n] == '*')
199                 normalized_input = normalized_input.substr(0, n);
200
201         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
202         vector<CitationStyle>::const_iterator end = valid_styles.end();
203         for (; it != end; ++it) {
204                 CitationStyle this_cs = *it;
205                 if (this_cs.cmd == normalized_input) {
206                         cs = *it;
207                         break;
208                 }
209         }
210
211         cs.forceUpperCase &= input[0] == 'C';
212         cs.fullAuthorList &= input[n] == '*';
213
214         return cs;
215 }
216
217
218 inline docstring wrapCitation(docstring const & key,
219                 docstring const & content, bool for_xhtml)
220 {
221         if (!for_xhtml)
222                 return content;
223         // we have to do the escaping here, because we will ultimately
224         // write this as a raw string, so as not to escape the tags.
225         return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
226                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
227 }
228
229 } // anonymous namespace
230
231 docstring InsetCitation::generateLabel(bool for_xhtml) const
232 {
233         docstring label;
234         label = complexLabel(for_xhtml);
235
236         // Fallback to fail-safe
237         if (label.empty())
238                 label = basicLabel(for_xhtml);
239
240         return label;
241 }
242
243
244 docstring InsetCitation::complexLabel(bool for_xhtml) const
245 {
246         Buffer const & buf = buffer();
247         // Only start the process off after the buffer is loaded from file.
248         if (!buf.isFullyLoaded())
249                 return docstring();
250
251         BiblioInfo const & biblist = buf.masterBibInfo();
252         if (biblist.empty())
253                 return docstring();
254
255         docstring const & key = getParam("key");
256         if (key.empty())
257                 return _("No citations selected!");
258
259         // We don't currently use the full or forceUCase fields.
260         string cite_type = getCmdName();
261         if (cite_type[0] == 'C')
262                 // If we were going to use them, this would mean ForceUCase
263                 cite_type = string(1, 'c') + cite_type.substr(1);
264         if (cite_type[cite_type.size() - 1] == '*')
265                 // and this would mean FULL
266                 cite_type = cite_type.substr(0, cite_type.size() - 1);
267
268         docstring const & before = getParam("before");
269         docstring const & after = getParam("after");
270
271         // FIXME: allow to add cite macros
272         /*
273         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
274         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
275         */
276         docstring label;
277         vector<docstring> keys = getVectorFromString(key);
278         label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
279         return label;
280 }
281
282
283 docstring InsetCitation::basicLabel(bool for_xhtml) const
284 {
285         docstring keys = getParam("key");
286         docstring label;
287
288         docstring key;
289         do {
290                 // if there is no comma, then everything goes into key
291                 // and keys will be empty.
292                 keys = trim(split(keys, key, ','));
293                 key = trim(key);
294                 if (!label.empty())
295                         label += ", ";
296                 label += wrapCitation(key, key, for_xhtml);
297         } while (!keys.empty());
298
299         docstring const & after = getParam("after");
300         if (!after.empty())
301                 label += ", " + after;
302
303         return '[' + label + ']';
304 }
305
306 docstring InsetCitation::screenLabel() const
307 {
308         return cache.screen_label;
309 }
310
311
312 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
313 {
314         if (!cache.recalculate && buffer().citeLabelsValid())
315                 return;
316         // The label may have changed, so we have to re-create it.
317         docstring const glabel = generateLabel();
318         cache.recalculate = false;
319         cache.generated_label = glabel;
320         unsigned int const maxLabelChars = 45;
321         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
322         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
323 }
324
325
326 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
327                                                          UpdateType) const
328 {
329         // NOTE
330         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
331         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
332         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
333         // then we will also need to change that routine.
334         docstring const tocitem = getParam("key");
335         shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
336         toc->push_back(TocItem(cpit, 0, tocitem, output_active));
337 }
338
339
340 int InsetCitation::plaintext(odocstringstream & os,
341        OutputParams const &, size_t) const
342 {
343         string const & cmd = getCmdName();
344         if (cmd == "nocite")
345                 return 0;
346
347         docstring const label = generateLabel(false);
348         os << label;
349         return label.size();
350 }
351
352
353 static docstring const cleanupWhitespace(docstring const & citelist)
354 {
355         docstring::const_iterator it  = citelist.begin();
356         docstring::const_iterator end = citelist.end();
357         // Paranoia check: make sure that there is no whitespace in here
358         // -- at least not behind commas or at the beginning
359         docstring result;
360         char_type last = ',';
361         for (; it != end; ++it) {
362                 if (*it != ' ')
363                         last = *it;
364                 if (*it != ' ' || last != ',')
365                         result += *it;
366         }
367         return result;
368 }
369
370
371 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
372 {
373         os << from_ascii("<citation>")
374            << cleanupWhitespace(getParam("key"))
375            << from_ascii("</citation>");
376         return 0;
377 }
378
379
380 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
381 {
382         string const & cmd = getCmdName();
383         if (cmd == "nocite")
384                 return docstring();
385
386         // have to output this raw, because generateLabel() will include tags
387         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
388
389         return docstring();
390 }
391
392
393 void InsetCitation::toString(odocstream & os) const
394 {
395         odocstringstream ods;
396         plaintext(ods, OutputParams(0));
397         os << ods.str();
398 }
399
400
401 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
402 {
403         os += screenLabel();
404 }
405
406
407 // Have to overwrite the default InsetCommand method in order to check that
408 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
409 // citations and then changes his mind, turning natbib support off. The output
410 // should revert to the default citation command as provided by the citation
411 // engine, e.g. \cite[]{} for the basic engine.
412 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
413 {
414         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
415         CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
416         BiblioInfo const & bi = buffer().masterBibInfo();
417         // FIXME UNICODE
418         docstring const cite_str = from_utf8(citationStyleToString(cs));
419
420         if (runparams.inulemcmd > 0)
421                 os << "\\mbox{";
422
423         os << "\\" << cite_str;
424
425         docstring const & before = getParam("before");
426         docstring const & after  = getParam("after");
427         if (!before.empty() && cs.textBefore)
428                 os << '[' << before << "][" << after << ']';
429         else if (!after.empty() && cs.textAfter)
430                 os << '[' << after << ']';
431
432         if (!bi.isBibtex(getParam("key")))
433                 // escape chars with bibitems
434                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
435         else
436                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
437
438         if (runparams.inulemcmd)
439                 os << "}";
440 }
441
442
443 string InsetCitation::contextMenuName() const
444 {
445         return "context-citation";
446 }
447
448
449 } // namespace lyx