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