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