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