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