]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
Encapsulate all menu related stuff inside Menu.cpp and simplify a few things.
[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
25 #include "BranchList.h"
26 #include "Buffer.h"
27 #include "BufferList.h"
28 #include "BufferParams.h"
29 #include "Converter.h"
30 #include "CutAndPaste.h"
31 #include "Floating.h"
32 #include "FloatList.h"
33 #include "Format.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "KeyMap.h"
37 #include "Lexer.h"
38 #include "LyXAction.h"
39 #include "LyX.h" // for lastfiles
40 #include "LyXFunc.h"
41 #include "Paragraph.h"
42 #include "qt_helpers.h"
43 #include "Session.h"
44 #include "TextClass.h"
45 #include "TocBackend.h"
46 #include "ToolbarBackend.h"
47
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/filetools.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h"
53
54 #include <QCursor>
55 #include <QHash>
56 #include <QMenuBar>
57 #include <QString>
58
59 #include <boost/shared_ptr.hpp>
60
61 #include <algorithm>
62 #include <ostream>
63 #include <vector>
64
65 using namespace std;
66 using namespace lyx::support;
67
68
69 namespace lyx {
70 namespace frontend {
71
72 namespace {
73
74 // MacOSX specific stuff is at the end.
75
76 class Menu;
77
78 ///
79 class MenuItem {
80 public:
81         /// The type of elements that can be in a menu
82         enum Kind {
83                 ///
84                 Command,
85                 ///
86                 Submenu,
87                 ///
88                 Separator,
89                 /** This is the list of last opened file,
90                     typically for the File menu. */
91                 Lastfiles,
92                 /** This is the list of opened Documents,
93                     typically for the Documents menu. */
94                 Documents,
95                 /** This is the bookmarks */
96                 Bookmarks,
97                 ///
98                 Toc,
99                 /** This is a list of viewable formats
100                     typically for the File->View menu. */
101                 ViewFormats,
102                 /** This is a list of updatable formats
103                     typically for the File->Update menu. */
104                 UpdateFormats,
105                 /** This is a list of exportable formats
106                     typically for the File->Export menu. */
107                 ExportFormats,
108                 /** This is a list of importable formats
109                     typically for the File->Export menu. */
110                 ImportFormats,
111                 /** This is the list of elements available
112                  * for insertion into document. */
113                 CharStyles,
114                 /** This is the list of user-configurable
115                 insets to insert into document */
116                 Custom,
117                 /** This is the list of XML elements to
118                 insert into the document */
119                 Elements,
120                 /** This is the list of floats that we can
121                     insert a list for. */
122                 FloatListInsert,
123                 /** This is the list of floats that we can
124                     insert. */
125                 FloatInsert,
126                 /** This is the list of selections that can
127                     be pasted. */
128                 PasteRecent,
129                 /** toolbars */
130                 Toolbars,
131                 /** Available branches in document */
132                 Branches
133         };
134
135         explicit MenuItem(Kind kind);
136
137         MenuItem(Kind kind,
138                  QString const & label,
139                  QString const & submenu = QString(),
140                  bool optional = false);
141
142         MenuItem(Kind kind,
143                  QString const & label,
144                  FuncRequest const & func,
145                  bool optional = false);
146
147         /// This one is just to please boost::shared_ptr<>
148         ~MenuItem();
149         /// The label of a given menuitem
150         QString label() const;
151         /// The keyboard shortcut (usually underlined in the entry)
152         QString shortcut() const;
153         /// The complete label, with label and shortcut separated by a '|'
154         QString fulllabel() const { return label_;}
155         /// The kind of entry
156         Kind kind() const { return kind_; }
157         /// the action (if relevant)
158         FuncRequest const & func() const { return func_; }
159         /// returns true if the entry should be ommited when disabled
160         bool optional() const { return optional_; }
161         /// returns the status of the lfun associated with this entry
162         FuncStatus const & status() const { return status_; }
163         /// returns the status of the lfun associated with this entry
164         FuncStatus & status() { return status_; }
165         /// returns the status of the lfun associated with this entry
166         void status(FuncStatus const & status) { status_ = status; }
167         ///returns the binding associated to this action.
168         QString binding() const;
169         /// the description of the  submenu (if relevant)
170         QString const & submenuname() const { return submenuname_; }
171         /// set the description of the  submenu
172         void submenuname(QString const & name) { submenuname_ = name; }
173         ///
174         Menu * submenu() const { return submenu_.get(); }
175         ///
176         void setSubmenu(Menu * menu);
177
178 private:
179         ///
180         Kind kind_;
181         ///
182         QString label_;
183         ///
184         FuncRequest func_;
185         ///
186         QString submenuname_;
187         ///
188         bool optional_;
189         ///
190         FuncStatus status_;
191         ///
192         boost::shared_ptr<Menu> submenu_;
193 };
194
195 ///
196 class Menu {
197 public:
198         ///
199         typedef std::vector<MenuItem> ItemList;
200         ///
201         typedef ItemList::const_iterator const_iterator;
202
203         ///
204         explicit Menu(QString const & name = QString()) : name_(name) {}
205
206         ///
207         void read(Lexer &);
208         ///
209         QString const & name() const { return name_; }
210         ///
211         bool empty() const { return items_.empty(); }
212         /// Clear the menu content.
213         void clear() { items_.clear(); }
214         ///
215         size_t size() const { return items_.size(); }
216         ///
217         MenuItem const & operator[](size_t) const;
218         ///
219         const_iterator begin() const { return items_.begin(); }
220         ///
221         const_iterator end() const { return items_.end(); }
222         
223         // search for func in this menu iteratively, and put menu
224         // names in a stack.
225         bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
226                 const;
227
228 private:
229         friend class Menus;
230         ///
231         bool hasFunc(FuncRequest const &) const;
232         /// Add the menu item unconditionally
233         void add(MenuItem const & item) { items_.push_back(item); }
234         /// Checks the associated FuncRequest status before adding the
235         /// menu item.
236         void addWithStatusCheck(MenuItem const &);
237         // Check whether the menu shortcuts are unique
238         void checkShortcuts() const;
239         ///
240         void expandLastfiles();
241         void expandDocuments();
242         void expandBookmarks();
243         void expandFormats(MenuItem::Kind kind, Buffer const * buf);
244         void expandFloatListInsert(Buffer const * buf);
245         void expandFloatInsert(Buffer const * buf);
246         void expandFlexInsert(Buffer const * buf, std::string s);
247         void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
248         void expandToc(Buffer const * buf);
249         void expandPasteRecent();
250         void expandToolbars();
251         void expandBranches(Buffer const * buf);
252
253         ItemList items_;
254         ///
255         QString name_;
256 };
257
258 /// a submenu
259 class GuiPopupMenu : public QMenu
260 {
261 public:
262         ///
263         GuiPopupMenu(GuiView * owner, MenuItem const & mi, bool top_level)
264                 : QMenu(owner), owner_(owner), top_level_(top_level)
265         {
266                 name_ = mi.submenuname();
267                 setTitle(label(mi));
268         }
269
270         /// populates the menu or one of its submenu
271         /// This is used as a recursive function
272         void populate(QMenu * qMenu, Menu * menu);
273
274         /// Get a Menu item label from the menu backend
275         QString label(MenuItem const & mi) const;
276
277         void showEvent(QShowEvent * ev)
278         {
279                 if (top_level_)
280                         guiApp->menus().updateMenu(name_);
281                 QMenu::showEvent(ev);
282         }
283
284         bool const top_level_;
285
286         ///
287         Menu topLevelMenu_;
288
289         /// our owning view
290         GuiView * owner_;
291         /// the name of this menu
292         QString name_;
293 };
294
295
296 class MenuNamesEqual
297 {
298 public:
299         MenuNamesEqual(QString const & name) : name_(name) {}
300         bool operator()(Menu const & menu) const { return menu.name() == name_; }
301 private:
302         QString name_;
303 };
304
305 ///
306 typedef std::vector<Menu> MenuList;
307 ///
308 typedef MenuList::const_iterator const_iterator;
309 ///
310 typedef MenuList::iterator iterator;
311
312
313 void GuiPopupMenu::populate(QMenu * qMenu, Menu * menu)
314 {
315         LYXERR(Debug::GUI, "populating menu " << fromqstr(menu->name()));
316         if (menu->size() == 0) {
317                 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu->name()));
318                 return;
319         }
320         LYXERR(Debug::GUI, " *****  menu entries " << menu->size());
321
322         Menu::const_iterator m = menu->begin();
323         Menu::const_iterator end = menu->end();
324
325         for (; m != end; ++m) {
326
327                 if (m->kind() == MenuItem::Separator) {
328
329                         qMenu->addSeparator();
330                         LYXERR(Debug::GUI, "adding Menubar Separator");
331
332                 } else if (m->kind() == MenuItem::Submenu) {
333
334                         LYXERR(Debug::GUI, "** creating New Sub-Menu "
335                                 << fromqstr(label(*m)));
336                         QMenu * subMenu = qMenu->addMenu(label(*m));
337                         populate(subMenu, m->submenu());
338
339                 } else { // we have a MenuItem::Command
340
341                         LYXERR(Debug::GUI, "creating Menu Item "
342                                 << fromqstr(m->label()));
343
344                         Action * action = new Action(*owner_,
345                                 QIcon(), label(*m), m->func(), QString());
346                         qMenu->addAction(action);
347                 }
348         }
349 }
350
351
352 QString GuiPopupMenu::label(MenuItem const & mi) const
353 {
354         QString label = mi.label();
355         label.replace("&", "&&");
356
357         QString shortcut = mi.shortcut();
358         if (!shortcut.isEmpty()) {
359                 int pos = label.indexOf(shortcut);
360                 if (pos != -1)
361                         //label.insert(pos, 1, char_type('&'));
362                         label.replace(pos, 0, "&");
363         }
364
365         QString const binding = mi.binding();
366         if (!binding.isEmpty())
367                 label += '\t' + binding;
368
369         return label;
370 }
371
372 } // namespace anon
373
374 struct Menus::Impl {
375         ///
376         void add(Menu const &);
377         ///
378         bool hasMenu(QString const &) const;
379         ///
380         Menu & getMenu(QString const &);
381         ///
382         Menu const & getMenu(QString const &) const;
383         ///
384         bool empty() const { return menulist_.empty(); }
385         /** This defines a menu whose entries list the FuncRequests
386             that will be removed by expand() in other menus. This is
387             used by the Qt/Mac code
388         */
389         void setSpecialMenu(Menu const & menu) { specialmenu_ = menu; }
390         ///
391         Menu const & specialMenu() { return specialmenu_; }
392
393         /// Expands some special entries of the menu
394         /** The entries with the following kind are expanded to a
395             sequence of Command MenuItems: Lastfiles, Documents,
396             ViewFormats, ExportFormats, UpdateFormats, Branches
397         */
398         void expand(Menu const & frommenu, Menu & tomenu,
399                     Buffer const *) const;
400         ///
401         const_iterator begin() const { return menulist_.begin(); }
402         ///
403         iterator begin() { return menulist_.begin(); }
404         ///
405         const_iterator end() const { return menulist_.end(); }
406         ///
407         iterator end() { return menulist_.end(); }
408
409         ///
410         MenuList menulist_;
411         ///
412         Menu menubar_;
413         ///
414         Menu specialmenu_;
415
416         /// Initialize specific MACOS X menubar
417         void macxMenuBarInit(GuiView * view);
418
419         typedef QHash<QString, GuiPopupMenu *> NameMap;
420
421         /// name to menu for \c menu() method.
422         NameMap name_map_;
423 };
424
425
426 Menus::Menus(): d(new Impl) {}
427
428
429 bool Menus::searchMenu(FuncRequest const & func,
430         vector<docstring> & names) const
431 {
432         return d->menubar_.searchMenu(func, names);
433 }
434
435
436 void Menus::fillMenuBar(GuiView * view)
437 {
438         // Clear all menubar contents before filling it.
439         view->menuBar()->clear();
440         
441 #ifdef Q_WS_MACX
442         // setup special mac specific menu item
443         macxMenuBarInit(view);
444 #endif
445
446         LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
447
448         if (d->menubar_.size() == 0) {
449                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
450                         << fromqstr(d->menubar_.name()));
451                 return;
452         }
453         else {
454                 LYXERR(Debug::GUI, "menu bar entries "
455                         << d->menubar_.size());
456         }
457
458         Menu menu;
459         d->expand(d->menubar_, menu, view->buffer());
460
461         Menu::const_iterator m = menu.begin();
462         Menu::const_iterator end = menu.end();
463
464         for (; m != end; ++m) {
465
466                 if (m->kind() != MenuItem::Submenu) {
467                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
468                         continue;
469                 }
470
471                 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
472                         << " is a submenu named " << fromqstr(m->submenuname()));
473
474                 QString name = m->submenuname();
475                 if (!d->hasMenu(name)) {
476                         LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
477                                 << " submenu has no menu!");
478                         continue;
479                 }
480
481                 GuiPopupMenu * qmenu = new GuiPopupMenu(view, *m, true);
482                 view->menuBar()->addMenu(qmenu);
483
484                 d->name_map_[name] = qmenu;
485         }
486 }
487
488
489 void Menus::updateMenu(QString const & name)
490 {
491         GuiPopupMenu * qmenu = d->name_map_[name];
492         LYXERR(Debug::GUI, "GuiPopupMenu::updateView()"
493                 << "\tTriggered menu: " << fromqstr(qmenu->name_));
494         qmenu->clear();
495
496         if (qmenu->name_.isEmpty())
497                 return;
498
499         // Here, We make sure that theLyXFunc points to the correct LyXView.
500         theLyXFunc().setLyXView(qmenu->owner_);
501
502         Menu const & fromLyxMenu = d->getMenu(qmenu->name_);
503         d->expand(fromLyxMenu, qmenu->topLevelMenu_, qmenu->owner_->buffer());
504
505         if (!d->hasMenu(qmenu->topLevelMenu_.name())) {
506                 LYXERR(Debug::GUI, "\tWARNING: menu seems empty"
507                         << fromqstr(qmenu->topLevelMenu_.name()));
508         }
509         qmenu->populate(qmenu, &qmenu->topLevelMenu_);
510 }
511
512
513 QMenu * Menus::menu(QString const & name)
514 {
515         LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
516         GuiPopupMenu * menu = d->name_map_.value(name, 0);
517         if (!menu)
518                 LYXERR0("resquested context menu not found: " << fromqstr(name));
519         return menu;
520 }
521
522
523 /// Some special Qt/Mac support hacks
524
525 /*
526   Here is what the Qt documentation says about how a menubar is chosen:
527
528      1) If the window has a QMenuBar then it is used. 2) If the window
529      is a modal then its menubar is used. If no menubar is specified
530      then a default menubar is used (as documented below) 3) If the
531      window has no parent then the default menubar is used (as
532      documented below).
533
534      The above 3 steps are applied all the way up the parent window
535      chain until one of the above are satisifed. If all else fails a
536      default menubar will be created, the default menubar on Qt/Mac is
537      an empty menubar, however you can create a different default
538      menubar by creating a parentless QMenuBar, the first one created
539      will thus be designated the default menubar, and will be used
540      whenever a default menubar is needed.
541
542   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
543   that this menubar will be used also when one of LyX' dialogs has
544   focus. (JMarc)
545 */
546
547 void Menus::Impl::macxMenuBarInit(GuiView * view)
548 {
549         // The Mac menubar initialisation must be done only once!
550         static bool done = false;
551         if (done)
552                 return;
553         done = true;
554
555         /* Since Qt 4.2, the qt/mac menu code has special code for
556            specifying the role of a menu entry. However, it does not
557            work very well with our scheme of creating menus on demand,
558            and therefore we need to put these entries in a special
559            invisible menu. (JMarc)
560         */
561
562         /* The entries of our special mac menu. If we add support for
563          * special entries in Menus, we could imagine something
564          * like
565          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
566          * and therefore avoid hardcoding. I am not sure it is worth
567          * the hassle, though. (JMarc)
568          */
569         struct MacMenuEntry {
570                 kb_action action;
571                 char const * arg;
572                 char const * label;
573                 QAction::MenuRole role;
574         };
575
576         MacMenuEntry entries[] = {
577                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
578                  QAction::AboutRole},
579                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
580                  QAction::PreferencesRole},
581                 {LFUN_RECONFIGURE, "", "Reconfigure",
582                  QAction::ApplicationSpecificRole},
583                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
584         };
585         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
586
587         // the special menu for Menus.
588         Menu special;
589         for (size_t i = 0 ; i < num_entries ; ++i) {
590                 FuncRequest const func(entries[i].action,
591                                        from_utf8(entries[i].arg));
592                 special.add(MenuItem(MenuItem::Command, entries[i].label, func));
593         }
594         setSpecialMenu(special);
595
596         // add the entries to a QMenu that will eventually be empty
597         // and therefore invisible.
598         QMenu * qMenu = view->menuBar()->addMenu("special");
599
600         // we do not use 'special' because it is a temporary variable,
601         // whereas Menus::specialMenu points to a persistent copy.
602         Menu::const_iterator cit = specialMenu().begin();
603         Menu::const_iterator end = specialMenu().end();
604         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
605                 Action * action = new Action(*view, QIcon(), cit->label(),
606                                              cit->func(), QString());
607                 action->setMenuRole(entries[i].role);
608                 qMenu->addAction(action);
609         }
610 }
611
612
613 MenuItem::MenuItem(Kind kind)
614         : kind_(kind), optional_(false)
615 {}
616
617
618 MenuItem::MenuItem(Kind kind, QString const & label,
619                    QString const & submenu, bool optional)
620         : kind_(kind), label_(label),
621           submenuname_(submenu), optional_(optional)
622 {
623         BOOST_ASSERT(kind == Submenu);
624 }
625
626
627 MenuItem::MenuItem(Kind kind, QString const & label,
628                    FuncRequest const & func, bool optional)
629         : kind_(kind), label_(label), func_(func), optional_(optional)
630 {
631         func_.origin = FuncRequest::MENU;
632 }
633
634
635 MenuItem::~MenuItem()
636 {}
637
638
639 void MenuItem::setSubmenu(Menu * menu)
640 {
641         submenu_.reset(menu);
642 }
643
644
645 QString MenuItem::label() const
646 {
647         return label_.split('|')[0];
648 }
649
650
651 QString MenuItem::shortcut() const
652 {
653         return label_.contains('|') ? label_.split('|')[1] : QString();
654 }
655
656
657 QString MenuItem::binding() const
658 {
659         if (kind_ != Command)
660                 return QString();
661
662         // Get the keys bound to this action, but keep only the
663         // first one later
664         KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
665
666         if (bindings.size())
667                 return toqstr(bindings.begin()->print(KeySequence::ForGui));
668
669         LYXERR(Debug::KBMAP, "No binding for "
670                 << lyxaction.getActionName(func_.action)
671                 << '(' << func_.argument() << ')');
672         return QString();
673 }
674
675
676 void Menu::addWithStatusCheck(MenuItem const & i)
677 {
678         switch (i.kind()) {
679
680         case MenuItem::Command: {
681                 FuncStatus status = lyx::getStatus(i.func());
682                 if (status.unknown() || (!status.enabled() && i.optional()))
683                         break;
684                 items_.push_back(i);
685                 items_.back().status(status);
686                 break;
687         }
688
689         case MenuItem::Submenu: {
690                 if (i.submenu()) {
691                         bool enabled = false;
692                         for (const_iterator cit = i.submenu()->begin();
693                              cit != i.submenu()->end(); ++cit) {
694                                 if ((cit->kind() == MenuItem::Command
695                                      || cit->kind() == MenuItem::Submenu)
696                                     && cit->status().enabled()) {
697                                         enabled = true;
698                                         break;
699                                 }
700                         }
701                         if (enabled || !i.optional()) {
702                                 items_.push_back(i);
703                                 items_.back().status().enabled(enabled);
704                         }
705                 }
706                 else
707                         items_.push_back(i);
708                 break;
709         }
710
711         case MenuItem::Separator:
712                 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
713                         items_.push_back(i);
714                 break;
715
716         default:
717                 items_.push_back(i);
718         }
719 }
720
721
722 void Menu::read(Lexer & lex)
723 {
724         enum Menutags {
725                 md_item = 1,
726                 md_branches,
727                 md_documents,
728                 md_bookmarks,
729                 md_charstyles,
730                 md_custom,
731                 md_elements,
732                 md_endmenu,
733                 md_exportformats,
734                 md_importformats,
735                 md_lastfiles,
736                 md_optitem,
737                 md_optsubmenu,
738                 md_separator,
739                 md_submenu,
740                 md_toc,
741                 md_updateformats,
742                 md_viewformats,
743                 md_floatlistinsert,
744                 md_floatinsert,
745                 md_pasterecent,
746                 md_toolbars,
747                 md_last
748         };
749
750         struct keyword_item menutags[md_last - 1] = {
751                 { "bookmarks", md_bookmarks },
752                 { "branches", md_branches },
753                 { "charstyles", md_charstyles },
754                 { "custom", md_custom },
755                 { "documents", md_documents },
756                 { "elements", md_elements },
757                 { "end", md_endmenu },
758                 { "exportformats", md_exportformats },
759                 { "floatinsert", md_floatinsert },
760                 { "floatlistinsert", md_floatlistinsert },
761                 { "importformats", md_importformats },
762                 { "item", md_item },
763                 { "lastfiles", md_lastfiles },
764                 { "optitem", md_optitem },
765                 { "optsubmenu", md_optsubmenu },
766                 { "pasterecent", md_pasterecent },
767                 { "separator", md_separator },
768                 { "submenu", md_submenu },
769                 { "toc", md_toc },
770                 { "toolbars", md_toolbars },
771                 { "updateformats", md_updateformats },
772                 { "viewformats", md_viewformats }
773         };
774
775         lex.pushTable(menutags, md_last - 1);
776         if (lyxerr.debugging(Debug::PARSER))
777                 lex.printTable(lyxerr);
778
779         bool quit = false;
780         bool optional = false;
781
782         while (lex.isOK() && !quit) {
783                 switch (lex.lex()) {
784                 case md_optitem:
785                         optional = true;
786                         // fallback to md_item
787                 case md_item: {
788                         lex.next(true);
789                         docstring const name = translateIfPossible(lex.getDocString());
790                         lex.next(true);
791                         string const command = lex.getString();
792                         FuncRequest func = lyxaction.lookupFunc(command);
793                         add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
794                         optional = false;
795                         break;
796                 }
797
798                 case md_separator:
799                         add(MenuItem(MenuItem::Separator));
800                         break;
801
802                 case md_lastfiles:
803                         add(MenuItem(MenuItem::Lastfiles));
804                         break;
805
806                 case md_charstyles:
807                         add(MenuItem(MenuItem::CharStyles));
808                         break;
809
810                 case md_custom:
811                         add(MenuItem(MenuItem::Custom));
812                         break;
813
814                 case md_elements:
815                         add(MenuItem(MenuItem::Elements));
816                         break;
817
818                 case md_documents:
819                         add(MenuItem(MenuItem::Documents));
820                         break;
821
822                 case md_bookmarks:
823                         add(MenuItem(MenuItem::Bookmarks));
824                         break;
825
826                 case md_toc:
827                         add(MenuItem(MenuItem::Toc));
828                         break;
829
830                 case md_viewformats:
831                         add(MenuItem(MenuItem::ViewFormats));
832                         break;
833
834                 case md_updateformats:
835                         add(MenuItem(MenuItem::UpdateFormats));
836                         break;
837
838                 case md_exportformats:
839                         add(MenuItem(MenuItem::ExportFormats));
840                         break;
841
842                 case md_importformats:
843                         add(MenuItem(MenuItem::ImportFormats));
844                         break;
845
846                 case md_floatlistinsert:
847                         add(MenuItem(MenuItem::FloatListInsert));
848                         break;
849
850                 case md_floatinsert:
851                         add(MenuItem(MenuItem::FloatInsert));
852                         break;
853
854                 case md_pasterecent:
855                         add(MenuItem(MenuItem::PasteRecent));
856                         break;
857
858                 case md_toolbars:
859                         add(MenuItem(MenuItem::Toolbars));
860                         break;
861
862                 case md_branches:
863                         add(MenuItem(MenuItem::Branches));
864                         break;
865
866                 case md_optsubmenu:
867                         optional = true;
868                         // fallback to md_submenu
869                 case md_submenu: {
870                         lex.next(true);
871                         docstring const mlabel = translateIfPossible(lex.getDocString());
872                         lex.next(true);
873                         docstring const mname = lex.getDocString();
874                         add(MenuItem(MenuItem::Submenu,
875                                 toqstr(mlabel), toqstr(mname), optional));
876                         optional = false;
877                         break;
878                 }
879
880                 case md_endmenu:
881                         quit = true;
882                         break;
883
884                 default:
885                         lex.printError("Menu::read: "
886                                        "Unknown menu tag: `$$Token'");
887                         break;
888                 }
889         }
890         lex.popTable();
891 }
892
893
894 MenuItem const & Menu::operator[](size_type i) const
895 {
896         return items_[i];
897 }
898
899
900 bool Menu::hasFunc(FuncRequest const & func) const
901 {
902         for (const_iterator it = begin(), et = end(); it != et; ++it)
903                 if (it->func() == func)
904                         return true;
905         return false;
906 }
907
908
909 void Menu::checkShortcuts() const
910 {
911         // This is a quadratic algorithm, but we do not care because
912         // menus are short enough
913         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
914                 QString shortcut = it1->shortcut();
915                 if (shortcut.isEmpty())
916                         continue;
917                 if (!it1->label().contains(shortcut))
918                         lyxerr << "Menu warning: menu entry \""
919                                << fromqstr(it1->label())
920                                << "\" does not contain shortcut `"
921                                << fromqstr(shortcut) << "'." << endl;
922                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
923                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
924                                 lyxerr << "Menu warning: menu entries "
925                                        << '"' << fromqstr(it1->fulllabel())
926                                        << "\" and \"" << fromqstr(it2->fulllabel())
927                                        << "\" share the same shortcut."
928                                        << endl;
929                         }
930                 }
931         }
932 }
933
934
935 bool Menu::searchMenu(FuncRequest const & func, vector<docstring> & names) const
936 {
937         const_iterator m = begin();
938         const_iterator m_end = end();
939         for (; m != m_end; ++m) {
940                 if (m->kind() == MenuItem::Command && m->func() == func) {
941                         names.push_back(qstring_to_ucs4(m->label()));
942                         return true;
943                 }
944                 if (m->kind() == MenuItem::Submenu) {
945                         names.push_back(qstring_to_ucs4(m->label()));
946                         Menu const & submenu = *m->submenu();
947                         if (submenu.searchMenu(func, names))
948                                 return true;
949                         names.pop_back();
950                 }
951         }
952         return false;
953 }
954
955
956 namespace {
957
958 bool compareFormat(Format const * p1, Format const * p2)
959 {
960         return *p1 < *p2;
961 }
962
963
964 QString limitStringLength(docstring const & str)
965 {
966         size_t const max_item_length = 45;
967
968         if (str.size() > max_item_length)
969                 return toqstr(str.substr(0, max_item_length - 3) + "...");
970
971         return toqstr(str);
972 }
973
974 } // namespace anon
975
976
977 void Menu::expandLastfiles()
978 {
979         LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
980         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
981
982         int ii = 1;
983
984         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
985                 string const file = lfit->absFilename();
986                 QString const label = QString("%1. %2|%3").arg(ii)
987                         .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
988                 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
989         }
990 }
991
992
993 void Menu::expandDocuments()
994 {
995         Buffer * first = theBufferList().first();
996         if (first) {
997                 Buffer * b = first;
998                 int ii = 1;
999                 
1000                 // We cannot use a for loop as the buffer list cycles.
1001                 do {
1002                         QString label = toqstr(b->fileName().displayName(20));
1003                         if (!b->isClean())
1004                                 label += "*";
1005                         if (ii < 10)
1006                                 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
1007                         add(MenuItem(MenuItem::Command, label,
1008                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1009                         
1010                         b = theBufferList().next(b);
1011                         ++ii;
1012                 } while (b != first); 
1013         } else {
1014                 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
1015                            FuncRequest(LFUN_NOACTION)));
1016         }
1017 }
1018
1019
1020 void Menu::expandBookmarks()
1021 {
1022         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
1023
1024         for (size_t i = 1; i <= bm.size(); ++i) {
1025                 if (bm.isValid(i)) {
1026                         string const file = bm.bookmark(i).filename.absFilename();
1027                         QString const label = QString("%1. %2|%3").arg(i)
1028                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1029                         add(MenuItem(MenuItem::Command, label,
1030                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1031                 }
1032         }
1033 }
1034
1035
1036 void Menu::expandFormats(MenuItem::Kind kind, Buffer const * buf)
1037 {
1038         if (!buf && kind != MenuItem::ImportFormats) {
1039                 add(MenuItem(MenuItem::Command,
1040                                     qt_("No Document Open!"),
1041                                     FuncRequest(LFUN_NOACTION)));
1042                 return;
1043         }
1044
1045         typedef vector<Format const *> Formats;
1046         Formats formats;
1047         kb_action action;
1048
1049         switch (kind) {
1050         case MenuItem::ImportFormats:
1051                 formats = theConverters().importableFormats();
1052                 action = LFUN_BUFFER_IMPORT;
1053                 break;
1054         case MenuItem::ViewFormats:
1055                 formats = buf->exportableFormats(true);
1056                 action = LFUN_BUFFER_VIEW;
1057                 break;
1058         case MenuItem::UpdateFormats:
1059                 formats = buf->exportableFormats(true);
1060                 action = LFUN_BUFFER_UPDATE;
1061                 break;
1062         default:
1063                 formats = buf->exportableFormats(false);
1064                 action = LFUN_BUFFER_EXPORT;
1065         }
1066         sort(formats.begin(), formats.end(), &compareFormat);
1067
1068         Formats::const_iterator fit = formats.begin();
1069         Formats::const_iterator end = formats.end();
1070         for (; fit != end ; ++fit) {
1071                 if ((*fit)->dummy())
1072                         continue;
1073                 QString label = toqstr((*fit)->prettyname());
1074                 QString const shortcut = toqstr((*fit)->shortcut());
1075
1076                 switch (kind) {
1077                 case MenuItem::ImportFormats:
1078                         // FIXME: This is a hack, we should rather solve
1079                         // FIXME: bug 2488 instead.
1080                         if ((*fit)->name() == "text")
1081                                 label = qt_("Plain Text");
1082                         else if ((*fit)->name() == "textparagraph")
1083                                 label = qt_("Plain Text, Join Lines");
1084                         label += "...";
1085                         break;
1086                 case MenuItem::ViewFormats:
1087                 case MenuItem::ExportFormats:
1088                 case MenuItem::UpdateFormats:
1089                         if (!(*fit)->documentFormat())
1090                                 continue;
1091                         break;
1092                 default:
1093                         BOOST_ASSERT(false);
1094                         break;
1095                 }
1096                 // FIXME: if we had proper support for translating the
1097                 // format names defined in configure.py, there would
1098                 // not be a need to check whether the shortcut is
1099                 // correct. If we add it uncondiitonally, it would
1100                 // create useless warnings on bad shortcuts
1101                 if (!shortcut.isEmpty() && label.contains(shortcut))
1102                         label += '|' + shortcut;
1103
1104                 if (buf)
1105                         addWithStatusCheck(MenuItem(MenuItem::Command, label,
1106                                 FuncRequest(action, (*fit)->name())));
1107                 else
1108                         add(MenuItem(MenuItem::Command, label,
1109                                 FuncRequest(action, (*fit)->name())));
1110         }
1111 }
1112
1113
1114 void Menu::expandFloatListInsert(Buffer const * buf)
1115 {
1116         if (!buf) {
1117                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
1118                                     FuncRequest(LFUN_NOACTION)));
1119                 return;
1120         }
1121
1122         FloatList const & floats = buf->params().documentClass().floats();
1123         FloatList::const_iterator cit = floats.begin();
1124         FloatList::const_iterator end = floats.end();
1125         for (; cit != end; ++cit) {
1126                 addWithStatusCheck(MenuItem(MenuItem::Command,
1127                                     qt_(cit->second.listName()),
1128                                     FuncRequest(LFUN_FLOAT_LIST,
1129                                                 cit->second.type())));
1130         }
1131 }
1132
1133
1134 void Menu::expandFloatInsert(Buffer const * buf)
1135 {
1136         if (!buf) {
1137                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
1138                                     FuncRequest(LFUN_NOACTION)));
1139                 return;
1140         }
1141
1142         FloatList const & floats = buf->params().documentClass().floats();
1143         FloatList::const_iterator cit = floats.begin();
1144         FloatList::const_iterator end = floats.end();
1145         for (; cit != end; ++cit) {
1146                 // normal float
1147                 QString const label = qt_(cit->second.name());
1148                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1149                                     FuncRequest(LFUN_FLOAT_INSERT,
1150                                                 cit->second.type())));
1151         }
1152 }
1153
1154
1155 void Menu::expandFlexInsert(Buffer const * buf, string s)
1156 {
1157         if (!buf) {
1158                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
1159                                     FuncRequest(LFUN_NOACTION)));
1160                 return;
1161         }
1162         TextClass::InsetLayouts const & insetLayouts =
1163                 buf->params().documentClass().insetLayouts();
1164         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1165         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1166         for (; cit != end; ++cit) {
1167                 docstring const label = cit->first;
1168                 if (cit->second.lyxtype() == s)
1169                         addWithStatusCheck(MenuItem(MenuItem::Command, 
1170                                 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
1171                                                 label)));
1172         }
1173 }
1174
1175
1176 size_t const max_number_of_items = 25;
1177
1178 void Menu::expandToc2(Toc const & toc_list,
1179                 size_t from, size_t to, int depth)
1180 {
1181         int shortcut_count = 0;
1182
1183         // check whether depth is smaller than the smallest depth in toc.
1184         int min_depth = 1000;
1185         for (size_t i = from; i < to; ++i)
1186                 min_depth = min(min_depth, toc_list[i].depth());
1187         if (min_depth > depth)
1188                 depth = min_depth;
1189
1190         if (to - from <= max_number_of_items) {
1191                 for (size_t i = from; i < to; ++i) {
1192                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1193                         label += limitStringLength(toc_list[i].str());
1194                         if (toc_list[i].depth() == depth
1195                             && shortcut_count < 9) {
1196                                 if (label.contains(QString::number(shortcut_count + 1)))
1197                                         label += '|' + QString::number(++shortcut_count);
1198                         }
1199                         add(MenuItem(MenuItem::Command, label,
1200                                             FuncRequest(toc_list[i].action())));
1201                 }
1202         } else {
1203                 size_t pos = from;
1204                 while (pos < to) {
1205                         size_t new_pos = pos + 1;
1206                         while (new_pos < to &&
1207                                toc_list[new_pos].depth() > depth)
1208                                 ++new_pos;
1209
1210                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1211                         label += limitStringLength(toc_list[pos].str());
1212                         if (toc_list[pos].depth() == depth &&
1213                             shortcut_count < 9) {
1214                                 if (label.contains(QString::number(shortcut_count + 1)))
1215                                         label += '|' + QString::number(++shortcut_count);
1216                         }
1217                         if (new_pos == pos + 1) {
1218                                 add(MenuItem(MenuItem::Command,
1219                                                     label, FuncRequest(toc_list[pos].action())));
1220                         } else {
1221                                 MenuItem item(MenuItem::Submenu, label);
1222                                 item.setSubmenu(new Menu);
1223                                 item.submenu()->expandToc2(toc_list, pos, new_pos, depth + 1);
1224                                 add(item);
1225                         }
1226                         pos = new_pos;
1227                 }
1228         }
1229 }
1230
1231
1232 void Menu::expandToc(Buffer const * buf)
1233 {
1234         // To make things very cleanly, we would have to pass buf to
1235         // all MenuItem constructors and to expandToc2. However, we
1236         // know that all the entries in a TOC will be have status_ ==
1237         // OK, so we avoid this unnecessary overhead (JMarc)
1238
1239         if (!buf) {
1240                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
1241                                     FuncRequest(LFUN_NOACTION)));
1242                 return;
1243         }
1244
1245         Buffer* cbuf = const_cast<Buffer*>(buf);
1246         cbuf->tocBackend().update();
1247         cbuf->structureChanged();
1248
1249         // Add an entry for the master doc if this is a child doc
1250         Buffer const * const master = buf->masterBuffer();
1251         if (buf != master) {
1252                 ParIterator const pit = par_iterator_begin(master->inset());
1253                 string const arg = convert<string>(pit->id());
1254                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1255                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1256         }
1257
1258         FloatList const & floatlist = buf->params().documentClass().floats();
1259         TocList const & toc_list = buf->tocBackend().tocs();
1260         TocList::const_iterator cit = toc_list.begin();
1261         TocList::const_iterator end = toc_list.end();
1262         for (; cit != end; ++cit) {
1263                 // Handle this later
1264                 if (cit->first == "tableofcontents")
1265                         continue;
1266
1267                 // All the rest is for floats
1268                 auto_ptr<Menu> menu(new Menu);
1269                 TocIterator ccit = cit->second.begin();
1270                 TocIterator eend = cit->second.end();
1271                 for (; ccit != eend; ++ccit) {
1272                         QString const label = limitStringLength(ccit->str());
1273                         menu->add(MenuItem(MenuItem::Command, label,
1274                                            FuncRequest(ccit->action())));
1275                 }
1276                 string const & floatName = floatlist.getType(cit->first).listName();
1277                 QString label;
1278                 if (!floatName.empty())
1279                         label = qt_(floatName);
1280                 // BUG3633: listings is not a proper float so its name
1281                 // is not shown in floatlist.
1282                 else if (cit->first == "equation")
1283                         label = qt_("List of Equations");
1284                 else if (cit->first == "index")
1285                         label = qt_("List of Indexes");
1286                 else if (cit->first == "listing")
1287                         label = qt_("List of Listings");
1288                 else if (cit->first == "marginalnote")
1289                         label = qt_("List of Marginal notes");
1290                 else if (cit->first == "note")
1291                         label = qt_("List of Notes");
1292                 else if (cit->first == "footnote")
1293                         label = qt_("List of Foot notes");
1294                 else if (cit->first == "label")
1295                         label = qt_("Labels and References");
1296                 else if (cit->first == "citation")
1297                         label = qt_("List of Citations");
1298                 // this should not happen now, but if something else like
1299                 // listings is added later, this can avoid an empty menu name.
1300                 else
1301                         label = qt_("Other floats");
1302                 MenuItem item(MenuItem::Submenu, label);
1303                 item.setSubmenu(menu.release());
1304                 add(item);
1305         }
1306
1307         // Handle normal TOC
1308         cit = toc_list.find("tableofcontents");
1309         if (cit == end) {
1310                 addWithStatusCheck(MenuItem(MenuItem::Command,
1311                                     qt_("No Table of contents"),
1312                                     FuncRequest()));
1313         } else {
1314                 expandToc2(cit->second, 0, cit->second.size(), 0);
1315         }
1316 }
1317
1318
1319 void Menu::expandPasteRecent()
1320 {
1321         vector<docstring> const sel = cap::availableSelections();
1322
1323         vector<docstring>::const_iterator cit = sel.begin();
1324         vector<docstring>::const_iterator end = sel.end();
1325
1326         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1327                 add(MenuItem(MenuItem::Command, toqstr(*cit),
1328                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1329         }
1330 }
1331
1332
1333 void Menu::expandToolbars()
1334 {
1335         //
1336         // extracts the toolbars from the backend
1337         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1338         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1339
1340         for (; cit != end; ++cit) {
1341                 QString label = qt_(cit->gui_name);
1342                 // frontends are not supposed to turn on/off toolbars,
1343                 // if they cannot update ToolbarBackend::flags. That
1344                 // is to say, ToolbarsBackend::flags should reflect
1345                 // the true state of toolbars.
1346                 //
1347                 // menu is displayed as
1348                 //       on/off review
1349                 // and
1350                 //              review (auto)
1351                 // in the case of auto.
1352                 if (cit->flags & ToolbarInfo::AUTO)
1353                         label += qt_(" (auto)");
1354                 add(MenuItem(MenuItem::Command, label,
1355                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1356         }
1357 }
1358
1359
1360 void Menu::expandBranches(Buffer const * buf)
1361 {
1362         if (!buf) {
1363                 add(MenuItem(MenuItem::Command,
1364                                     qt_("No Document Open!"),
1365                                     FuncRequest(LFUN_NOACTION)));
1366                 return;
1367         }
1368
1369         BufferParams const & params = buf->masterBuffer()->params();
1370         if (params.branchlist().empty()) {
1371                 add(MenuItem(MenuItem::Command,
1372                                     qt_("No Branch in Document!"),
1373                                     FuncRequest(LFUN_NOACTION)));
1374                 return;
1375         }
1376
1377         BranchList::const_iterator cit = params.branchlist().begin();
1378         BranchList::const_iterator end = params.branchlist().end();
1379
1380         for (int ii = 1; cit != end; ++cit, ++ii) {
1381                 docstring label = cit->getBranch();
1382                 if (ii < 10)
1383                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1384                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1385                                     FuncRequest(LFUN_BRANCH_INSERT,
1386                                                 cit->getBranch())));
1387         }
1388 }
1389
1390
1391 void Menus::Impl::expand(Menu const & frommenu, Menu & tomenu,
1392                          Buffer const * buf) const
1393 {
1394         if (!tomenu.empty())
1395                 tomenu.clear();
1396
1397         for (Menu::const_iterator cit = frommenu.begin();
1398              cit != frommenu.end() ; ++cit) {
1399                 switch (cit->kind()) {
1400                 case MenuItem::Lastfiles:
1401                         tomenu.expandLastfiles();
1402                         break;
1403
1404                 case MenuItem::Documents:
1405                         tomenu.expandDocuments();
1406                         break;
1407
1408                 case MenuItem::Bookmarks:
1409                         tomenu.expandBookmarks();
1410                         break;
1411
1412                 case MenuItem::ImportFormats:
1413                 case MenuItem::ViewFormats:
1414                 case MenuItem::UpdateFormats:
1415                 case MenuItem::ExportFormats:
1416                         tomenu.expandFormats(cit->kind(), buf);
1417                         break;
1418
1419                 case MenuItem::CharStyles:
1420                         tomenu.expandFlexInsert(buf, "charstyle");
1421                         break;
1422
1423                 case MenuItem::Custom:
1424                         tomenu.expandFlexInsert(buf, "custom");
1425                         break;
1426
1427                 case MenuItem::Elements:
1428                         tomenu.expandFlexInsert(buf, "element");
1429                         break;
1430
1431                 case MenuItem::FloatListInsert:
1432                         tomenu.expandFloatListInsert(buf);
1433                         break;
1434
1435                 case MenuItem::FloatInsert:
1436                         tomenu.expandFloatInsert(buf);
1437                         break;
1438
1439                 case MenuItem::PasteRecent:
1440                         tomenu.expandPasteRecent();
1441                         break;
1442
1443                 case MenuItem::Toolbars:
1444                         tomenu.expandToolbars();
1445                         break;
1446
1447                 case MenuItem::Branches:
1448                         tomenu.expandBranches(buf);
1449                         break;
1450
1451                 case MenuItem::Toc:
1452                         tomenu.expandToc(buf);
1453                         break;
1454
1455                 case MenuItem::Submenu: {
1456                         MenuItem item(*cit);
1457                         item.setSubmenu(new Menu(cit->submenuname()));
1458                         expand(getMenu(cit->submenuname()),
1459                                *item.submenu(), buf);
1460                         tomenu.addWithStatusCheck(item);
1461                 }
1462                 break;
1463
1464                 case MenuItem::Separator:
1465                         tomenu.addWithStatusCheck(*cit);
1466                         break;
1467
1468                 case MenuItem::Command:
1469                         if (!specialmenu_.hasFunc(cit->func()))
1470                                 tomenu.addWithStatusCheck(*cit);
1471                 }
1472         }
1473
1474         // we do not want the menu to end with a separator
1475         if (!tomenu.empty()
1476             && tomenu.items_.back().kind() == MenuItem::Separator)
1477                 tomenu.items_.pop_back();
1478
1479         // Check whether the shortcuts are unique
1480         tomenu.checkShortcuts();
1481 }
1482
1483
1484 void Menus::read(Lexer & lex)
1485 {
1486         enum Menutags {
1487                 md_menu = 1,
1488                 md_menubar,
1489                 md_endmenuset,
1490                 md_last
1491         };
1492
1493         struct keyword_item menutags[md_last - 1] = {
1494                 { "end", md_endmenuset },
1495                 { "menu", md_menu },
1496                 { "menubar", md_menubar }
1497         };
1498
1499         //consistency check
1500         if (compare_ascii_no_case(lex.getString(), "menuset")) {
1501                 lyxerr << "Menubackend::read: ERROR wrong token:`"
1502                        << lex.getString() << '\'' << endl;
1503         }
1504
1505         lex.pushTable(menutags, md_last - 1);
1506         if (lyxerr.debugging(Debug::PARSER))
1507                 lex.printTable(lyxerr);
1508
1509         bool quit = false;
1510
1511         while (lex.isOK() && !quit) {
1512                 switch (lex.lex()) {
1513                 case md_menubar:
1514                         d->menubar_.read(lex);
1515                         break;
1516                 case md_menu: {
1517                         lex.next(true);
1518                         QString const name = toqstr(lex.getDocString());
1519                         if (d->hasMenu(name)) {
1520                                 d->getMenu(name).read(lex);
1521                         } else {
1522                                 Menu menu(name);
1523                                 menu.read(lex);
1524                                 d->add(menu);
1525                         }
1526                         break;
1527                 }
1528                 case md_endmenuset:
1529                         quit = true;
1530                         break;
1531                 default:
1532                         lex.printError("menubackend::read: "
1533                                        "Unknown menu tag: `$$Token'");
1534                         break;
1535                 }
1536         }
1537         lex.popTable();
1538 }
1539
1540
1541 void Menus::Impl::add(Menu const & menu)
1542 {
1543         menulist_.push_back(menu);
1544 }
1545
1546
1547 bool Menus::Impl::hasMenu(QString const & name) const
1548 {
1549         return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1550 }
1551
1552
1553 Menu const & Menus::Impl::getMenu(QString const & name) const
1554 {
1555         const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1556         if (cit == end())
1557                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1558         BOOST_ASSERT(cit != end());
1559         return (*cit);
1560 }
1561
1562
1563 Menu & Menus::Impl::getMenu(QString const & name)
1564 {
1565         iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1566         if (it == end())
1567                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1568         BOOST_ASSERT(it != end());
1569         return (*it);
1570 }
1571
1572
1573 } // namespace frontend
1574 } // namespace lyx
1575
1576 #include "Menus_moc.cpp"