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