]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Count words in hyperlink
[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 "Citation.h"
22 #include "DispatchResult.h"
23 #include "FuncCode.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "LyX.h"
28 #include "LyXRC.h"
29 #include "output_xhtml.h"
30 #include "output_docbook.h"
31 #include "ParIterator.h"
32 #include "texstream.h"
33 #include "TocBackend.h"
34
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/FileNameList.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40
41 #include <algorithm>
42 #include <climits>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48
49 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
50         : InsetCommand(buf, p)
51 {
52         buffer().removeBiblioTempFiles();
53 }
54
55
56 InsetCitation::~InsetCitation()
57 {
58         if (isBufferLoaded())
59                 /* We do not use buffer() because Coverity believes that this
60                  * may throw an exception. Actually this code path is not
61                  * taken when buffer_ == 0 */
62                 buffer_->removeBiblioTempFiles();
63 }
64
65
66 // May well be over-ridden when session settings are loaded
67 // in GuiCitation. Unfortunately, that will not happen until
68 // such a dialog is created.
69 bool InsetCitation::last_literal = true;
70
71
72 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
73 {
74         static ParamInfo param_info_;
75
76         // standard cite does only take one argument, but biblatex, jurabib
77         // and natbib extend this to two arguments, so
78         // we have to allow both here. InsetCitation takes care that
79         // LaTeX output is nevertheless correct.
80         if (param_info_.empty()) {
81                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
82                                 ParamInfo::HANDLING_LATEXIFY);
83                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
84                                 ParamInfo::HANDLING_LATEXIFY);
85                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
86                 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
87                                 ParamInfo::HANDLING_LATEXIFY);
88                 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
89                                 ParamInfo::HANDLING_LATEXIFY);
90                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
91         }
92         return param_info_;
93 }
94
95
96 // We allow any command here, since we fall back to cite
97 // anyway if a command is not allowed by a style
98 bool InsetCitation::isCompatibleCommand(string const &)
99 {
100         return true;
101 }
102
103
104 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
105                                   vector<CitationStyle> const & valid_styles) const
106 {
107         CitationStyle cs = valid_styles[0];
108         cs.forceUpperCase = false;
109         cs.hasStarredVersion = false;
110
111         string normalized_input = input;
112         string::size_type const n = input.size() - 1;
113         if (isUpperCase(input[0]))
114                 normalized_input[0] = lowercase(input[0]);
115         if (input[n] == '*')
116                 normalized_input = normalized_input.substr(0, n);
117
118         string const alias = bp.getCiteAlias(normalized_input);
119         if (!alias.empty())
120                 normalized_input = alias;
121
122         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
123         vector<CitationStyle>::const_iterator end = valid_styles.end();
124         for (; it != end; ++it) {
125                 CitationStyle this_cs = *it;
126                 if (this_cs.name == normalized_input) {
127                         cs = *it;
128                         break;
129                 }
130         }
131
132         return cs;
133 }
134
135
136 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
137 {
138         switch (cmd.action()) {
139         case LFUN_INSET_EDIT:
140                 openCitation();
141                 break;
142         case LFUN_INSET_MODIFY: {
143                 buffer().removeBiblioTempFiles();
144                 cache.recalculate = true;
145                 if (cmd.getArg(0) == "toggleparam") {
146                         string cmdname = getCmdName();
147                         string const alias =
148                                 buffer().masterParams().getCiteAlias(cmdname);
149                         if (!alias.empty())
150                                 cmdname = alias;
151                         string const par = cmd.getArg(1);
152                         string newcmdname = cmdname;
153                         if (par == "star") {
154                                 if (suffixIs(cmdname, "*"))
155                                         newcmdname = rtrim(cmdname, "*");
156                                 else
157                                         newcmdname = cmdname + "*";
158                         } else if (par == "casing") {
159                                 if (isUpperCase(cmdname[0]))
160                                         newcmdname[0] = lowercase(cmdname[0]);
161                                 else
162                                         newcmdname[0] = uppercase(newcmdname[0]);
163                         }
164                         cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
165                 }
166         }
167         // fall through
168         default:
169                 InsetCommand::doDispatch(cur, cmd);
170         }
171 }
172
173 bool InsetCitation::openCitationPossible() const
174 {
175         Buffer const & buf = *buffer_;
176         // only after the buffer is loaded from file...
177         if (!buf.isFullyLoaded())
178                 return false;
179
180         BiblioInfo const & bi = buf.masterBibInfo();
181         if (bi.empty())
182                 return false;
183
184         docstring const & key = getParam("key");
185         if (key.empty())
186                 return false;
187
188         // does bibtex item contains some locator?
189         vector<docstring> keys = getVectorFromString(key);
190         docstring doi, url, file;
191         for (docstring const & kvar : keys) {
192                 bi.getLocators(kvar, doi, url, file);
193                 if (!file.empty() || !doi.empty() || !url.empty())
194                         return true;
195         }
196
197         // last resort: is external script activated?
198         return lyxrc.citation_search;
199 }
200
201 void InsetCitation::openCitation()
202 {
203         Buffer const & buf = *buffer_;
204         BiblioInfo const & bi = buf.masterBibInfo();
205         docstring const & key = getParam("key");
206
207         vector<docstring> keys = getVectorFromString(key);
208         docstring titledata, doi, url, file;
209         for (docstring const & kvar : keys) {
210                 CiteItem ci;
211                 titledata = bi.getInfo(kvar, buffer(), ci,
212                                        from_ascii(lyxrc.citation_search_pattern));
213                 // some cleanup: commas and " and ", as used in name lists,
214                 // are not expected in file names
215                 titledata = subst(titledata, from_ascii(","), docstring());
216                 titledata = subst(titledata, from_ascii(" and "), from_ascii(" "));
217                 bi.getLocators(kvar, doi, url, file);
218                 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
219                         << url << " file:" << file << " title data:" << titledata
220                         << " citation search: " << lyxrc.citation_search
221                         << " citation search pattern: " << lyxrc.citation_search_pattern);
222                 docstring locator;
223                 if (!file.empty()) {
224                         locator = file;
225                 } else if (!doi.empty()) {
226                         locator = doi;
227                 } else if (!url.empty()) {
228                         locator = url;
229                 } else {
230                         locator = "EXTERNAL " + titledata;
231                 }
232                 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
233                 lyx::dispatch(cmd);
234         }
235 }
236
237
238 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
239         FuncStatus & status) const
240 {
241         switch (cmd.action()) {
242         // Handle the alias case
243         case LFUN_INSET_MODIFY:
244                 if (cmd.getArg(0) == "changetype") {
245                         string cmdname = getCmdName();
246                         string const alias =
247                                 buffer().masterParams().getCiteAlias(cmdname);
248                         if (!alias.empty())
249                                 cmdname = alias;
250                         if (suffixIs(cmdname, "*"))
251                                 cmdname = rtrim(cmdname, "*");
252                         string const newtype = cmd.getArg(1);
253                         status.setEnabled(isCompatibleCommand(newtype));
254                         status.setOnOff(newtype == cmdname);
255                 }
256                 if (cmd.getArg(0) == "toggleparam") {
257                         string cmdname = getCmdName();
258                         string const alias =
259                                 buffer().masterParams().getCiteAlias(cmdname);
260                         if (!alias.empty())
261                                 cmdname = alias;
262                         vector<CitationStyle> citation_styles =
263                                 buffer().masterParams().citeStyles();
264                         CitationStyle cs = getCitationStyle(buffer().masterParams(),
265                                                             cmdname, citation_styles);
266                         if (cmd.getArg(1) == "star") {
267                                 status.setEnabled(cs.hasStarredVersion);
268                                 status.setOnOff(suffixIs(cmdname, "*"));
269                         }
270                         else if (cmd.getArg(1) == "casing") {
271                                 status.setEnabled(cs.forceUpperCase);
272                                 status.setOnOff(isUpperCase(cmdname[0]));
273                         }
274                 }
275                 return true;
276         case LFUN_INSET_EDIT:
277                 return openCitationPossible();
278         default:
279                 return InsetCommand::getStatus(cur, cmd, status);
280         }
281 }
282
283
284 bool InsetCitation::addKey(string const & key)
285 {
286         docstring const ukey = from_utf8(key);
287         docstring const & curkeys = getParam("key");
288         if (curkeys.empty()) {
289                 setParam("key", ukey);
290                 cache.recalculate = true;
291                 return true;
292         }
293
294         vector<docstring> keys = getVectorFromString(curkeys);
295         vector<docstring>::const_iterator it = keys.begin();
296         vector<docstring>::const_iterator en = keys.end();
297         for (; it != en; ++it) {
298                 if (*it == ukey) {
299                         LYXERR0("Key " << key << " already present.");
300                         return false;
301                 }
302         }
303         keys.push_back(ukey);
304         setParam("key", getStringFromVector(keys));
305         cache.recalculate = true;
306         return true;
307 }
308
309
310 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
311 {
312         Buffer const & buf = bv.buffer();
313         // Only after the buffer is loaded from file...
314         if (!buf.isFullyLoaded())
315                 return docstring();
316
317         BiblioInfo const & bi = buf.masterBibInfo();
318         if (bi.empty())
319                 return _("No bibliography defined!");
320
321         docstring const & key = getParam("key");
322         if (key.empty())
323                 return _("No citations selected!");
324
325         CiteItem ci;
326         ci.richtext = true;
327         vector<docstring> keys = getVectorFromString(key);
328         if (keys.size() == 1)
329                 return bi.getInfo(keys[0], buffer(), ci);
330
331         docstring tip;
332         tip += "<ol>";
333         int count = 0;
334         for (docstring const & kvar : keys) {
335                 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
336                 // limit to reasonable size.
337                 if (count > 9 && keys.size() > 11) {
338                         tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
339                         tip += "<p>"
340                                 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
341                                 + "</p>";
342                         break;
343                 }
344                 if (key_info.empty())
345                         continue;
346                 tip += "<li>" + key_info + "</li>";
347                 ++count;
348         }
349         tip += "</ol>";
350         return tip;
351 }
352
353
354 namespace {
355
356 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
357                                   vector<CitationStyle> const & valid_styles)
358 {
359         CitationStyle cs = valid_styles[0];
360         cs.forceUpperCase = false;
361         cs.hasStarredVersion = false;
362
363         string normalized_input = input;
364         string::size_type const n = input.size() - 1;
365         if (isUpperCase(input[0]))
366                 normalized_input[0] = lowercase(input[0]);
367         if (input[n] == '*')
368                 normalized_input = normalized_input.substr(0, n);
369
370         string const alias = bp.getCiteAlias(normalized_input);
371         if (!alias.empty())
372                 normalized_input = alias;
373
374         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
375         vector<CitationStyle>::const_iterator end = valid_styles.end();
376         for (; it != end; ++it) {
377                 CitationStyle this_cs = *it;
378                 if (this_cs.name == normalized_input) {
379                         cs = *it;
380                         break;
381                 }
382         }
383
384         cs.forceUpperCase &= input[0] == uppercase(input[0]);
385         cs.hasStarredVersion &= input[n] == '*';
386
387         return cs;
388 }
389
390
391 inline docstring wrapCitation(docstring const & key,
392                 docstring const & content, bool for_xhtml)
393 {
394         if (!for_xhtml)
395                 return content;
396         // we have to do the escaping here, because we will ultimately
397         // write this as a raw string, so as not to escape the tags.
398         return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
399                         xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
400 }
401
402 } // anonymous namespace
403
404
405 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
406 {
407         vector<docstring> ps =
408                 getVectorFromString(p, from_ascii("\t"));
409         QualifiedList res;
410         for (docstring const & s: ps) {
411                 docstring key = s;
412                 docstring val;
413                 if (contains(s, ' '))
414                         val = split(s, key, ' ');
415                 res.push_back(make_pair(key, val));
416         }
417         return res;
418 }
419
420 docstring InsetCitation::generateLabel(bool for_xhtml) const
421 {
422         docstring label;
423         label = complexLabel(for_xhtml);
424
425         // Fallback to fail-safe
426         if (label.empty())
427                 label = basicLabel(for_xhtml);
428
429         return label;
430 }
431
432
433 docstring InsetCitation::complexLabel(bool for_xhtml) const
434 {
435         Buffer const & buf = buffer();
436         // Only start the process off after the buffer is loaded from file.
437         if (!buf.isFullyLoaded())
438                 return docstring();
439
440         docstring const & key = getParam("key");
441
442         BiblioInfo const & biblist = buf.masterBibInfo();
443
444         // mark broken citations
445         setBroken(false);
446
447         if (biblist.empty()) {
448                 setBroken(true);
449                 return docstring();
450         }
451
452         if (key.empty())
453                 return _("No citations selected!");
454
455         // check all citations
456         // we only really want the last 'false', to suppress trimming, but
457         // we need to give the other defaults, too, to set it.
458         vector<docstring> keys =
459                 getVectorFromString(key, from_ascii(","), false, false);
460         for (auto const & k : keys) {
461                 if (biblist.find(k) == biblist.end()) {
462                         setBroken(true);
463                         break;
464                 }
465         }
466         
467         string cite_type = getCmdName();
468         bool const uppercase = isUpperCase(cite_type[0]);
469         if (uppercase)
470                 cite_type[0] = lowercase(cite_type[0]);
471         bool const starred = (cite_type[cite_type.size() - 1] == '*');
472         if (starred)
473                 cite_type = cite_type.substr(0, cite_type.size() - 1);
474
475         // handle alias
476         string const alias = buf.masterParams().getCiteAlias(cite_type);
477         if (!alias.empty())
478                 cite_type = alias;
479
480         // FIXME: allow to add cite macros
481         /*
482         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
483         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
484         */
485         docstring label;
486         CitationStyle cs = getCitationStyle(buffer().masterParams(),
487                         cite_type, buffer().masterParams().citeStyles());
488         bool const qualified = cs.hasQualifiedList
489                 && (keys.size() > 1
490                     || !getParam("pretextlist").empty()
491                     || !getParam("posttextlist").empty());
492         QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
493         QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
494
495         CiteItem ci;
496         ci.textBefore = getParam("before");
497         ci.textAfter = getParam("after");
498         ci.forceUpperCase = uppercase;
499         ci.Starred = starred;
500         ci.max_size = UINT_MAX;
501         ci.isQualified = qualified;
502         ci.pretexts = pres;
503         ci.posttexts = posts;
504         if (for_xhtml) {
505                 ci.max_key_size = UINT_MAX;
506                 ci.context = CiteItem::Export;
507         }
508         ci.richtext = for_xhtml;
509         label = biblist.getLabel(keys, buffer(), cite_type, ci);
510         return label;
511 }
512
513
514 docstring InsetCitation::basicLabel(bool for_xhtml) const
515 {
516         docstring keys = getParam("key");
517         docstring label;
518
519         docstring key;
520         do {
521                 // if there is no comma, then everything goes into key
522                 // and keys will be empty.
523                 keys = split(keys, key, ',');
524                 if (!label.empty())
525                         label += ", ";
526                 label += wrapCitation(key, key, for_xhtml);
527         } while (!keys.empty());
528
529         docstring const & after = getParam("after");
530         if (!after.empty())
531                 label += ", " + after;
532
533         return '[' + label + ']';
534 }
535
536
537 bool InsetCitation::forceLTR(OutputParams const & rp) const
538 {
539         // We have to force LTR for numeric references
540         // [= bibliography, plain BibTeX, numeric natbib
541         // and biblatex]. Except for XeTeX/bidi. See #3005.
542         if (rp.useBidiPackage())
543                 return false;
544         return (buffer().masterParams().citeEngine() == "basic"
545                 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
546 }
547
548 docstring InsetCitation::screenLabel() const
549 {
550         return cache.screen_label;
551 }
552
553
554 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
555 {
556         if (!cache.recalculate && buffer().citeLabelsValid())
557                 return;
558         // The label may have changed, so we have to re-create it.
559         docstring const glabel = generateLabel();
560         cache.recalculate = false;
561         cache.generated_label = glabel;
562         unsigned int const maxLabelChars = 45;
563         cache.screen_label = glabel;
564         support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
565 }
566
567
568 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
569                                                          UpdateType, TocBackend & backend) const
570 {
571         // NOTE
572         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
573         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
574         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
575         // then we will also need to change that routine.
576         docstring tocitem;
577         if (isBroken())
578                 tocitem = _("BROKEN: ");
579         tocitem += getParam("key");
580         TocBuilder & b = backend.builder("citation");
581         b.pushItem(cpit, tocitem, output_active);
582         b.pop();
583         if (isBroken()) {
584                 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
585                 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
586         }
587 }
588
589
590 int InsetCitation::plaintext(odocstringstream & os,
591        OutputParams const &, size_t) const
592 {
593         string const & cmd = getCmdName();
594         if (cmd == "nocite")
595                 return 0;
596
597         docstring const label = generateLabel();
598         os << label;
599         return label.size();
600 }
601
602
603 static docstring const cleanupWhitespace(docstring const & citelist)
604 {
605         docstring::const_iterator it  = citelist.begin();
606         docstring::const_iterator end = citelist.end();
607         // Paranoia check: make sure that there is no whitespace in here
608         // -- at least not behind commas or at the beginning
609         docstring result;
610         char_type last = ',';
611         for (; it != end; ++it) {
612                 if (*it != ' ')
613                         last = *it;
614                 if (*it != ' ' || last != ',')
615                         result += *it;
616         }
617         return result;
618 }
619
620
621 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
622 {
623         if (getCmdName() == "nocite")
624                 return;
625
626         // Split the different citations (on ","), so that one tag can be output for each of them.
627         // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
628         docstring citations = getParam("key");
629         if (citations.find(',') == string::npos) {
630                 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
631         } else {
632                 size_t pos = 0;
633                 while (pos != string::npos) {
634                         pos = citations.find(',');
635                         xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
636                         citations.erase(0, pos + 1);
637
638                         if (pos != string::npos) {
639                                 xs << ", "; 
640                         }
641                 }
642         }
643 }
644
645
646 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
647 {
648         if (getCmdName() == "nocite")
649                 return docstring();
650
651         // have to output this raw, because generateLabel() will include tags
652         xs << XMLStream::ESCAPE_NONE << generateLabel(true);
653
654         return docstring();
655 }
656
657
658 void InsetCitation::toString(odocstream & os) const
659 {
660         odocstringstream ods;
661         plaintext(ods, OutputParams(nullptr));
662         os << ods.str();
663 }
664
665
666 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
667 {
668         os += screenLabel();
669 }
670
671
672 // Have to overwrite the default InsetCommand method in order to check that
673 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
674 // citations and then changes his mind, turning natbib support off. The output
675 // should revert to the default citation command as provided by the citation
676 // engine, e.g. \cite[]{} for the basic engine.
677 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
678 {
679         // When this is a child compiled on its own, we use the children
680         // own bibinfo, else the master's
681         BiblioInfo const & bi = runparams.is_child
682                         ? buffer().masterBibInfo() : buffer().bibInfo();
683         docstring const key = getParam("key");
684         // "keyonly" command: output the plain key and stop.
685         if (getCmdName() == "keyonly") {
686                 // Special command to only return the key
687                 if (!bi.isBibtex(getParam("key")))
688                         // escape chars with bibitems
689                         os << escape(cleanupWhitespace(key));
690                 else
691                         os << cleanupWhitespace(key);
692                 return;
693         }
694         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
695         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
696                                                getCmdName(), citation_styles);
697         // FIXME UNICODE
698         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
699
700         // check if we have to do a qualified list
701         vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
702         bool const qualified = cs.hasQualifiedList
703                 && (!getParam("pretextlist").empty()
704                     || !getParam("posttextlist").empty());
705
706         if (runparams.inulemcmd > 0)
707                 os << "\\mbox{";
708
709         os << "\\" << cite_str;
710
711         if (qualified)
712                 os << "s";
713
714         ParamInfo const & pinfo = findInfo(string());
715         docstring before = params().prepareCommand(runparams, getParam("before"),
716                                                    pinfo["before"].handling());
717         docstring after = params().prepareCommand(runparams, getParam("after"),
718                                                    pinfo["after"].handling());
719         if (!before.empty() && cs.textBefore) {
720                 if (qualified)
721                         os << '(' << protectArgument(before, '(', ')')
722                            << ")(" << protectArgument(after, '(', ')') << ')';
723                 else
724                         os << '[' << protectArgument(before) << "]["
725                            << protectArgument(after) << ']';
726         } else if (!after.empty() && cs.textAfter) {
727                 if (qualified)
728                         os << '(' << protectArgument(after, '(', ')') << ')';
729                 else
730                         os << '[' << protectArgument(after) << ']';
731         }
732
733         if (!bi.isBibtex(key))
734                 // escape chars with bibitems
735                 os << '{' << escape(cleanupWhitespace(key)) << '}';
736         else {
737                 if (qualified) {
738                         QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
739                         QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
740                         for (docstring const & k : keys) {
741                                 docstring prenote;
742                                 QualifiedList::iterator it = pres.begin();
743                                 for (; it != pres.end() ; ++it) {
744                                         if ((*it).first == k) {
745                                                 prenote = (*it).second;
746                                                 pres.erase(it);
747                                                 break;
748                                         }
749                                 }
750                                 docstring bef = params().prepareCommand(runparams, prenote,
751                                                    pinfo["pretextlist"].handling());
752                                 docstring postnote;
753                                 QualifiedList::iterator pit = posts.begin();
754                                 for (; pit != posts.end() ; ++pit) {
755                                         if ((*pit).first == k) {
756                                                 postnote = (*pit).second;
757                                                 posts.erase(pit);
758                                                 break;
759                                         }
760                                 }
761                                 docstring aft = params().prepareCommand(runparams, postnote,
762                                                    pinfo["posttextlist"].handling());
763                                 if (!bef.empty())
764                                         os << '[' << protectArgument(bef)
765                                            << "][" << protectArgument(aft) << ']';
766                                 else if (!aft.empty())
767                                         os << '[' << protectArgument(aft) << ']';
768                                 os << '{' << k << '}';
769                         }
770                 } else
771                         os << '{' << cleanupWhitespace(key) << '}';
772         }
773
774         if (runparams.inulemcmd)
775                 os << "}";
776 }
777
778
779 pair<int, int> InsetCitation::isWords() const
780 {
781         docstring const label = generateLabel(false);
782         return pair<int, int>(label.size(), wordCount(label));
783 }
784
785
786 string InsetCitation::contextMenuName() const
787 {
788         return "context-citation";
789 }
790
791
792 } // namespace lyx