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