]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Implement display of forceUpperCase
[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         bool const uppercase = isUpperCase(cite_type[0]);
260         if (uppercase)
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.forceUpperCase = uppercase;
282         ci.max_size = UINT_MAX;
283         if (for_xhtml) {
284                 ci.max_key_size = UINT_MAX;
285                 ci.context = CiteItem::Export;
286         }
287         ci.richtext = for_xhtml;
288         label = biblist.getLabel(keys, buffer(), cite_type, ci);
289         return label;
290 }
291
292
293 docstring InsetCitation::basicLabel(bool for_xhtml) const
294 {
295         docstring keys = getParam("key");
296         docstring label;
297
298         docstring key;
299         do {
300                 // if there is no comma, then everything goes into key
301                 // and keys will be empty.
302                 keys = trim(split(keys, key, ','));
303                 key = trim(key);
304                 if (!label.empty())
305                         label += ", ";
306                 label += wrapCitation(key, key, for_xhtml);
307         } while (!keys.empty());
308
309         docstring const & after = getParam("after");
310         if (!after.empty())
311                 label += ", " + after;
312
313         return '[' + label + ']';
314 }
315
316 docstring InsetCitation::screenLabel() const
317 {
318         return cache.screen_label;
319 }
320
321
322 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
323 {
324         if (!cache.recalculate && buffer().citeLabelsValid())
325                 return;
326         // The label may have changed, so we have to re-create it.
327         docstring const glabel = generateLabel();
328         cache.recalculate = false;
329         cache.generated_label = glabel;
330         unsigned int const maxLabelChars = 45;
331         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
332         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
333 }
334
335
336 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
337                                                          UpdateType) const
338 {
339         // NOTE
340         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
341         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
342         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
343         // then we will also need to change that routine.
344         docstring const tocitem = getParam("key");
345         shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
346         toc->push_back(TocItem(cpit, 0, tocitem, output_active));
347 }
348
349
350 int InsetCitation::plaintext(odocstringstream & os,
351        OutputParams const &, size_t) const
352 {
353         string const & cmd = getCmdName();
354         if (cmd == "nocite")
355                 return 0;
356
357         docstring const label = generateLabel(false);
358         os << label;
359         return label.size();
360 }
361
362
363 static docstring const cleanupWhitespace(docstring const & citelist)
364 {
365         docstring::const_iterator it  = citelist.begin();
366         docstring::const_iterator end = citelist.end();
367         // Paranoia check: make sure that there is no whitespace in here
368         // -- at least not behind commas or at the beginning
369         docstring result;
370         char_type last = ',';
371         for (; it != end; ++it) {
372                 if (*it != ' ')
373                         last = *it;
374                 if (*it != ' ' || last != ',')
375                         result += *it;
376         }
377         return result;
378 }
379
380
381 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
382 {
383         os << from_ascii("<citation>")
384            << cleanupWhitespace(getParam("key"))
385            << from_ascii("</citation>");
386         return 0;
387 }
388
389
390 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
391 {
392         string const & cmd = getCmdName();
393         if (cmd == "nocite")
394                 return docstring();
395
396         // have to output this raw, because generateLabel() will include tags
397         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
398
399         return docstring();
400 }
401
402
403 void InsetCitation::toString(odocstream & os) const
404 {
405         odocstringstream ods;
406         plaintext(ods, OutputParams(0));
407         os << ods.str();
408 }
409
410
411 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
412 {
413         os += screenLabel();
414 }
415
416
417 // Have to overwrite the default InsetCommand method in order to check that
418 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
419 // citations and then changes his mind, turning natbib support off. The output
420 // should revert to the default citation command as provided by the citation
421 // engine, e.g. \cite[]{} for the basic engine.
422 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
423 {
424         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
425         CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
426         BiblioInfo const & bi = buffer().masterBibInfo();
427         // FIXME UNICODE
428         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
429
430         if (runparams.inulemcmd > 0)
431                 os << "\\mbox{";
432
433         os << "\\" << cite_str;
434
435         docstring const & before = getParam("before");
436         docstring const & after  = getParam("after");
437         if (!before.empty() && cs.textBefore)
438                 os << '[' << before << "][" << after << ']';
439         else if (!after.empty() && cs.textAfter)
440                 os << '[' << after << ']';
441
442         if (!bi.isBibtex(getParam("key")))
443                 // escape chars with bibitems
444                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
445         else
446                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
447
448         if (runparams.inulemcmd)
449                 os << "}";
450 }
451
452
453 string InsetCitation::contextMenuName() const
454 {
455         return "context-citation";
456 }
457
458
459 } // namespace lyx