]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Implement CiteItem in the chain
[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, but biblatex, jurabib
65         // and natbib extend 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 // We allow any command here, since we fall back to cite
78 // anyway if a command is not allowed by a style
79 bool InsetCitation::isCompatibleCommand(string const &)
80 {
81         return true;
82 }
83
84
85 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
86 {
87         if (cmd.action() == LFUN_INSET_MODIFY) {
88                 buffer().removeBiblioTempFiles();
89                 cache.recalculate = true;
90         }
91         InsetCommand::doDispatch(cur, cmd);
92 }
93
94
95 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
96         FuncStatus & status) const
97 {
98         switch (cmd.action()) {
99         // Handle the alias case
100         case LFUN_INSET_MODIFY:
101                 if (cmd.getArg(0) == "changetype") {
102                         string cmdname = getCmdName();
103                         string const alias = buffer().params().getCiteAlias(cmdname);
104                         if (!alias.empty())
105                                 cmdname = alias;
106                         string const newtype = cmd.getArg(1);
107                         status.setEnabled(isCompatibleCommand(newtype));
108                         status.setOnOff(newtype == cmdname);
109                 }
110                 status.setEnabled(true);
111                 return true;
112         default:
113                 return InsetCommand::getStatus(cur, cmd, status);
114         }
115 }
116
117
118 bool InsetCitation::addKey(string const & key)
119 {
120         docstring const ukey = from_utf8(key);
121         docstring const & curkeys = getParam("key");
122         if (curkeys.empty()) {
123                 setParam("key", ukey);
124                 cache.recalculate = true;
125                 return true;
126         }
127
128         vector<docstring> keys = getVectorFromString(curkeys);
129         vector<docstring>::const_iterator it = keys.begin();
130         vector<docstring>::const_iterator en = keys.end();
131         for (; it != en; ++it) {
132                 if (*it == ukey) {
133                         LYXERR0("Key " << key << " already present.");
134                         return false;
135                 }
136         }
137         keys.push_back(ukey);
138         setParam("key", getStringFromVector(keys));
139         cache.recalculate = true;
140         return true;
141 }
142
143
144 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
145 {
146         Buffer const & buf = bv.buffer();
147         // Only after the buffer is loaded from file...
148         if (!buf.isFullyLoaded())
149                 return docstring();
150
151         BiblioInfo const & bi = buf.masterBibInfo();
152         if (bi.empty())
153                 return _("No bibliography defined!");
154
155         docstring const & key = getParam("key");
156         if (key.empty())
157                 return _("No citations selected!");
158
159         CiteItem ci;
160         ci.richtext = true;
161         vector<docstring> keys = getVectorFromString(key);
162         if (keys.size() == 1)
163                 return bi.getInfo(keys[0], buffer(), ci);
164
165         docstring tip;
166         tip += "<ol>";
167         for (docstring const & key : keys) {
168                 docstring const key_info = bi.getInfo(key, buffer(), ci);
169                 if (key_info.empty())
170                         continue;
171                 tip += "<li>" + key_info + "</li>";
172         }
173         tip += "</ol>";
174         return tip;
175 }
176
177
178 namespace {
179
180
181 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
182                                   vector<CitationStyle> const & valid_styles)
183 {
184         CitationStyle cs = valid_styles[0];
185         cs.forceUpperCase = false;
186         cs.hasStarredVersion = false;
187
188         string normalized_input = input;
189         string::size_type const n = input.size() - 1;
190         if (isUpperCase(input[0]))
191                 normalized_input[0] = lowercase(input[0]);
192         if (input[n] == '*')
193                 normalized_input = normalized_input.substr(0, n);
194
195         string const alias = bp.getCiteAlias(normalized_input);
196         if (!alias.empty())
197                 normalized_input = alias;
198
199         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
200         vector<CitationStyle>::const_iterator end = valid_styles.end();
201         for (; it != end; ++it) {
202                 CitationStyle this_cs = *it;
203                 if (this_cs.name == normalized_input) {
204                         cs = *it;
205                         break;
206                 }
207         }
208
209         cs.forceUpperCase &= input[0] == uppercase(input[0]);
210         cs.hasStarredVersion &= input[n] == '*';
211
212         return cs;
213 }
214
215
216 inline docstring wrapCitation(docstring const & key,
217                 docstring const & content, bool for_xhtml)
218 {
219         if (!for_xhtml)
220                 return content;
221         // we have to do the escaping here, because we will ultimately
222         // write this as a raw string, so as not to escape the tags.
223         return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
224                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
225 }
226
227 } // anonymous namespace
228
229 docstring InsetCitation::generateLabel(bool for_xhtml) const
230 {
231         docstring label;
232         label = complexLabel(for_xhtml);
233
234         // Fallback to fail-safe
235         if (label.empty())
236                 label = basicLabel(for_xhtml);
237
238         return label;
239 }
240
241
242 docstring InsetCitation::complexLabel(bool for_xhtml) const
243 {
244         Buffer const & buf = buffer();
245         // Only start the process off after the buffer is loaded from file.
246         if (!buf.isFullyLoaded())
247                 return docstring();
248
249         BiblioInfo const & biblist = buf.masterBibInfo();
250         if (biblist.empty())
251                 return docstring();
252
253         docstring const & key = getParam("key");
254         if (key.empty())
255                 return _("No citations selected!");
256
257         // We don't currently use the full or forceUCase fields.
258         string cite_type = getCmdName();
259         if (isUpperCase(cite_type[0]))
260                 // If we were going to use them, this would mean ForceUCase
261                 cite_type[0] = lowercase(cite_type[0]);
262         if (cite_type[cite_type.size() - 1] == '*')
263                 // and this would mean FULL
264                 cite_type = cite_type.substr(0, cite_type.size() - 1);
265
266         // handle alias
267         string const alias = buf.params().getCiteAlias(cite_type);
268         if (!alias.empty())
269                 cite_type = alias;
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         CiteItem ci;
279         ci.textBefore = getParam("before");
280         ci.textAfter = getParam("after");
281         ci.max_size = UINT_MAX;
282         if (for_xhtml) {
283                 ci.max_key_size = UINT_MAX;
284                 ci.context = CiteItem::Export;
285         }
286         ci.richtext = for_xhtml;
287         label = biblist.getLabel(keys, buffer(), cite_type, ci);
288         return label;
289 }
290
291
292 docstring InsetCitation::basicLabel(bool for_xhtml) const
293 {
294         docstring keys = getParam("key");
295         docstring label;
296
297         docstring key;
298         do {
299                 // if there is no comma, then everything goes into key
300                 // and keys will be empty.
301                 keys = trim(split(keys, key, ','));
302                 key = trim(key);
303                 if (!label.empty())
304                         label += ", ";
305                 label += wrapCitation(key, key, for_xhtml);
306         } while (!keys.empty());
307
308         docstring const & after = getParam("after");
309         if (!after.empty())
310                 label += ", " + after;
311
312         return '[' + label + ']';
313 }
314
315 docstring InsetCitation::screenLabel() const
316 {
317         return cache.screen_label;
318 }
319
320
321 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
322 {
323         if (!cache.recalculate && buffer().citeLabelsValid())
324                 return;
325         // The label may have changed, so we have to re-create it.
326         docstring const glabel = generateLabel();
327         cache.recalculate = false;
328         cache.generated_label = glabel;
329         unsigned int const maxLabelChars = 45;
330         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
331         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
332 }
333
334
335 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
336                                                          UpdateType) const
337 {
338         // NOTE
339         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
340         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
341         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
342         // then we will also need to change that routine.
343         docstring const tocitem = getParam("key");
344         shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
345         toc->push_back(TocItem(cpit, 0, tocitem, output_active));
346 }
347
348
349 int InsetCitation::plaintext(odocstringstream & os,
350        OutputParams const &, size_t) const
351 {
352         string const & cmd = getCmdName();
353         if (cmd == "nocite")
354                 return 0;
355
356         docstring const label = generateLabel(false);
357         os << label;
358         return label.size();
359 }
360
361
362 static docstring const cleanupWhitespace(docstring const & citelist)
363 {
364         docstring::const_iterator it  = citelist.begin();
365         docstring::const_iterator end = citelist.end();
366         // Paranoia check: make sure that there is no whitespace in here
367         // -- at least not behind commas or at the beginning
368         docstring result;
369         char_type last = ',';
370         for (; it != end; ++it) {
371                 if (*it != ' ')
372                         last = *it;
373                 if (*it != ' ' || last != ',')
374                         result += *it;
375         }
376         return result;
377 }
378
379
380 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
381 {
382         os << from_ascii("<citation>")
383            << cleanupWhitespace(getParam("key"))
384            << from_ascii("</citation>");
385         return 0;
386 }
387
388
389 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
390 {
391         string const & cmd = getCmdName();
392         if (cmd == "nocite")
393                 return docstring();
394
395         // have to output this raw, because generateLabel() will include tags
396         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
397
398         return docstring();
399 }
400
401
402 void InsetCitation::toString(odocstream & os) const
403 {
404         odocstringstream ods;
405         plaintext(ods, OutputParams(0));
406         os << ods.str();
407 }
408
409
410 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
411 {
412         os += screenLabel();
413 }
414
415
416 // Have to overwrite the default InsetCommand method in order to check that
417 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
418 // citations and then changes his mind, turning natbib support off. The output
419 // should revert to the default citation command as provided by the citation
420 // engine, e.g. \cite[]{} for the basic engine.
421 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
422 {
423         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
424         CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
425         BiblioInfo const & bi = buffer().masterBibInfo();
426         // FIXME UNICODE
427         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
428
429         if (runparams.inulemcmd > 0)
430                 os << "\\mbox{";
431
432         os << "\\" << cite_str;
433
434         docstring const & before = getParam("before");
435         docstring const & after  = getParam("after");
436         if (!before.empty() && cs.textBefore)
437                 os << '[' << before << "][" << after << ']';
438         else if (!after.empty() && cs.textAfter)
439                 os << '[' << after << ']';
440
441         if (!bi.isBibtex(getParam("key")))
442                 // escape chars with bibitems
443                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
444         else
445                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
446
447         if (runparams.inulemcmd)
448                 os << "}";
449 }
450
451
452 string InsetCitation::contextMenuName() const
453 {
454         return "context-citation";
455 }
456
457
458 } // namespace lyx