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