]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
QDialogButtonBox for the remaining dialogs.
[lyx.git] / src / frontends / qt4 / Menus.cpp
1 /**
2  * \file qt4/Menus.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Asger Alstrup
8  * \author Lars Gullik Bjønnes
9  * \author Jean-Marc Lasgouttes
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Martin Vermeer
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "Menus.h"
20
21 #include "Action.h"
22 #include "GuiApplication.h"
23 #include "GuiView.h"
24 #include "GuiWorkArea.h"
25 #include "qt_helpers.h"
26
27 #include "BiblioInfo.h"
28 #include "BranchList.h"
29 #include "Buffer.h"
30 #include "BufferList.h"
31 #include "BufferParams.h"
32 #include "BufferView.h"
33 #include "Converter.h"
34 #include "CutAndPaste.h"
35 #include "Floating.h"
36 #include "FloatList.h"
37 #include "Format.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "IndicesList.h"
41 #include "KeyMap.h"
42 #include "Language.h"
43 #include "Layout.h"
44 #include "Lexer.h"
45 #include "LyXAction.h"
46 #include "LyX.h"
47 #include "LyXRC.h"
48 #include "lyxfind.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "Session.h"
53 #include "SpellChecker.h"
54 #include "TextClass.h"
55 #include "Text.h"
56 #include "TocBackend.h"
57 #include "Toolbars.h"
58 #include "WordLangTuple.h"
59
60 #include "insets/Inset.h"
61 #include "insets/InsetCitation.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetQuotes.h"
64
65 #include "support/lassert.h"
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/docstring_list.h"
69 #include "support/filetools.h"
70 #include "support/gettext.h"
71 #include "support/lstrings.h"
72
73 #include <QCursor>
74 #include <QHash>
75 #include <QList>
76 #include <QMenuBar>
77 #include <QString>
78 #if QT_VERSION >= 0x040600
79 #include <QProxyStyle>
80 #endif
81
82 #include <algorithm>
83 #include <memory>
84 #include <vector>
85
86 using namespace std;
87 using namespace lyx::support;
88
89
90 namespace lyx {
91 namespace frontend {
92
93 namespace {
94
95 // MacOSX specific stuff is at the end.
96
97 class MenuDefinition;
98
99 ///
100 class MenuItem {
101 public:
102         /// The type of elements that can be in a menu
103         enum Kind {
104                 ///
105                 Command,
106                 ///
107                 Submenu,
108                 ///
109                 Separator,
110                 /** This type of item explains why something is unavailable. If this
111                     menuitem is in a submenu, the submenu is enabled to make sure the
112                     user sees the information. */
113                 Help,
114                 /** This type of item merely shows that there might be a list or
115                     something alike at this position, but the list is still empty.
116                     If this item is in a submenu, the submenu will not always be
117                     enabled. */
118                 Info,
119                 /** This is the list of last opened file,
120                     typically for the File menu. */
121                 Lastfiles,
122                 /** This is the list of opened Documents,
123                     typically for the Documents menu. */
124                 Documents,
125                 /** This is the bookmarks */
126                 Bookmarks,
127                 ///
128                 Toc,
129                 /** This is a list of viewable formats
130                     typically for the File->View menu. */
131                 ViewFormats,
132                 /** This is a list of updatable formats
133                     typically for the File->Update menu. */
134                 UpdateFormats,
135                 /** This is a list of exportable formats
136                     typically for the File->Export menu. */
137                 ExportFormats,
138                 /** This exports the document default format
139                     typically for the File->Export menu. */
140                 ExportFormat,
141                 /** This is a list of importable formats
142                     typically for the File->Import menu. */
143                 ImportFormats,
144                 /** This is the list of elements available
145                  * for insertion into document. */
146                 CharStyles,
147                 /** This is the list of user-configurable
148                 insets to insert into document */
149                 Custom,
150                 /** This is the list of XML elements to
151                 insert into the document */
152                 Elements,
153                 /** This is the list of floats that we can
154                     insert a list for. */
155                 FloatListInsert,
156                 /** This is the list of floats that we can
157                     insert. */
158                 FloatInsert,
159                 /** This is the list of selections that can
160                     be pasted. */
161                 PasteRecent,
162                 /** toolbars */
163                 Toolbars,
164                 /** Available branches in document */
165                 Branches,
166                 /** Available indices in document */
167                 Indices,
168                 /** Context menu for indices in document */
169                 IndicesContext,
170                 /** Available index lists in document */
171                 IndicesLists,
172                 /** Context menu for available indices lists in document */
173                 IndicesListsContext,
174                 /** Available citation styles for a given citation */
175                 CiteStyles,
176                 /** Available graphics groups */
177                 GraphicsGroups,
178                 /// Words suggested by the spellchecker.
179                 SpellingSuggestions,
180                 /** Used Languages */
181                 LanguageSelector,
182                 /** This is the list of arguments available
183                     for insertion into the current layout. */
184                 Arguments,
185                 /** This is the list of arguments available
186                     in the InsetArgument context menu. */
187                 SwitchArguments,
188                 /** This is the list of captions available
189                 in the current layout. */
190                 Captions,
191                 /** This is the list of captions available
192                 in the InsetCaption context menu. */
193                 SwitchCaptions,
194                 /** Commands to separate environments. */
195                 EnvironmentSeparators,
196                 /** Commands to separate environments (context menu version). */
197                 EnvironmentSeparatorsContext,
198                 /** This is the list of quotation marks available */
199                 SwitchQuotes
200         };
201
202         explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
203
204         MenuItem(Kind kind,
205                  QString const & label,
206                  QString const & submenu = QString(),
207                  QString const & tooltip = QString(),
208                  bool optional = false)
209                 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
210                   submenuname_(submenu), tooltip_(tooltip), optional_(optional)
211         {
212                 LATTEST(kind == Submenu || kind == Help || kind == Info);
213         }
214
215         MenuItem(Kind kind,
216                  QString const & label,
217                  FuncRequest const & func,
218                  QString const & tooltip = QString(),
219                  bool optional = false,
220                  FuncRequest::Origin origin = FuncRequest::MENU)
221                 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
222                   tooltip_(tooltip), optional_(optional)
223         {
224                 func_->setOrigin(origin);
225         }
226
227         /// The label of a given menuitem
228         QString label() const
229         {
230                 int const index = label_.lastIndexOf('|');
231                 return index == -1 ? label_ : label_.left(index);
232         }
233
234         /// The keyboard shortcut (usually underlined in the entry)
235         QString shortcut() const
236         {
237                 int const index = label_.lastIndexOf('|');
238                 return index == -1 ? QString() : label_.mid(index + 1);
239         }
240         /// The complete label, with label and shortcut separated by a '|'
241         QString fulllabel() const { return label_; }
242         /// The kind of entry
243         Kind kind() const { return kind_; }
244         /// the action (if relevant)
245         shared_ptr<FuncRequest const> func() const { return func_; }
246         /// the tooltip
247         QString const & tooltip() const { return tooltip_; }
248         /// returns true if the entry should be omitted when disabled
249         bool optional() const { return optional_; }
250         /// returns the status of the lfun associated with this entry
251         FuncStatus const & status() const { return status_; }
252         /// returns the status of the lfun associated with this entry
253         FuncStatus & status() { return status_; }
254         /// returns the status of the lfun associated with this entry
255         void status(FuncStatus const & status) { status_ = status; }
256
257         ///returns the binding associated to this action.
258         QString binding() const
259         {
260                 if (kind_ != Command)
261                         return QString();
262                 // Get the keys bound to this action, but keep only the
263                 // first one later
264                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
265                 if (!bindings.empty())
266                         return toqstr(bindings.begin()->print(KeySequence::ForGui));
267
268                 LYXERR(Debug::KBMAP, "No binding for "
269                         << lyxaction.getActionName(func_->action())
270                         << '(' << func_->argument() << ')');
271                 return QString();
272         }
273
274         /// the description of the  submenu (if relevant)
275         QString const & submenuname() const { return submenuname_; }
276         /// set the description of the  submenu
277         void submenuname(QString const & name) { submenuname_ = name; }
278         ///
279         bool hasSubmenu() const { return !submenu_.isEmpty(); }
280         ///
281         MenuDefinition const & submenu() const { return submenu_.at(0); }
282         MenuDefinition & submenu() { return submenu_[0]; }
283         ///
284         void setSubmenu(MenuDefinition const & menu)
285         {
286                 submenu_.clear();
287                 submenu_.append(menu);
288         }
289
290 private:
291         ///
292         Kind kind_;
293         ///
294         QString label_;
295         ///
296         shared_ptr<FuncRequest> func_;// non-null
297         ///
298         QString submenuname_;
299         ///
300         QString tooltip_;
301         ///
302         bool optional_;
303         ///
304         FuncStatus status_;
305         /// contains 0 or 1 item.
306         QList<MenuDefinition> submenu_;
307 };
308
309 ///
310 class MenuDefinition {
311 public:
312         ///
313         typedef std::vector<MenuItem> ItemList;
314         ///
315         typedef ItemList::const_iterator const_iterator;
316         ///
317         explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
318
319         ///
320         void read(Lexer &);
321         ///
322         QString const & name() const { return name_; }
323         ///
324         bool empty() const { return items_.empty(); }
325         /// Clear the menu content.
326         void clear() { items_.clear(); }
327         ///
328         size_t size() const { return items_.size(); }
329         ///
330         const_iterator begin() const { return items_.begin(); }
331         ///
332         const_iterator end() const { return items_.end(); }
333         ///
334         void cat(MenuDefinition const & other);
335         ///
336         void catSub(docstring const & name);
337
338         // search for func in this menu iteratively, and put menu
339         // names in a stack.
340         bool searchMenu(FuncRequest const & func, docstring_list & names)
341                 const;
342         ///
343         bool hasFunc(FuncRequest const &) const;
344         /// Add the menu item unconditionally
345         void add(MenuItem const & item) { items_.push_back(item); }
346         /// Checks the associated FuncRequest status before adding the
347         /// menu item.
348         void addWithStatusCheck(MenuItem const &);
349         // Check whether the menu shortcuts are unique
350         void checkShortcuts() const;
351         ///
352         void expandLastfiles();
353         void expandDocuments();
354         void expandBookmarks();
355         void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
356         void expandFloatListInsert(Buffer const * buf);
357         void expandFloatInsert(Buffer const * buf);
358         void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
359         void expandTocSubmenu(std::string const & type, Toc const & toc_list);
360         void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
361         void expandToc(Buffer const * buf);
362         void expandPasteRecent(Buffer const * buf);
363         void expandToolbars();
364         void expandBranches(Buffer const * buf);
365         void expandIndices(Buffer const * buf, bool listof = false);
366         void expandIndicesContext(Buffer const * buf, bool listof = false);
367         void expandCiteStyles(BufferView const *);
368         void expandGraphicsGroups(BufferView const *);
369         void expandSpellingSuggestions(BufferView const *);
370         void expandLanguageSelector(Buffer const * buf);
371         void expandArguments(BufferView const *, bool switcharg = false);
372         void expandCaptions(Buffer const * buf, bool switchcap = false);
373         void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
374         void expandQuotes(BufferView const *);
375         ///
376         ItemList items_;
377         ///
378         QString name_;
379 };
380
381
382 /// Helper for std::find_if
383 class MenuNamesEqual
384 {
385 public:
386         MenuNamesEqual(QString const & name) : name_(name) {}
387         bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
388 private:
389         QString name_;
390 };
391
392
393 ///
394 typedef std::vector<MenuDefinition> MenuList;
395 ///
396 typedef MenuList::const_iterator const_iterator;
397 ///
398 typedef MenuList::iterator iterator;
399
400 /////////////////////////////////////////////////////////////////////
401 // MenuDefinition implementation
402 /////////////////////////////////////////////////////////////////////
403
404 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
405 {
406         switch (i.kind()) {
407
408         case MenuItem::Command: {
409                 FuncStatus status = lyx::getStatus(*i.func());
410                 if (status.unknown() || (!status.enabled() && i.optional()))
411                         break;
412                 items_.push_back(i);
413                 items_.back().status(status);
414                 break;
415         }
416
417         case MenuItem::Submenu: {
418                 bool enabled = false;
419                 if (i.hasSubmenu()) {
420                         for (const_iterator cit = i.submenu().begin();
421                                   cit != i.submenu().end(); ++cit) {
422                                 // Only these kind of items affect the status of the submenu
423                                 if ((cit->kind() == MenuItem::Command
424                                      || cit->kind() == MenuItem::Submenu
425                                      || cit->kind() == MenuItem::Help)
426                                     && cit->status().enabled()) {
427                                         enabled = true;
428                                         break;
429                                 }
430                         }
431                 }
432                 if (enabled || !i.optional()) {
433                         items_.push_back(i);
434                         items_.back().status().setEnabled(enabled);
435                 }
436                 break;
437         }
438
439         case MenuItem::Separator:
440                 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
441                         items_.push_back(i);
442                 break;
443
444         default:
445                 items_.push_back(i);
446         }
447 }
448
449
450 void MenuDefinition::read(Lexer & lex)
451 {
452         enum {
453                 md_item = 1,
454                 md_branches,
455                 md_citestyles,
456                 md_documents,
457                 md_bookmarks,
458                 md_charstyles,
459                 md_custom,
460                 md_elements,
461                 md_endmenu,
462                 md_exportformat,
463                 md_exportformats,
464                 md_importformats,
465                 md_indices,
466                 md_indicescontext,
467                 md_indiceslists,
468                 md_indiceslistscontext,
469                 md_lastfiles,
470                 md_optitem,
471                 md_optsubmenu,
472                 md_separator,
473                 md_submenu,
474                 md_toc,
475                 md_updateformats,
476                 md_viewformats,
477                 md_floatlistinsert,
478                 md_floatinsert,
479                 md_pasterecent,
480                 md_toolbars,
481                 md_graphicsgroups,
482                 md_spellingsuggestions,
483                 md_languageselector,
484                 md_arguments,
485                 md_switcharguments,
486                 md_captions,
487                 md_switchcaptions,
488                 md_env_separators,
489                 md_env_separatorscontext,
490                 md_switchquotes
491         };
492
493         LexerKeyword menutags[] = {
494                 { "arguments", md_arguments },
495                 { "bookmarks", md_bookmarks },
496                 { "branches", md_branches },
497                 { "captions", md_captions },
498                 { "charstyles", md_charstyles },
499                 { "citestyles", md_citestyles },
500                 { "custom", md_custom },
501                 { "documents", md_documents },
502                 { "elements", md_elements },
503                 { "end", md_endmenu },
504                 { "environmentseparators", md_env_separators },
505                 { "environmentseparatorscontext", md_env_separatorscontext },
506                 { "exportformat", md_exportformat },
507                 { "exportformats", md_exportformats },
508                 { "floatinsert", md_floatinsert },
509                 { "floatlistinsert", md_floatlistinsert },
510                 { "graphicsgroups", md_graphicsgroups },
511                 { "importformats", md_importformats },
512                 { "indices", md_indices },
513                 { "indicescontext", md_indicescontext },
514                 { "indiceslists", md_indiceslists },
515                 { "indiceslistscontext", md_indiceslistscontext },
516                 { "item", md_item },
517                 { "languageselector", md_languageselector },
518                 { "lastfiles", md_lastfiles },
519                 { "optitem", md_optitem },
520                 { "optsubmenu", md_optsubmenu },
521                 { "pasterecent", md_pasterecent },
522                 { "separator", md_separator },
523                 { "spellingsuggestions", md_spellingsuggestions },
524                 { "submenu", md_submenu },
525                 { "switcharguments", md_switcharguments },
526                 { "switchcaptions", md_switchcaptions },
527                 { "switchquotes", md_switchquotes },
528                 { "toc", md_toc },
529                 { "toolbars", md_toolbars },
530                 { "updateformats", md_updateformats },
531                 { "viewformats", md_viewformats }
532         };
533
534         lex.pushTable(menutags);
535         lex.setContext("MenuDefinition::read: ");
536
537         int md_type = 0;
538         while (lex.isOK() && md_type != md_endmenu) {
539                 switch (md_type = lex.lex()) {
540                 case md_optitem:
541                 case md_item: {
542                         lex.next(true);
543                         docstring const name = translateIfPossible(lex.getDocString());
544                         lex.next(true);
545                         string const command = lex.getString();
546                         FuncRequest func = lyxaction.lookupFunc(command);
547                         FuncRequest::Origin origin = FuncRequest::MENU;
548                         if (name_.startsWith("context-toc-"))
549                                 origin = FuncRequest::TOC;
550                         bool const optional = (md_type == md_optitem);
551                         add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
552                         break;
553                 }
554
555                 case md_separator:
556                         add(MenuItem(MenuItem::Separator));
557                         break;
558
559                 case md_lastfiles:
560                         add(MenuItem(MenuItem::Lastfiles));
561                         break;
562
563                 case md_charstyles:
564                         add(MenuItem(MenuItem::CharStyles));
565                         break;
566
567                 case md_custom:
568                         add(MenuItem(MenuItem::Custom));
569                         break;
570
571                 case md_elements:
572                         add(MenuItem(MenuItem::Elements));
573                         break;
574
575                 case md_documents:
576                         add(MenuItem(MenuItem::Documents));
577                         break;
578
579                 case md_bookmarks:
580                         add(MenuItem(MenuItem::Bookmarks));
581                         break;
582
583                 case md_toc:
584                         add(MenuItem(MenuItem::Toc));
585                         break;
586
587                 case md_viewformats:
588                         add(MenuItem(MenuItem::ViewFormats));
589                         break;
590
591                 case md_updateformats:
592                         add(MenuItem(MenuItem::UpdateFormats));
593                         break;
594
595                 case md_exportformats:
596                         add(MenuItem(MenuItem::ExportFormats));
597                         break;
598
599                 case md_exportformat:
600                         add(MenuItem(MenuItem::ExportFormat));
601                         break;
602
603                 case md_importformats:
604                         add(MenuItem(MenuItem::ImportFormats));
605                         break;
606
607                 case md_floatlistinsert:
608                         add(MenuItem(MenuItem::FloatListInsert));
609                         break;
610
611                 case md_floatinsert:
612                         add(MenuItem(MenuItem::FloatInsert));
613                         break;
614
615                 case md_pasterecent:
616                         add(MenuItem(MenuItem::PasteRecent));
617                         break;
618
619                 case md_toolbars:
620                         add(MenuItem(MenuItem::Toolbars));
621                         break;
622
623                 case md_branches:
624                         add(MenuItem(MenuItem::Branches));
625                         break;
626
627                 case md_citestyles:
628                         add(MenuItem(MenuItem::CiteStyles));
629                         break;
630
631                 case md_graphicsgroups:
632                         add(MenuItem(MenuItem::GraphicsGroups));
633                         break;
634
635                 case md_spellingsuggestions:
636                         add(MenuItem(MenuItem::SpellingSuggestions));
637                         break;
638
639                 case md_languageselector:
640                         add(MenuItem(MenuItem::LanguageSelector));
641                         break;
642
643                 case md_indices:
644                         add(MenuItem(MenuItem::Indices));
645                         break;
646
647                 case md_indicescontext:
648                         add(MenuItem(MenuItem::IndicesContext));
649                         break;
650
651                 case md_indiceslists:
652                         add(MenuItem(MenuItem::IndicesLists));
653                         break;
654
655                 case md_indiceslistscontext:
656                         add(MenuItem(MenuItem::IndicesListsContext));
657                         break;
658
659                 case md_arguments:
660                         add(MenuItem(MenuItem::Arguments));
661                         break;
662
663                 case md_switcharguments:
664                         add(MenuItem(MenuItem::SwitchArguments));
665                         break;
666
667                 case md_captions:
668                         add(MenuItem(MenuItem::Captions));
669                         break;
670
671                 case md_switchcaptions:
672                         add(MenuItem(MenuItem::SwitchCaptions));
673                         break;
674
675                 case md_env_separators:
676                         add(MenuItem(MenuItem::EnvironmentSeparators));
677                         break;
678
679                 case md_env_separatorscontext:
680                         add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
681                         break;
682
683                 case md_switchquotes:
684                         add(MenuItem(MenuItem::SwitchQuotes));
685                         break;
686
687                 case md_optsubmenu:
688                 case md_submenu: {
689                         lex.next(true);
690                         docstring const mlabel = translateIfPossible(lex.getDocString());
691                         lex.next(true);
692                         docstring const mname = lex.getDocString();
693                         bool const optional = (md_type == md_optsubmenu);
694                         add(MenuItem(MenuItem::Submenu,
695                                 toqstr(mlabel), toqstr(mname), QString(), optional));
696                         break;
697                 }
698
699                 case md_endmenu:
700                         break;
701
702                 default:
703                         lex.printError("Unknown menu tag");
704                         break;
705                 }
706         }
707         lex.popTable();
708 }
709
710
711 bool MenuDefinition::hasFunc(FuncRequest const & func) const
712 {
713         for (const_iterator it = begin(), et = end(); it != et; ++it)
714                 if (*it->func() == func)
715                         return true;
716         return false;
717 }
718
719
720 void MenuDefinition::catSub(docstring const & name)
721 {
722         add(MenuItem(MenuItem::Submenu,
723                      qt_("More...|M"), toqstr(name), QString(), false));
724 }
725
726 void MenuDefinition::cat(MenuDefinition const & other)
727 {
728         const_iterator et = other.end();
729         for (const_iterator it = other.begin(); it != et; ++it)
730                 add(*it);
731 }
732
733
734 void MenuDefinition::checkShortcuts() const
735 {
736         // This is a quadratic algorithm, but we do not care because
737         // menus are short enough
738         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
739                 QString shortcut = it1->shortcut();
740                 if (shortcut.isEmpty())
741                         continue;
742                 if (!it1->label().contains(shortcut))
743                         LYXERR0("Menu warning: menu entry \""
744                                << it1->label()
745                                << "\" does not contain shortcut `"
746                                << shortcut << "'.");
747                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
748                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
749                                 LYXERR0("Menu warning: menu entries "
750                                        << '"' << it1->fulllabel()
751                                        << "\" and \"" << it2->fulllabel()
752                                        << "\" share the same shortcut.");
753                         }
754                 }
755         }
756 }
757
758
759 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
760 {
761         const_iterator m = begin();
762         const_iterator m_end = end();
763         for (; m != m_end; ++m) {
764                 if (m->kind() == MenuItem::Command && *m->func() == func) {
765                         names.push_back(qstring_to_ucs4(m->label()));
766                         return true;
767                 }
768                 if (m->kind() == MenuItem::Submenu) {
769                         names.push_back(qstring_to_ucs4(m->label()));
770                         if (!m->hasSubmenu()) {
771                                 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
772                                         << m->label() << " name=" << m->submenuname());
773                                 names.pop_back();
774                                 continue;
775                         }
776                         if (m->submenu().searchMenu(func, names))
777                                 return true;
778                         names.pop_back();
779                 }
780         }
781         return false;
782 }
783
784
785 QString limitStringLength(docstring const & str)
786 {
787         size_t const max_item_length = 45;
788         docstring ret = str.substr(0, max_item_length + 1);
789         support::truncateWithEllipsis(ret, max_item_length);
790         return toqstr(ret);
791 }
792
793
794 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
795 {
796         if (!bv)
797                 return;
798         set<string> grp;
799         graphics::getGraphicsGroups(bv->buffer(), grp);
800         if (grp.empty())
801                 return;
802
803         set<string>::const_iterator it = grp.begin();
804         set<string>::const_iterator end = grp.end();
805         add(MenuItem(MenuItem::Command, qt_("No Group"),
806                      FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
807         for (; it != end; ++it) {
808                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
809                                 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
810         }
811 }
812
813
814 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
815 {
816         if (!bv)
817                 return;
818         Cursor const & cur = bv->cursor();
819         if (!cur.inTexted())
820                 return;
821         WordLangTuple wl;
822         docstring_list suggestions;
823         Paragraph const & par = cur.paragraph();
824         pos_type from = cur.pos();
825         pos_type to = from;
826         SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
827         switch (res) {
828         case SpellChecker::UNKNOWN_WORD:
829                 if (lyxrc.spellcheck_continuously) {
830                         LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
831                         docstring const & selection = cur.selectionAsString(false);
832                         if (!cur.selection() || selection == wl.word()) {
833                                 size_t i = 0;
834                                 size_t m = 10; // first submenu index
835                                 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
836                                 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
837                                 for (; i != suggestions.size(); ++i) {
838                                         docstring const & suggestion = suggestions[i];
839                                         LYXERR(Debug::GUI, suggestion);
840                                         MenuItem w(MenuItem::Command, toqstr(suggestion),
841                                                 FuncRequest(LFUN_WORD_REPLACE,
842                                                         replace2string(suggestion, selection,
843                                                                 true,     // case sensitive
844                                                                 true,     // match word
845                                                                 false,    // all words
846                                                                 true,     // forward
847                                                                 false))); // find next
848                                         if (i < m)
849                                                 add(w);
850                                         else
851                                                 item.submenu().add(w);
852                                 }
853                                 if (i > m)
854                                         add(item);
855                                 if (i > 0)
856                                         add(MenuItem(MenuItem::Separator));
857                                 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
858                                 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
859                                                 FuncRequest(LFUN_SPELLING_ADD, arg)));
860                                 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
861                                                 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
862                         }
863                 }
864                 break;
865         case SpellChecker::LEARNED_WORD: {
866                         LYXERR(Debug::GUI, "Learned Word.");
867                         docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
868                         add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
869                                         FuncRequest(LFUN_SPELLING_REMOVE, arg)));
870                 }
871                 break;
872         case SpellChecker::NO_DICTIONARY:
873                 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
874                 // FALLTHROUGH
875         case SpellChecker::WORD_OK:
876         case SpellChecker::COMPOUND_WORD:
877         case SpellChecker::ROOT_FOUND:
878         case SpellChecker::IGNORED_WORD:
879                 break;
880         }
881 }
882
883 struct sortLanguageByName {
884         bool operator()(const Language * a, const Language * b) const {
885                 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
886         }
887 };
888
889 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
890 {
891         if (!buf)
892                 return;
893
894         std::set<Language const *> languages_buffer =
895                 buf->masterBuffer()->getLanguages();
896
897         if (languages_buffer.size() < 2)
898                 return;
899
900         std::set<Language const *, sortLanguageByName> langs;
901
902         std::set<Language const *>::const_iterator const beg =
903                 languages_buffer.begin();
904         for (std::set<Language const *>::const_iterator cit = beg;
905              cit != languages_buffer.end(); ++cit) {
906                 langs.insert(*cit);
907         }
908
909         MenuItem item(MenuItem::Submenu, qt_("Language|L"));
910         item.setSubmenu(MenuDefinition(qt_("Language")));
911         QString morelangs = qt_("More Languages ...|M");
912         QStringList accelerators;
913         if (morelangs.contains('|'))
914                 accelerators.append(morelangs.section('|', -1));
915         std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
916         for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
917                          cit != langs.end(); ++cit) {
918                 QString label = qt_((*cit)->display());
919                 // try to add an accelerator
920                 bool success = false;
921                 // try capitals first
922                 for (int i = 0; i < label.size(); ++i) {
923                         QChar const ch = label[i];
924                         if (!ch.isUpper())
925                                 continue;
926                         if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
927                                 label = label + toqstr("|") + ch;
928                                 accelerators.append(ch);
929                                 success = true;
930                                 break;
931                         }
932                 }
933                 // if all capitals are taken, try the rest
934                 if (!success) {
935                         for (int i = 0; i < label.size(); ++i) {
936                                 if (label[i].isSpace())
937                                         continue;
938                                 QString const ch = QString(label[i]);
939                                 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
940                                         label = label + toqstr("|") + ch;
941                                         accelerators.append(ch);
942                                         break;
943                                 }
944                         }
945                 }
946                 MenuItem w(MenuItem::Command, label,
947                         FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
948                 item.submenu().addWithStatusCheck(w);
949         }
950         item.submenu().add(MenuItem(MenuItem::Separator));
951         item.submenu().add(MenuItem(MenuItem::Command, morelangs,
952                         FuncRequest(LFUN_DIALOG_SHOW, "character")));
953         add(item);
954 }
955
956
957 void MenuDefinition::expandLastfiles()
958 {
959         LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
960         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
961
962         unsigned int ii = 1;
963
964         for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
965                 string const file = lfit->absFileName();
966                 QString const short_path = toqstr(makeDisplayPath(file, 30));
967                 QString const long_path = toqstr(makeDisplayPath(file));
968                 QString label;
969                 if (ii < 10)
970                         label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
971                 else
972                         label = QString("%1. %2").arg(ii).arg(short_path);
973                 add(MenuItem(MenuItem::Command, label,
974                         FuncRequest(LFUN_FILE_OPEN, file), long_path));
975         }
976 }
977
978
979 void MenuDefinition::expandDocuments()
980 {
981         MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
982         item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
983
984         Buffer * first = theBufferList().first();
985         if (!first) {
986                 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
987                 return;
988         }
989
990         int i = 0;
991         while (true) {
992                 if (!guiApp->currentView())
993                         break;
994                 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
995                 if (!wa)
996                         break;
997                 Buffer const & b = wa->bufferView().buffer();
998                 QString label = toqstr(b.fileName().displayName(20));
999                 if (!b.isClean())
1000                         label += "*";
1001                 if (b.notifiesExternalModification())
1002                         label += QChar(0x26a0);
1003                 if (i < 10)
1004                         label = QString::number(i) + ". " + label + '|' + QString::number(i);
1005                 add(MenuItem(MenuItem::Command, label,
1006                         FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1007                 ++i;
1008         }
1009
1010
1011         i = 0;
1012         Buffer * b = first;
1013         // We cannot use a for loop as the buffer list cycles.
1014         do {
1015                 if (!(guiApp->currentView()
1016                     && guiApp->currentView()->workArea(*b))) {
1017                         QString label = toqstr(b->fileName().displayName(20));
1018                         if (!b->isClean())
1019                                 label += "*";
1020                         if (b->notifiesExternalModification())
1021                                 label += QChar(0x26a0);
1022                         if (i < 10)
1023                                 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1024                         item.submenu().add(MenuItem(MenuItem::Command, label,
1025                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1026                         ++i;
1027                 }
1028                 b = theBufferList().next(b);
1029         } while (b != first);
1030
1031         if (!item.submenu().empty())
1032                 add(item);
1033 }
1034
1035
1036 void MenuDefinition::expandBookmarks()
1037 {
1038         lyx::BookmarksSection const & bm = theSession().bookmarks();
1039
1040         bool empty = true;
1041         for (size_t i = 1; i <= bm.size(); ++i) {
1042                 if (bm.isValid(i)) {
1043                         string const file = bm.bookmark(i).filename.absFileName();
1044                         QString const label = QString("%1. %2|%3").arg(i)
1045                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1046                         add(MenuItem(MenuItem::Command, label,
1047                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1048                         empty = false;
1049                 }
1050         }
1051         if (empty)
1052                 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1053 }
1054
1055
1056 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1057 {
1058         if (!buf && kind != MenuItem::ImportFormats)
1059                 return;
1060
1061         FormatList formats;
1062         FuncCode action = LFUN_NOACTION;
1063
1064         switch (kind) {
1065         case MenuItem::ImportFormats:
1066                 formats = theConverters().importableFormats();
1067                 action = LFUN_BUFFER_IMPORT;
1068                 break;
1069         case MenuItem::ViewFormats:
1070                 formats = buf->params().exportableFormats(true);
1071                 action = LFUN_BUFFER_VIEW;
1072                 break;
1073         case MenuItem::UpdateFormats:
1074                 formats = buf->params().exportableFormats(true);
1075                 action = LFUN_BUFFER_UPDATE;
1076                 break;
1077         case MenuItem::ExportFormats:
1078                 formats = buf->params().exportableFormats(false);
1079                 action = LFUN_BUFFER_EXPORT;
1080                 break;
1081         default:
1082                 LATTEST(false);
1083                 return;
1084         }
1085
1086         bool const view_update = (kind == MenuItem::ViewFormats
1087                         || kind == MenuItem::UpdateFormats);
1088
1089         QString smenue;
1090         if (view_update)
1091                 smenue = (kind == MenuItem::ViewFormats
1092                         ? qt_("View (Other Formats)|F")
1093                         : qt_("Update (Other Formats)|p"));
1094         MenuItem item(MenuItem::Submenu, smenue);
1095         item.setSubmenu(MenuDefinition(smenue));
1096
1097         for (Format const * f : formats) {
1098                 if (f->dummy())
1099                         continue;
1100
1101                 docstring lab = f->prettyname();
1102                 docstring const scut = from_utf8(f->shortcut());
1103                 docstring const tmplab = lab;
1104
1105                 if (!scut.empty())
1106                         lab += char_type('|') + scut;
1107                 docstring const lab_i18n = translateIfPossible(lab);
1108                 docstring const shortcut = split(lab_i18n, lab, '|');
1109
1110                 bool const untranslated = (lab == lab_i18n);
1111                 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1112
1113                 switch (kind) {
1114                 case MenuItem::ImportFormats:
1115                         label += from_ascii("...");
1116                         break;
1117                 case MenuItem::ViewFormats:
1118                 case MenuItem::UpdateFormats:
1119                         if (f->name() == buf->params().getDefaultOutputFormat()) {
1120                                 docstring lbl = (kind == MenuItem::ViewFormats
1121                                         ? bformat(_("View [%1$s]|V"), label)
1122                                         : bformat(_("Update [%1$s]|U"), label));
1123                                 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1124                                 continue;
1125                         }
1126                         break;
1127                 case MenuItem::ExportFormats:
1128                         if (!f->inExportMenu())
1129                                 continue;
1130                         break;
1131                 default:
1132                         // we already asserted earlier in this case
1133                         // LATTEST(false);
1134                         continue;
1135                 }
1136                 if (!shortcut.empty())
1137                         label += '|' + shortcut;
1138
1139                 if (view_update) {
1140                         // note that at this point, we know that buf is not null
1141                         LATTEST(buf);
1142                         item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1143                                 toqstr(label), FuncRequest(action, f->name())));
1144                 } else {
1145                         if (buf)
1146                                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1147                                         FuncRequest(action, f->name())));
1148                         else
1149                                 add(MenuItem(MenuItem::Command, toqstr(label),
1150                                         FuncRequest(action, f->name())));
1151                 }
1152         }
1153         if (view_update)
1154                 add(item);
1155 }
1156
1157
1158 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1159 {
1160         if (!buf)
1161                 return;
1162
1163         FloatList const & floats = buf->params().documentClass().floats();
1164         FloatList::const_iterator cit = floats.begin();
1165         FloatList::const_iterator end = floats.end();
1166         set<string> seen;
1167         for (; cit != end; ++cit) {
1168                 if (!cit->second.usesFloatPkg()) {
1169                         // Different floats could declare the same ListCommand. We only
1170                         // want it on the list once, though.
1171                         string const & list_cmd = cit->second.listCommand();
1172                         if (list_cmd.empty())
1173                                 // we do not know how to generate such a list
1174                                 continue;
1175                         // This form of insert returns an iterator pointing to the newly
1176                         // inserted element OR the existing element with that value, and
1177                         // a bool indicating whether we inserted a new element. So we can
1178                         // see if one is there and insert it if not all at once.
1179                         pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1180                         if (!ret.second)
1181                                 continue;
1182                 }
1183                 string const & list_name = cit->second.listName();
1184                 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1185                         FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1186         }
1187 }
1188
1189
1190 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1191 {
1192         if (!buf)
1193                 return;
1194
1195         FloatList const & floats = buf->params().documentClass().floats();
1196         FloatList::const_iterator cit = floats.begin();
1197         FloatList::const_iterator end = floats.end();
1198         for (; cit != end; ++cit) {
1199                 // normal float
1200                 QString const label = qt_(cit->second.name());
1201                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1202                                     FuncRequest(LFUN_FLOAT_INSERT,
1203                                                 cit->second.floattype())));
1204         }
1205 }
1206
1207
1208 void MenuDefinition::expandFlexInsert(
1209                 Buffer const * buf, InsetLayout::InsetLyXType type)
1210 {
1211         if (!buf)
1212                 return;
1213
1214         TextClass::InsetLayouts const & insetLayouts =
1215                 buf->params().documentClass().insetLayouts();
1216         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1217         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1218         for (; cit != end; ++cit) {
1219                 if (cit->second.lyxtype() == type) {
1220                         if (!cit->second.obsoleted_by().empty())
1221                                 continue;
1222                         docstring label = cit->first;
1223                         // we remove the "Flex:" prefix, if it is present
1224                         if (prefixIs(label, from_ascii("Flex:")))
1225                                 label = label.substr(5);
1226                         addWithStatusCheck(MenuItem(MenuItem::Command,
1227                                 toqstr(translateIfPossible(label)),
1228                                 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1229                 }
1230         }
1231         // FIXME This is a little clunky.
1232         if (items_.empty() && type == InsetLayout::CUSTOM && !buf->hasReadonlyFlag())
1233                 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1234 }
1235
1236
1237 // Threshold before we stop displaying sub-items alongside items
1238 // (for display purposes). Ideally this should fit on a screen.
1239 size_t const max_number_of_items = 30;
1240 // Size limit for the menu. This is for performance purposes,
1241 // because qt already displays a scrollable menu when necessary.
1242 // Ideally this should be the menu size from which scrollable
1243 // menus become unpractical.
1244 size_t const menu_size_limit = 80;
1245
1246 void MenuDefinition::expandToc2(Toc const & toc_list,
1247                                 size_t from, size_t to, int depth,
1248                                 string toc_type)
1249 {
1250         int shortcut_count = 0;
1251
1252         // check whether depth is smaller than the smallest depth in toc.
1253         int min_depth = 1000;
1254         for (size_t i = from; i < to; ++i)
1255                 min_depth = min(min_depth, toc_list[i].depth());
1256         if (min_depth > depth)
1257                 depth = min_depth;
1258
1259         if (to - from <= max_number_of_items) {
1260                 for (size_t i = from; i < to; ++i) {
1261                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1262                         label += limitStringLength(toc_list[i].asString());
1263                         if (toc_list[i].depth() == depth) {
1264                                 label += '|';
1265                             if (shortcut_count < 9) {
1266                                         if (label.contains(QString::number(shortcut_count + 1)))
1267                                                 label += QString::number(++shortcut_count);
1268                                 }
1269                         }
1270                         add(MenuItem(MenuItem::Command, label,
1271                                             FuncRequest(toc_list[i].action())));
1272                         // separator after the menu heading
1273                         if (toc_list[i].depth() < depth)
1274                                 add(MenuItem(MenuItem::Separator));
1275                 }
1276         } else {
1277                 size_t pos = from;
1278                 size_t size = 1;
1279                 while (pos < to) {
1280                         size_t new_pos = pos + 1;
1281                         while (new_pos < to && toc_list[new_pos].depth() > depth)
1282                                 ++new_pos;
1283
1284                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1285                         label += limitStringLength(toc_list[pos].asString());
1286                         if (toc_list[pos].depth() == depth) {
1287                                 label += '|';
1288                             if (shortcut_count < 9) {
1289                                         if (label.contains(QString::number(shortcut_count + 1)))
1290                                                 label += QString::number(++shortcut_count);
1291                                 }
1292                         }
1293                         if (size >= menu_size_limit) {
1294                                 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1295                                 add(MenuItem(MenuItem::Command, "...", f));
1296                                 break;
1297                         }
1298                         if (new_pos == pos + 1) {
1299                                 add(MenuItem(MenuItem::Command,
1300                                                     label, FuncRequest(toc_list[pos].action())));
1301                         } else {
1302                                 MenuDefinition sub;
1303                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1304                                 MenuItem item(MenuItem::Submenu, label);
1305                                 item.setSubmenu(sub);
1306                                 add(item);
1307                         }
1308                         ++size;
1309                         pos = new_pos;
1310                 }
1311         }
1312 }
1313
1314
1315 void MenuDefinition::expandToc(Buffer const * buf)
1316 {
1317         // To make things very cleanly, we would have to pass buf to
1318         // all MenuItem constructors and to expandToc2. However, we
1319         // know that all the entries in a TOC will be have status_ ==
1320         // OK, so we avoid this unnecessary overhead (JMarc)
1321         if (!buf) {
1322                 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1323                 return;
1324         }
1325         // Add an entry for the master doc if this is a child doc
1326         Buffer const * const master = buf->masterBuffer();
1327         if (buf != master) {
1328                 ParIterator const pit = par_iterator_begin(master->inset());
1329                 string const arg = convert<string>(pit->id());
1330                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1331                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1332         }
1333
1334         MenuDefinition other_lists;
1335         // In the navigation menu, only add tocs from this document
1336         TocBackend const & backend = buf->tocBackend();
1337         TocList const & toc_list = backend.tocs();
1338         for (pair<string, shared_ptr<Toc>> const & toc : toc_list) {
1339                 // Handle table of contents later
1340                 if (toc.first == "tableofcontents" || toc.second->empty())
1341                         continue;
1342                 MenuDefinition submenu;
1343                 submenu.expandTocSubmenu(toc.first, *toc.second);
1344                 docstring const toc_name = backend.outlinerName(toc.first);
1345                 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1346                 item.setSubmenu(submenu);
1347                 // deserves to be in the main menu?
1348                 if (!TocBackend::isOther(toc.first))
1349                         add(item);
1350                 else
1351                         other_lists.add(item);
1352         }
1353         if (!other_lists.empty()) {
1354                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1355                 item.setSubmenu(other_lists);
1356                 add(item);
1357         }
1358         // Handle normal TOC
1359         add(MenuItem(MenuItem::Separator));
1360         TocList::const_iterator cit = toc_list.find("tableofcontents");
1361         if (cit == toc_list.end())
1362                 LYXERR(Debug::GUI, "No table of contents.");
1363         else {
1364                 if (!cit->second->empty())
1365                         expandToc2(*cit->second, 0, cit->second->size(), 0,
1366                                    "tableofcontents");
1367                 else
1368                         add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1369         }
1370 }
1371
1372
1373 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1374 {
1375         // "Open outliner..." entry
1376         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1377         add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1378         add(MenuItem(MenuItem::Separator));
1379         // add entries
1380         expandToc2(toc, 0, toc.size(), 0, type);
1381 }
1382
1383
1384 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1385 {
1386         docstring_list const sel = cap::availableSelections(buf);
1387
1388         docstring_list::const_iterator cit = sel.begin();
1389         docstring_list::const_iterator end = sel.end();
1390
1391         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1392                 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1393                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1394         }
1395 }
1396
1397
1398 void MenuDefinition::expandToolbars()
1399 {
1400         MenuDefinition other_lists;
1401         // extracts the toolbars from the backend
1402         Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1403         Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1404         for (; cit != end; ++cit) {
1405                 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1406                                 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1407                 if (guiApp->toolbars().isMainToolbar(cit->name))
1408                         add(item);
1409                 else
1410                         other_lists.add(item);
1411         }
1412
1413         if (!other_lists.empty()) {
1414                 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1415                 item.setSubmenu(other_lists);
1416                 add(item);
1417         }
1418 }
1419
1420
1421 void MenuDefinition::expandBranches(Buffer const * buf)
1422 {
1423         if (!buf || buf->hasReadonlyFlag())
1424                 return;
1425
1426         BufferParams const & master_params = buf->masterBuffer()->params();
1427         BufferParams const & params = buf->params();
1428         if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1429                 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1430                 return;
1431         }
1432
1433         BranchList::const_iterator cit = master_params.branchlist().begin();
1434         BranchList::const_iterator end = master_params.branchlist().end();
1435
1436         for (int ii = 1; cit != end; ++cit, ++ii) {
1437                 docstring label = cit->branch();
1438                 if (ii < 10) {
1439                         label = convert<docstring>(ii) + ". " + label
1440                                 + char_type('|') + convert<docstring>(ii);
1441                 }
1442                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1443                                     FuncRequest(LFUN_BRANCH_INSERT,
1444                                                 cit->branch())));
1445         }
1446
1447         if (buf == buf->masterBuffer())
1448                 return;
1449
1450         MenuDefinition child_branches;
1451
1452         BranchList::const_iterator ccit = params.branchlist().begin();
1453         BranchList::const_iterator cend = params.branchlist().end();
1454
1455         for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1456                 docstring label = ccit->branch();
1457                 if (ii < 10) {
1458                         label = convert<docstring>(ii) + ". " + label
1459                                 + char_type('|') + convert<docstring>(ii);
1460                 } else
1461                         label += char_type('|');
1462                 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1463                                     toqstr(label),
1464                                     FuncRequest(LFUN_BRANCH_INSERT,
1465                                                 ccit->branch())));
1466         }
1467
1468         if (!child_branches.empty()) {
1469                 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1470                 item.setSubmenu(child_branches);
1471                 add(item);
1472         }
1473 }
1474
1475
1476 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1477 {
1478         if (!buf)
1479                 return;
1480
1481         BufferParams const & params = buf->masterBuffer()->params();
1482         if (!params.use_indices) {
1483                 if (listof)
1484                         addWithStatusCheck(MenuItem(MenuItem::Command,
1485                                            qt_("Index List|I"),
1486                                            FuncRequest(LFUN_INDEX_PRINT,
1487                                                   from_ascii("idx"))));
1488                 else
1489                         addWithStatusCheck(MenuItem(MenuItem::Command,
1490                                            qt_("Index Entry|d"),
1491                                            FuncRequest(LFUN_INDEX_INSERT,
1492                                                   from_ascii("idx"))));
1493                 return;
1494         }
1495
1496         if (params.indiceslist().empty())
1497                 return;
1498
1499         IndicesList::const_iterator cit = params.indiceslist().begin();
1500         IndicesList::const_iterator end = params.indiceslist().end();
1501
1502         for (int ii = 1; cit != end; ++cit, ++ii) {
1503                 if (listof) {
1504                         docstring const label =
1505                                 bformat(_("Index: %1$s"), cit->index());
1506                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1507                                            FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1508                 } else {
1509                         docstring const label =
1510                                 bformat(_("Index Entry (%1$s)"), cit->index());
1511                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1512                                            FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1513                 }
1514         }
1515 }
1516
1517
1518 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1519 {
1520         if (!buf)
1521                 return;
1522
1523         BufferParams const & params = buf->masterBuffer()->params();
1524         if (!params.use_indices || params.indiceslist().empty())
1525                 return;
1526
1527         IndicesList::const_iterator cit = params.indiceslist().begin();
1528         IndicesList::const_iterator end = params.indiceslist().end();
1529
1530         for (int ii = 1; cit != end; ++cit, ++ii) {
1531                 if (listof) {
1532                         InsetCommandParams p(INDEX_PRINT_CODE);
1533                         p["type"] = cit->shortcut();
1534                         string const data = InsetCommand::params2string(p);
1535                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1536                                            FuncRequest(LFUN_INSET_MODIFY, data)));
1537                 } else {
1538                         docstring const label =
1539                                         bformat(_("Index Entry (%1$s)"), cit->index());
1540                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1541                                            FuncRequest(LFUN_INSET_MODIFY,
1542                                                   from_ascii("changetype ") + cit->shortcut())));
1543                 }
1544         }
1545 }
1546
1547
1548 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1549 {
1550         if (!bv)
1551                 return;
1552
1553         Inset const * inset = bv->cursor().nextInset();
1554         if (!inset || inset->lyxCode() != CITE_CODE) {
1555                 add(MenuItem(MenuItem::Command,
1556                                     qt_("No Citation in Scope!"),
1557                                     FuncRequest(LFUN_NOACTION)));
1558                 return;
1559         }
1560         InsetCitation const * citinset =
1561                                 static_cast<InsetCitation const *>(inset);
1562
1563         Buffer const * buf = &bv->buffer();
1564         BufferParams const & bp = buf->masterParams();
1565         string const cmd = citinset->params().getCmdName();
1566
1567         docstring const & key = citinset->getParam("key");
1568         if (key.empty()) {
1569                 add(MenuItem(MenuItem::Command,
1570                                     qt_("No citations selected!"),
1571                                     FuncRequest(LFUN_NOACTION)));
1572                 return;
1573         }
1574
1575         size_t const n = cmd.size();
1576         bool const force = isUpperCase(cmd[0]);
1577         bool const star = cmd[n] == '*';
1578
1579         vector<docstring> const keys = getVectorFromString(key);
1580
1581         vector<CitationStyle> const citeStyleList = bp.citeStyles();
1582
1583         CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1584         bool const qualified = cs.hasQualifiedList
1585                 && (keys.size() > 1
1586                     || !citinset->getParam("pretextlist").empty()
1587                     || !citinset->getParam("posttextlist").empty());
1588         std::map<docstring, docstring> pres =
1589                 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1590         std::map<docstring, docstring> posts =
1591                 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1592
1593         CiteItem ci;
1594         ci.textBefore = citinset->getParam("before");
1595         ci.textAfter = citinset->getParam("after");
1596         ci.forceUpperCase = force;
1597         ci.Starred = star;
1598         ci.context = CiteItem::Dialog;
1599         ci.max_size = 40;
1600         ci.isQualified = qualified;
1601         ci.pretexts = pres;
1602         ci.posttexts = posts;
1603         BiblioInfo::CiteStringMap citeStrings =
1604                 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1605
1606         BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1607         BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1608
1609         for (int ii = 1; cit != end; ++cit, ++ii) {
1610                 docstring label = cit->second;
1611                 CitationStyle ccs = citeStyleList[ii - 1];
1612                 ccs.forceUpperCase &= force;
1613                 ccs.hasStarredVersion &= star;
1614                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1615                                     FuncRequest(LFUN_INSET_MODIFY,
1616                                                 "changetype " + from_utf8(citationStyleToString(ccs)))));
1617         }
1618
1619         if (cs.hasStarredVersion) {
1620                 docstring starred = _("All authors|h");
1621                 // Check if we have a custom string/tooltip for the starred version
1622                 if (!cs.stardesc.empty()) {
1623                         string val =
1624                                 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1625                         if (!val.empty())
1626                                 starred = translateIfPossible(from_utf8(val));
1627                         // Transform qt-style accelerators to menu-style
1628                         int const amps = count_char(starred, '&');
1629                         if (amps > 0) {
1630                                 if (amps > 1)
1631                                         starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1632                                 size_t nn = starred.find('&');
1633                                 char_type accel = char_type();
1634                                 if (nn != docstring::npos && nn < starred.size() - 1)
1635                                         accel = starred[nn + 1];
1636                                 starred = subst(starred, from_ascii("&"), from_ascii(""));
1637                                 if (amps > 1)
1638                                         starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1639                                 if (accel != char_type())
1640                                         starred = starred + '|' + accel;
1641                         }
1642                 }
1643                 add(MenuItem(MenuItem::Separator));
1644                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1645                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1646         }
1647
1648         if (cs.forceUpperCase) {
1649                 if (!cs.hasStarredVersion)
1650                         add(MenuItem(MenuItem::Separator));
1651                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1652                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1653         }
1654 }
1655
1656
1657 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1658 {
1659         if (!bv)
1660                 return;
1661
1662         if (!bv->cursor().inTexted())
1663                 return;
1664
1665         Inset const * inset = &bv->cursor().inset();
1666         Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1667         if (inset && args.empty())
1668                 args = inset->getLayout().args();
1669         if (args.empty() || (switcharg && args.size() == 1))
1670                 return;
1671         Layout::LaTeXArgMap::const_iterator lait = args.begin();
1672         Layout::LaTeXArgMap::const_iterator const laend = args.end();
1673         for (; lait != laend; ++lait) {
1674                 Layout::latexarg arg = (*lait).second;
1675                 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1676                 QString item = toqstr(translateIfPossible(str));
1677                 if (switcharg)
1678                         add(MenuItem(MenuItem::Command, item,
1679                                      FuncRequest(LFUN_INSET_MODIFY,
1680                                                  from_ascii("changetype ")
1681                                                  + from_ascii((*lait).first))));
1682                 else
1683                         add(MenuItem(MenuItem::Command, item,
1684                                      FuncRequest(LFUN_ARGUMENT_INSERT,
1685                                                  from_ascii((*lait).first))));
1686         }
1687 }
1688
1689
1690 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1691 {
1692         if (!buf)
1693                 return;
1694
1695         DocumentClass const & dc = buf->params().documentClass();
1696         vector< pair<docstring, FuncRequest> > caps;
1697         for (pair<docstring, InsetLayout> const & il : dc.insetLayouts()) {
1698                 docstring instype;
1699                 docstring const type = split(il.first, instype, ':');
1700                 if (instype == from_ascii("Caption")) {
1701                         // skip forbidden caption types
1702                         FuncRequest const cmd = switchcap
1703                                 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1704                                 : FuncRequest(LFUN_CAPTION_INSERT, type);
1705                         if (getStatus(cmd).enabled())
1706                                 caps.push_back(make_pair(type, cmd));
1707                 }
1708         }
1709
1710         if (caps.empty() || (switchcap && caps.size() == 1))
1711                 return;
1712         if (caps.size() == 1) {
1713                 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1714                 return;
1715         }
1716
1717         MenuDefinition captions;
1718         for (pair<docstring, FuncRequest> const & cap : caps) {
1719                 docstring const type = cap.first;
1720                 docstring const trtype = translateIfPossible(type);
1721                 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1722                 if (switchcap)
1723                         add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1724                 else
1725                         captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1726         }
1727         if (!captions.empty()) {
1728                 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1729                 item.setSubmenu(captions);
1730                 add(item);
1731         }
1732 }
1733
1734
1735 void MenuDefinition::expandQuotes(BufferView const * bv)
1736 {
1737         if (!bv)
1738                 return;
1739
1740         if (!bv->cursor().inTexted())
1741                 return;
1742
1743         Inset const * inset = bv->cursor().nextInset();
1744         if (!inset || inset->lyxCode() != QUOTE_CODE) {
1745                 add(MenuItem(MenuItem::Command,
1746                                     qt_("No Quote in Scope!"),
1747                                     FuncRequest(LFUN_NOACTION)));
1748                 return;
1749         }
1750         InsetQuotes const * qinset =
1751                 static_cast<InsetQuotes const *>(inset);
1752
1753         map<string, docstring> styles = quoteparams.getTypes();
1754         string const qtype = qinset->getType();
1755
1756         map<string, docstring>::const_iterator qq = styles.begin();
1757         map<string, docstring>::const_iterator end = styles.end();
1758
1759         MenuDefinition aqs;
1760
1761         BufferParams const & bp = bv->buffer().masterBuffer()->params();
1762
1763         // The global setting
1764         InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1765         char const globalqsc = quoteparams.getStyleChar(globalqs);
1766
1767         // The current language's default
1768         InsetQuotesParams::QuoteStyle langdefqs =
1769                 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1770         char const langqs = quoteparams.getStyleChar(langdefqs);
1771
1772         bool main_global_qs = false;
1773         bool main_langdef_qs = false;
1774         bool main_dynamic_qs = false;
1775         docstring const subcmd = from_ascii("changetype ");
1776         docstring const wildcards = from_ascii("..");
1777         // Add the items
1778         // First the top level menu (all glyphs of the current style) ...
1779         // Begin with dynamic (if they are current style),
1780         if (qtype[0] == 'x') {
1781                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1782                 docstring desc = bformat(_("%1$s (dynamic)"),
1783                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1784                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1785                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1786                 desc = bformat(_("%1$s (dynamic)"),
1787                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1788                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1789                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1790                 desc = bformat(_("%1$s (dynamic)"),
1791                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1792                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1793                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1794                 desc = bformat(_("%1$s (dynamic)"),
1795                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1796                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1797                 main_dynamic_qs = true;
1798         }
1799         // now traverse through the static styles ...
1800         for (; qq != end; ++qq) {
1801                 docstring const style = from_ascii(qq->first);
1802                 bool langdef = (style[0] == langqs);
1803                 bool globaldef = (style[0] == globalqsc);
1804
1805                 if (prefixIs(style, qtype[0])) {
1806                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1807                         docstring const desc = quoteparams.getShortGuiLabel(style);
1808                         add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1809                         main_global_qs = globaldef;
1810                         main_langdef_qs = langdef;
1811                 }
1812                 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1813                         docstring const desc =
1814                                 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1815                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1816                         aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1817                 }
1818         }
1819
1820         add(MenuItem(MenuItem::Separator));
1821
1822         bool display_static = false;
1823         // ... then potentially items to reset to the defaults and to dynamic style ...
1824         if (!main_dynamic_qs && globalqsc != 'x') {
1825                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1826                 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1827                                                 quoteparams.getGuiLabel(globalqs));
1828                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1829                 display_static = true;
1830         }
1831         if (!main_global_qs && langdefqs != globalqs) {
1832                 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1833                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1834                 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1835                                                 quoteparams.getGuiLabel(globalqs), variant);
1836                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1837         }
1838         if (!main_langdef_qs) {
1839                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1840                 docstring const desc = (main_dynamic_qs || display_static)
1841                                         ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1842                                                   quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1843                                         : bformat(_("Reset to language default (%1$s)|l"),
1844                                                   quoteparams.getGuiLabel(langdefqs));
1845                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1846         }
1847
1848         add(MenuItem(MenuItem::Separator));
1849
1850         // ... and a subitem with the rest
1851         MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1852         item.setSubmenu(aqs);
1853         add(item);
1854 }
1855
1856
1857 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1858                                                  bool contextmenu)
1859 {
1860         if (!bv)
1861                 return;
1862         Text const * text = bv->cursor().text();
1863         // no paragraphs and no separators exist in math
1864         if (!text)
1865                 return;
1866
1867         pit_type pit = bv->cursor().selBegin().pit();
1868         Paragraph const & par = text->getPar(pit);
1869         docstring const curlayout = par.layout().name();
1870         docstring outerlayout;
1871         docstring prevlayout;
1872         depth_type current_depth = par.params().depth();
1873         // check if we have an environment in our scope
1874         Paragraph cpar = par;
1875         while (true) {
1876                 if (pit == 0)
1877                         break;
1878                 --pit;
1879                 cpar = text->getPar(pit);
1880                 if (cpar.layout().isEnvironment() && prevlayout.empty()
1881                     && cpar.params().depth() <= current_depth)
1882                                 prevlayout = cpar.layout().name();
1883                 if (cpar.params().depth() < current_depth
1884                     && cpar.layout().isEnvironment()) {
1885                                 outerlayout = cpar.layout().name();
1886                                 current_depth = cpar.params().depth();
1887                 }
1888                 if (cpar.params().depth() == 0)
1889                         break;
1890         }
1891         if (par.layout().isEnvironment()) {
1892                 docstring label = contextmenu ?
1893                                         bformat(_("Insert Separated %1$s Above"),
1894                                                 translateIfPossible(curlayout)) :
1895                                         bformat(_("Separated %1$s Above"),
1896                                                 translateIfPossible(curlayout));
1897                 add(MenuItem(MenuItem::Command, toqstr(label),
1898                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1899                                          from_ascii("before"))));
1900                 label = contextmenu ?
1901                                 bformat(_("Insert Separated %1$s Below"),
1902                                         translateIfPossible(curlayout)):
1903                                 bformat(_("Separated %1$s Below"),
1904                                         translateIfPossible(curlayout));
1905                 // We use command-alternatives here since this is how the binding is defined
1906                 // (otherwise, the binding is not displayed in the menu)
1907                 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1908                         add(MenuItem(MenuItem::Command, toqstr(label),
1909                                      FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1910                                                  from_ascii("environment-split ; environment-split previous"))));
1911         }
1912         else if (!prevlayout.empty()) {
1913                 docstring const label = contextmenu ?
1914                         bformat(_("Insert Separated %1$s Below"),
1915                                 translateIfPossible(prevlayout)) :
1916                         bformat(_("Separated %1$s Below"),
1917                                 translateIfPossible(prevlayout));
1918                 // We use command-alternatives here since this is how the binding is defined
1919                 // (otherwise, the binding is not displayed in the menu)
1920                 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1921                         add(MenuItem(MenuItem::Command, toqstr(label),
1922                                      FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1923                                                  from_ascii("environment-split ; environment-split previous"))));
1924         }
1925         if (!outerlayout.empty()) {
1926                 docstring label;
1927                 if (contextmenu) {
1928                         label = (outerlayout == curlayout) ?
1929                                 bformat(_("Insert Separated Outer %1$s Below"),
1930                                         translateIfPossible(outerlayout)) :
1931                                 bformat(_("Insert Separated %1$s Below"),
1932                                         translateIfPossible(outerlayout));
1933                 } else {
1934                         label = (outerlayout == curlayout) ?
1935                                 bformat(_("Separated Outer %1$s Below"),
1936                                         translateIfPossible(outerlayout)) :
1937                                 bformat(_("Separated %1$s Below"),
1938                                         translateIfPossible(outerlayout));
1939                 }
1940                 add(MenuItem(MenuItem::Command, toqstr(label),
1941                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1942                                          from_ascii("outer"))));
1943         }
1944 }
1945
1946 } // namespace
1947
1948
1949 /////////////////////////////////////////////////////////////////////
1950 // Menu::Impl definition and implementation
1951 /////////////////////////////////////////////////////////////////////
1952
1953 struct Menu::Impl
1954 {
1955         /// populates the menu or one of its submenu
1956         /// This is used as a recursive function
1957         void populate(QMenu * qMenu, MenuDefinition const & menu);
1958
1959         /// Only needed for top level menus.
1960         MenuDefinition * top_level_menu;
1961         /// our owning view
1962         GuiView * view;
1963         /// the name of this menu
1964         QString name;
1965 };
1966
1967
1968
1969 /// Get a MenuDefinition item label from the menu backend
1970 static QString label(MenuItem const & mi)
1971 {
1972         QString label = mi.label();
1973         label.replace("&", "&&");
1974
1975         QString shortcut = mi.shortcut();
1976         if (!shortcut.isEmpty()) {
1977                 int pos = label.indexOf(shortcut);
1978                 if (pos != -1)
1979                         //label.insert(pos, 1, char_type('&'));
1980                         label.replace(pos, 0, "&");
1981         }
1982
1983         QString const binding = mi.binding();
1984         if (!binding.isEmpty())
1985                 label += '\t' + binding;
1986
1987         return label;
1988 }
1989
1990 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
1991 {
1992         LYXERR(Debug::GUI, "populating menu " << menu.name());
1993         if (menu.empty()) {
1994                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1995                 return;
1996         }
1997         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1998         for (MenuItem const & m : menu)
1999                 switch (m.kind()) {
2000                 case MenuItem::Separator:
2001                         qMenu->addSeparator();
2002                         break;
2003                 case MenuItem::Submenu: {
2004                         QMenu * subMenu = qMenu->addMenu(label(m));
2005                         populate(subMenu, m.submenu());
2006                         subMenu->setEnabled(!subMenu->isEmpty());
2007                         break;
2008                 }
2009                 case MenuItem::Command:
2010                 default:
2011                         // FIXME: A previous comment assured that MenuItem::Command was the
2012                         // only possible case in practice, but this is wrong.  It would be
2013                         // good to document which cases are actually treated here.
2014                         qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2015                                                     m.tooltip(), qMenu));
2016                         break;
2017                 }
2018 }
2019
2020 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2021 class AlwaysMnemonicStyle : public QProxyStyle {
2022 public:
2023         int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2024                 QStyleHintReturn *returnData = 0) const
2025         {
2026                 if (hint == QStyle::SH_UnderlineShortcut)
2027                         return 1;
2028                 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2029         }
2030 };
2031 #endif
2032
2033 /////////////////////////////////////////////////////////////////////
2034 // Menu implementation
2035 /////////////////////////////////////////////////////////////////////
2036
2037 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2038 : QMenu(gv), d(new Menu::Impl)
2039 {
2040 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2041         if (keyboard)
2042                 setStyle(new AlwaysMnemonicStyle);
2043 #else
2044         (void) keyboard;
2045 #endif
2046         d->top_level_menu = top_level? new MenuDefinition : 0;
2047         d->view = gv;
2048         d->name = name;
2049         setTitle(name);
2050         if (d->top_level_menu)
2051                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2052 }
2053
2054
2055 Menu::~Menu()
2056 {
2057         delete d->top_level_menu;
2058         delete d;
2059 }
2060
2061
2062 void Menu::updateView()
2063 {
2064         guiApp->menus().updateMenu(this);
2065 }
2066
2067
2068 void Menu::clear()
2069 {
2070         QList<QAction *> items = actions();
2071         for (int i = 0; i != items.size(); ++i) {
2072                 // QAction::menu() returns 0 if there's no submenu.
2073                 delete items.at(i)->menu();
2074         }
2075         QMenu::clear();
2076 }
2077
2078
2079 /////////////////////////////////////////////////////////////////////
2080 // Menus::Impl definition and implementation
2081 /////////////////////////////////////////////////////////////////////
2082
2083 struct Menus::Impl {
2084         ///
2085         bool hasMenu(QString const &) const;
2086         ///
2087         MenuDefinition & getMenu(QString const &);
2088         ///
2089         MenuDefinition const & getMenu(QString const &) const;
2090
2091         /// Expands some special entries of the menu
2092         /** The entries with the following kind are expanded to a
2093             sequence of Command MenuItems: Lastfiles, Documents,
2094             ViewFormats, ExportFormats, UpdateFormats, Branches,
2095             Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2096             EnvironmentSeparators
2097         */
2098         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2099                 BufferView const *) const;
2100
2101         /// Initialize specific MACOS X menubar
2102         void macxMenuBarInit(QMenuBar * qmb);
2103
2104         /// Mac special menu.
2105         /** This defines a menu whose entries list the FuncRequests
2106             that will be removed by expand() in other menus. This is
2107             used by the Qt/Mac code.
2108
2109             NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2110             such that the items will keep accessing the FuncRequests in
2111             the MenuDefinition. While Menus::Impl might be recreated,
2112             we keep mac_special_menu_ in memory by making it static.
2113         */
2114         static MenuDefinition mac_special_menu_;
2115
2116         ///
2117         MenuList menulist_;
2118         ///
2119         MenuDefinition menubar_;
2120
2121         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2122
2123         /// name to menu for \c menu() method.
2124         NameMap name_map_;
2125 };
2126
2127
2128 MenuDefinition Menus::Impl::mac_special_menu_;
2129
2130
2131 /*
2132   Here is what the Qt documentation says about how a menubar is chosen:
2133
2134      1) If the window has a QMenuBar then it is used. 2) If the window
2135      is a modal then its menubar is used. If no menubar is specified
2136      then a default menubar is used (as documented below) 3) If the
2137      window has no parent then the default menubar is used (as
2138      documented below).
2139
2140      The above 3 steps are applied all the way up the parent window
2141      chain until one of the above are satisifed. If all else fails a
2142      default menubar will be created, the default menubar on Qt/Mac is
2143      an empty menubar, however you can create a different default
2144      menubar by creating a parentless QMenuBar, the first one created
2145      will thus be designated the default menubar, and will be used
2146      whenever a default menubar is needed.
2147
2148   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2149   that this menubar will be used also when one of LyX' dialogs has
2150   focus. (JMarc)
2151 */
2152 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2153 {
2154         /* Since Qt 4.2, the qt/mac menu code has special code for
2155            specifying the role of a menu entry. However, it does not
2156            work very well with our scheme of creating menus on demand,
2157            and therefore we need to put these entries in a special
2158            invisible menu. (JMarc)
2159         */
2160
2161         /* The entries of our special mac menu. If we add support for
2162          * special entries in Menus, we could imagine something
2163          * like
2164          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
2165          * and therefore avoid hardcoding. I am not sure it is worth
2166          * the hassle, though. (JMarc)
2167          */
2168         struct MacMenuEntry {
2169                 FuncCode action;
2170                 char const * arg;
2171                 char const * label;
2172                 QAction::MenuRole role;
2173         };
2174
2175         static const MacMenuEntry entries[] = {
2176                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2177                  QAction::AboutRole},
2178                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2179                  QAction::PreferencesRole},
2180 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2181                 /* This doesn't work with Cocoa. */
2182                 {LFUN_RECONFIGURE, "", "Reconfigure",
2183                  QAction::ApplicationSpecificRole},
2184 #endif
2185                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2186         };
2187         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2188         const bool first_call = mac_special_menu_.empty();
2189
2190         LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2191         // the special menu for Menus. Fill it up only once.
2192         if (first_call) {
2193                 for (size_t i = 0 ; i < num_entries ; ++i) {
2194                         FuncRequest const func(entries[i].action,
2195                                 from_utf8(entries[i].arg));
2196                         mac_special_menu_.add(MenuItem(MenuItem::Command,
2197                                 entries[i].label, func));
2198                 }
2199         }
2200
2201         // add the entries to a QMenu that will eventually be empty
2202         // and therefore invisible.
2203         QMenu * qMenu = qmb->addMenu("special");
2204         size_t i = 0;
2205         for (MenuItem const & m : mac_special_menu_) {
2206                 Action * action = new Action(m.func(), QIcon(), m.label(),
2207                                              QString(), qMenu);
2208                 action->setMenuRole(entries[i].role);
2209                 qMenu->addAction(action);
2210                 ++i;
2211         }
2212 }
2213
2214
2215 void Menus::Impl::expand(MenuDefinition const & frommenu,
2216         MenuDefinition & tomenu, BufferView const * bv) const
2217 {
2218         if (!tomenu.empty())
2219                 tomenu.clear();
2220
2221         for (MenuDefinition::const_iterator cit = frommenu.begin();
2222              cit != frommenu.end() ; ++cit) {
2223                 Buffer const * buf = bv ? &bv->buffer() : 0;
2224                 switch (cit->kind()) {
2225                 case MenuItem::Lastfiles:
2226                         tomenu.expandLastfiles();
2227                         break;
2228
2229                 case MenuItem::Documents:
2230                         tomenu.expandDocuments();
2231                         break;
2232
2233                 case MenuItem::Bookmarks:
2234                         tomenu.expandBookmarks();
2235                         break;
2236
2237                 case MenuItem::ImportFormats:
2238                 case MenuItem::ViewFormats:
2239                 case MenuItem::UpdateFormats:
2240                 case MenuItem::ExportFormats:
2241                         tomenu.expandFormats(cit->kind(), buf);
2242                         break;
2243
2244                 case MenuItem::ExportFormat: {
2245                         if (!buf)
2246                                 break;
2247                         string const format = buf->params().getDefaultOutputFormat();
2248                         Format const * f = theFormats().getFormat(format);
2249                         docstring const name = f ? f->prettyname() : from_utf8(format);
2250                         docstring const label = bformat(_("Export [%1$s]|E"), name);
2251                         MenuItem item(MenuItem::Command, toqstr(label),
2252                                       FuncRequest(LFUN_BUFFER_EXPORT));
2253                         tomenu.addWithStatusCheck(item);
2254                         break;
2255                 }
2256
2257                 case MenuItem::CharStyles:
2258                         tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2259                         break;
2260
2261                 case MenuItem::Custom:
2262                         tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2263                         break;
2264
2265                 case MenuItem::Elements:
2266                         tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2267                         break;
2268
2269                 case MenuItem::FloatListInsert:
2270                         tomenu.expandFloatListInsert(buf);
2271                         break;
2272
2273                 case MenuItem::FloatInsert:
2274                         tomenu.expandFloatInsert(buf);
2275                         break;
2276
2277                 case MenuItem::PasteRecent:
2278                         tomenu.expandPasteRecent(buf);
2279                         break;
2280
2281                 case MenuItem::Toolbars:
2282                         tomenu.expandToolbars();
2283                         break;
2284
2285                 case MenuItem::Branches:
2286                         tomenu.expandBranches(buf);
2287                         break;
2288
2289                 case MenuItem::Indices:
2290                         tomenu.expandIndices(buf);
2291                         break;
2292
2293                 case MenuItem::IndicesContext:
2294                         tomenu.expandIndicesContext(buf);
2295                         break;
2296
2297                 case MenuItem::IndicesLists:
2298                         tomenu.expandIndices(buf, true);
2299                         break;
2300
2301                 case MenuItem::IndicesListsContext:
2302                         tomenu.expandIndicesContext(buf, true);
2303                         break;
2304
2305                 case MenuItem::CiteStyles:
2306                         tomenu.expandCiteStyles(bv);
2307                         break;
2308
2309                 case MenuItem::Toc:
2310                         tomenu.expandToc(buf);
2311                         break;
2312
2313                 case MenuItem::GraphicsGroups:
2314                         tomenu.expandGraphicsGroups(bv);
2315                         break;
2316
2317                 case MenuItem::SpellingSuggestions:
2318                         tomenu.expandSpellingSuggestions(bv);
2319                         break;
2320
2321                 case MenuItem::LanguageSelector:
2322                         tomenu.expandLanguageSelector(buf);
2323                         break;
2324
2325                 case MenuItem::Arguments:
2326                         tomenu.expandArguments(bv, false);
2327                         break;
2328
2329                 case MenuItem::SwitchArguments:
2330                         tomenu.expandArguments(bv, true);
2331                         break;
2332
2333                 case MenuItem::Captions:
2334                         tomenu.expandCaptions(buf, false);
2335                         break;
2336
2337                 case MenuItem::SwitchCaptions:
2338                         tomenu.expandCaptions(buf, true);
2339                         break;
2340
2341                 case MenuItem::EnvironmentSeparators:
2342                         tomenu.expandEnvironmentSeparators(bv);
2343                         break;
2344
2345                 case MenuItem::EnvironmentSeparatorsContext:
2346                         tomenu.expandEnvironmentSeparators(bv, true);
2347                         break;
2348
2349                 case MenuItem::SwitchQuotes:
2350                         tomenu.expandQuotes(bv);
2351                         break;
2352
2353                 case MenuItem::Submenu: {
2354                         MenuItem item(*cit);
2355                         item.setSubmenu(MenuDefinition(cit->submenuname()));
2356                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
2357                         tomenu.addWithStatusCheck(item);
2358                 }
2359                 break;
2360
2361                 case MenuItem::Info:
2362                 case MenuItem::Help:
2363                 case MenuItem::Separator:
2364                         tomenu.addWithStatusCheck(*cit);
2365                         break;
2366
2367                 case MenuItem::Command:
2368                         if (!mac_special_menu_.hasFunc(*cit->func()))
2369                                 tomenu.addWithStatusCheck(*cit);
2370                 }
2371         }
2372
2373         // we do not want the menu to end with a separator
2374         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2375                 tomenu.items_.pop_back();
2376
2377         // Check whether the shortcuts are unique
2378         tomenu.checkShortcuts();
2379 }
2380
2381
2382 bool Menus::Impl::hasMenu(QString const & name) const
2383 {
2384         return find_if(menulist_.begin(), menulist_.end(),
2385                 MenuNamesEqual(name)) != menulist_.end();
2386 }
2387
2388
2389 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2390 {
2391         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2392                 MenuNamesEqual(name));
2393         if (cit == menulist_.end()) {
2394                 LYXERR0("No submenu named " << name);
2395                 LASSERT(false, { static const MenuDefinition m; return m; });
2396         }
2397         return (*cit);
2398 }
2399
2400
2401 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2402 {
2403         iterator it = find_if(menulist_.begin(), menulist_.end(),
2404                 MenuNamesEqual(name));
2405         if (it == menulist_.end()) {
2406                 LYXERR0("No submenu named " << name);
2407                 LASSERT(false, { static MenuDefinition m; return m; });
2408         }
2409         return (*it);
2410 }
2411
2412
2413 /////////////////////////////////////////////////////////////////////
2414 //
2415 // Menus
2416 //
2417 /////////////////////////////////////////////////////////////////////
2418
2419 Menus::Menus() : d(new Impl) {}
2420
2421
2422 Menus::~Menus()
2423 {
2424         delete d;
2425 }
2426
2427
2428 void Menus::reset()
2429 {
2430         delete d;
2431         d = new Impl;
2432 }
2433
2434
2435 void Menus::read(Lexer & lex)
2436 {
2437         enum {
2438                 md_menu,
2439                 md_menubar,
2440                 md_endmenuset
2441         };
2442
2443         LexerKeyword menutags[] = {
2444                 { "end", md_endmenuset },
2445                 { "menu", md_menu },
2446                 { "menubar", md_menubar }
2447         };
2448
2449         // consistency check
2450         if (compare_ascii_no_case(lex.getString(), "menuset"))
2451                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2452
2453         lex.pushTable(menutags);
2454         lex.setContext("Menus::read");
2455
2456         bool quit = false;
2457
2458         while (lex.isOK() && !quit) {
2459                 switch (lex.lex()) {
2460                 case md_menubar:
2461                         d->menubar_.read(lex);
2462                         break;
2463                 case md_menu: {
2464                         lex.next(true);
2465                         QString const name = toqstr(lex.getDocString());
2466                         if (d->hasMenu(name))
2467                                 d->getMenu(name).read(lex);
2468                         else {
2469                                 MenuDefinition menu(name);
2470                                 menu.read(lex);
2471                                 d->menulist_.push_back(menu);
2472                         }
2473                         break;
2474                 }
2475                 case md_endmenuset:
2476                         quit = true;
2477                         break;
2478                 default:
2479                         lex.printError("Unknown menu tag");
2480                         break;
2481                 }
2482         }
2483         lex.popTable();
2484 }
2485
2486
2487 bool Menus::searchMenu(FuncRequest const & func,
2488         docstring_list & names) const
2489 {
2490         MenuDefinition menu;
2491         d->expand(d->menubar_, menu, 0);
2492         return menu.searchMenu(func, names);
2493 }
2494
2495
2496 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2497 {
2498         if (initial) {
2499 #ifdef Q_OS_MAC
2500                 // setup special mac specific menu items, but only do this
2501                 // the first time a QMenuBar is created. Otherwise Qt will
2502                 // create duplicate items in the application menu. It seems
2503                 // that Qt does not remove them when the QMenubar is cleared.
2504                 d->macxMenuBarInit(qmb);
2505 #endif
2506         } else {
2507                 // Clear all menubar contents before filling it.
2508                 qmb->clear();
2509 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2510                 d->macxMenuBarInit(qmb);
2511 #endif
2512         }
2513
2514         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2515
2516         if (d->menubar_.empty()) {
2517                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2518                         << d->menubar_.name());
2519                 return;
2520         }
2521         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2522
2523         MenuDefinition menu;
2524         BufferView * bv = 0;
2525         if (view)
2526                 bv = view->currentBufferView();
2527         d->expand(d->menubar_, menu, bv);
2528
2529         MenuDefinition::const_iterator m = menu.begin();
2530         MenuDefinition::const_iterator end = menu.end();
2531
2532         for (; m != end; ++m) {
2533
2534                 if (m->kind() != MenuItem::Submenu) {
2535                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2536                         continue;
2537                 }
2538
2539                 LYXERR(Debug::GUI, "menu bar item " << m->label()
2540                         << " is a submenu named " << m->submenuname());
2541
2542                 QString name = m->submenuname();
2543                 if (!d->hasMenu(name)) {
2544                         LYXERR(Debug::GUI, "\tERROR: " << name
2545                                 << " submenu has no menu!");
2546                         continue;
2547                 }
2548
2549                 Menu * menuptr = new Menu(view, m->submenuname(), true);
2550                 menuptr->setTitle(label(*m));
2551
2552 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2553                 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2554                 // so we create a temporary one here
2555                 QAction * action = new QAction(menuptr);
2556                 menuptr->addAction(action);
2557 #endif
2558
2559                 qmb->addMenu(menuptr);
2560
2561                 d->name_map_[view][name] = menuptr;
2562         }
2563 }
2564
2565
2566 void Menus::updateMenu(Menu * qmenu)
2567 {
2568         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2569         qmenu->clear();
2570
2571         if (qmenu->d->name.isEmpty())
2572                 return;
2573
2574         docstring identifier = qstring_to_ucs4(qmenu->d->name);
2575         MenuDefinition fromLyxMenu(qmenu->d->name);
2576         while (!identifier.empty()) {
2577                 docstring menu_name;
2578                 identifier = split(identifier, menu_name, ';');
2579
2580                 if (!d->hasMenu(toqstr(menu_name))) {
2581                         LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2582                                 << menu_name);
2583                         continue;
2584                 }
2585
2586                 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2587                 //FIXME: 50 is a wild guess. We should take into account here
2588                 //the expansion of menu items, disabled optional items etc.
2589                 bool const in_sub_menu = !fromLyxMenu.empty()
2590                         && fromLyxMenu.size() + cat_menu.size() > 50 ;
2591                 if (in_sub_menu)
2592                         fromLyxMenu.catSub(menu_name);
2593                 else
2594                         fromLyxMenu.cat(cat_menu);
2595                 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2596         }
2597
2598         if (fromLyxMenu.empty()) {
2599                 qmenu->addAction(qt_("No Action Defined!"));
2600                 return;
2601         }
2602
2603         BufferView * bv = 0;
2604         if (qmenu->d->view)
2605                 bv = qmenu->d->view->currentBufferView();
2606         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2607         qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2608 }
2609
2610
2611 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2612 {
2613         LYXERR(Debug::GUI, "Context menu requested: " << name);
2614         Menu * menu = d->name_map_[&view].value(name, 0);
2615         if (!menu && !name.startsWith("context-")) {
2616                 LYXERR0("requested context menu not found: " << name);
2617                 return 0;
2618         }
2619
2620         menu = new Menu(&view, name, true, keyboard);
2621         d->name_map_[&view][name] = menu;
2622         return menu;
2623 }
2624
2625 } // namespace frontend
2626 } // namespace lyx
2627
2628 #include "moc_Menus.cpp"