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