]> git.lyx.org Git - lyx.git/blob - src/MenuBackend.cpp
Transfer current_font and real_current_font from Text to Cursor.
[lyx.git] / src / MenuBackend.cpp
1 /**
2  * \file MenuBackend.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author André Pönitz
10  * \author Dekel Tsur
11  * \author Martin Vermeer
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "MenuBackend.h"
19
20 #include "BranchList.h"
21 #include "Buffer.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "Exporter.h"
27 #include "Floating.h"
28 #include "FloatList.h"
29 #include "Format.h"
30 #include "gettext.h"
31 #include "Importer.h"
32 #include "KeyMap.h"
33 #include "Session.h"
34 #include "LyXAction.h"
35 #include "LyX.h" // for lastfiles
36 #include "LyXFunc.h"
37 #include "Lexer.h"
38 #include "Paragraph.h"
39 #include "TocBackend.h"
40 #include "ToolbarBackend.h"
41
42 #include "support/filetools.h"
43 #include "support/lstrings.h"
44 #include "support/convert.h"
45
46 #include <boost/bind.hpp>
47
48 #include <algorithm>
49
50
51 namespace lyx {
52
53 using support::compare_ascii_no_case;
54 using support::contains;
55 using support::makeDisplayPath;
56 using support::token;
57
58 using boost::bind;
59
60 using std::auto_ptr;
61 using std::endl;
62 using std::equal_to;
63 using std::find_if;
64 using std::max;
65 using std::sort;
66 using std::string;
67 using std::vector;
68
69
70 namespace {
71
72 class MenuNamesEqual : public std::unary_function<Menu, bool> {
73 public:
74         MenuNamesEqual(docstring const & name)
75                 : name_(name) {}
76         bool operator()(Menu const & menu) const
77         {
78                 return menu.name() == name_;
79         }
80 private:
81         docstring name_;
82 };
83
84 } // namespace anon
85
86
87 // This is the global menu definition
88 MenuBackend menubackend;
89
90
91 MenuItem::MenuItem(Kind kind)
92         : kind_(kind), optional_(false)
93 {}
94
95
96 MenuItem::MenuItem(Kind kind, docstring const & label,
97                    docstring const & submenu, bool optional)
98         : kind_(kind), label_(label),
99           submenuname_(submenu), optional_(optional)
100 {
101         BOOST_ASSERT(kind == Submenu);
102 }
103
104
105 MenuItem::MenuItem(Kind kind, docstring const & label,
106                    FuncRequest const & func, bool optional)
107         : kind_(kind), label_(label), func_(func), optional_(optional)
108 {
109         func_.origin = FuncRequest::MENU;
110 }
111
112
113 MenuItem::~MenuItem()
114 {}
115
116
117 void MenuItem::submenu(Menu * menu)
118 {
119         submenu_.reset(menu);
120 }
121
122
123 docstring const MenuItem::label() const
124 {
125         return token(label_, char_type('|'), 0);
126 }
127
128
129 docstring const MenuItem::shortcut() const
130 {
131         return token(label_, char_type('|'), 1);
132 }
133
134
135 docstring const MenuItem::binding(bool forgui) const
136 {
137         if (kind_ != Command)
138                 return docstring();
139
140         // Get the keys bound to this action, but keep only the
141         // first one later
142         KeyMap::Bindings bindings = theTopLevelKeymap().findbindings(func_);
143
144         if (bindings.size()) {
145                 return bindings.begin()->print(forgui);
146         } else {
147                 LYXERR(Debug::KBMAP)
148                         << "No binding for "
149                         << lyxaction.getActionName(func_.action)
150                         << '(' << to_utf8(func_.argument()) << ')' << endl;
151                 return docstring();
152         }
153
154 }
155
156
157 Menu & Menu::add(MenuItem const & i)
158 {
159         items_.push_back(i);
160         return *this;
161 }
162
163
164 Menu & Menu::addWithStatusCheck(MenuItem const & i)
165 {
166         switch (i.kind()) {
167
168         case MenuItem::Command: {
169                 FuncStatus status = lyx::getStatus(i.func());
170                 if (status.unknown() || (!status.enabled() && i.optional()))
171                         break;
172                 items_.push_back(i);
173                 items_.back().status(status);
174                 break;
175         }
176
177         case MenuItem::Submenu: {
178                 if (i.submenu()) {
179                         bool enabled = false;
180                         for (const_iterator cit = i.submenu()->begin();
181                              cit != i.submenu()->end(); ++cit) {
182                                 if ((cit->kind() == MenuItem::Command
183                                      || cit->kind() == MenuItem::Submenu)
184                                     && cit->status().enabled()) {
185                                         enabled = true;
186                                         break;
187                                 }
188                         }
189                         if (enabled || !i.optional()) {
190                                 items_.push_back(i);
191                                 items_.back().status().enabled(enabled);
192                         }
193                 }
194                 else
195                         items_.push_back(i);
196                 break;
197         }
198
199         case MenuItem::Separator:
200                 if (!items_.empty()
201                     && items_.back().kind() != MenuItem::Separator)
202                         items_.push_back(i);
203                 break;
204
205         default:
206                 items_.push_back(i);
207         }
208
209         return *this;
210 }
211
212
213 Menu & Menu::read(Lexer & lex)
214 {
215         enum Menutags {
216                 md_item = 1,
217                 md_branches,
218                 md_documents,
219                 md_bookmarks,
220                 md_charstyles,
221                 md_custom,
222                 md_endmenu,
223                 md_exportformats,
224                 md_importformats,
225                 md_lastfiles,
226                 md_optitem,
227                 md_optsubmenu,
228                 md_separator,
229                 md_submenu,
230                 md_toc,
231                 md_updateformats,
232                 md_viewformats,
233                 md_floatlistinsert,
234                 md_floatinsert,
235                 md_pasterecent,
236                 md_toolbars,
237                 md_last
238         };
239
240         struct keyword_item menutags[md_last - 1] = {
241                 { "bookmarks", md_bookmarks },
242                 { "branches", md_branches },
243                 { "charstyles", md_charstyles },
244                 { "custom", md_custom },
245                 { "documents", md_documents },
246                 { "end", md_endmenu },
247                 { "exportformats", md_exportformats },
248                 { "floatinsert", md_floatinsert },
249                 { "floatlistinsert", md_floatlistinsert },
250                 { "importformats", md_importformats },
251                 { "item", md_item },
252                 { "lastfiles", md_lastfiles },
253                 { "optitem", md_optitem },
254                 { "optsubmenu", md_optsubmenu },
255                 { "pasterecent", md_pasterecent },
256                 { "separator", md_separator },
257                 { "submenu", md_submenu },
258                 { "toc", md_toc },
259                 { "toolbars", md_toolbars },
260                 { "updateformats", md_updateformats },
261                 { "viewformats", md_viewformats }
262         };
263
264         lex.pushTable(menutags, md_last - 1);
265         if (lyxerr.debugging(Debug::PARSER))
266                 lex.printTable(lyxerr);
267
268         bool quit = false;
269         bool optional = false;
270
271         while (lex.isOK() && !quit) {
272                 switch (lex.lex()) {
273                 case md_optitem:
274                         optional = true;
275                         // fallback to md_item
276                 case md_item: {
277                         lex.next(true);
278                         docstring const name = translateIfPossible(lex.getDocString());
279                         lex.next(true);
280                         string const command = lex.getString();
281                         FuncRequest func = lyxaction.lookupFunc(command);
282                         add(MenuItem(MenuItem::Command, name, func, optional));
283                         optional = false;
284                         break;
285                 }
286
287                 case md_separator:
288                         add(MenuItem(MenuItem::Separator));
289                         break;
290
291                 case md_lastfiles:
292                         add(MenuItem(MenuItem::Lastfiles));
293                         break;
294
295                 case md_charstyles:
296                         add(MenuItem(MenuItem::CharStyles));
297                         break;
298
299                 case md_custom:
300                         add(MenuItem(MenuItem::Custom));
301                         break;
302
303                 case md_documents:
304                         add(MenuItem(MenuItem::Documents));
305                         break;
306
307                 case md_bookmarks:
308                         add(MenuItem(MenuItem::Bookmarks));
309                         break;
310
311                 case md_toc:
312                         add(MenuItem(MenuItem::Toc));
313                         break;
314
315                 case md_viewformats:
316                         add(MenuItem(MenuItem::ViewFormats));
317                         break;
318
319                 case md_updateformats:
320                         add(MenuItem(MenuItem::UpdateFormats));
321                         break;
322
323                 case md_exportformats:
324                         add(MenuItem(MenuItem::ExportFormats));
325                         break;
326
327                 case md_importformats:
328                         add(MenuItem(MenuItem::ImportFormats));
329                         break;
330
331                 case md_floatlistinsert:
332                         add(MenuItem(MenuItem::FloatListInsert));
333                         break;
334
335                 case md_floatinsert:
336                         add(MenuItem(MenuItem::FloatInsert));
337                         break;
338
339                 case md_pasterecent:
340                         add(MenuItem(MenuItem::PasteRecent));
341                         break;
342
343                 case md_toolbars:
344                         add(MenuItem(MenuItem::Toolbars));
345                         break;
346
347                 case md_branches:
348                         add(MenuItem(MenuItem::Branches));
349                         break;
350
351                 case md_optsubmenu:
352                         optional = true;
353                         // fallback to md_submenu
354                 case md_submenu: {
355                         lex.next(true);
356                         docstring const mlabel = translateIfPossible(lex.getDocString());
357                         lex.next(true);
358                         docstring const mname = lex.getDocString();
359                         add(MenuItem(MenuItem::Submenu, mlabel, mname,
360                                      optional));
361                         optional = false;
362                         break;
363                 }
364
365                 case md_endmenu:
366                         quit = true;
367                         break;
368
369                 default:
370                         lex.printError("Menu::read: "
371                                        "Unknown menu tag: `$$Token'");
372                         break;
373                 }
374         }
375         lex.popTable();
376         return *this;
377 }
378
379
380 MenuItem const & Menu::operator[](size_type i) const
381 {
382         return items_[i];
383 }
384
385
386 bool Menu::hasFunc(FuncRequest const & func) const
387 {
388         return find_if(begin(), end(),
389                        bind(std::equal_to<FuncRequest>(),
390                             bind(&MenuItem::func, _1),
391                             func)) != end();
392 }
393
394 void Menu::checkShortcuts() const
395 {
396         // This is a quadratic algorithm, but we do not care because
397         // menus are short enough
398         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
399                 docstring shortcut = it1->shortcut();
400                 if (shortcut.empty())
401                         continue;
402                 if (!contains(it1->label(), shortcut))
403                         lyxerr << "Menu warning: menu entry \""
404                                << to_utf8(it1->label())
405                                << "\" does not contain shortcut `"
406                                << to_utf8(shortcut) << "'." << endl;
407                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
408                         if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
409                                 lyxerr << "Menu warning: menu entries "
410                                        << '"' << to_utf8(it1->fulllabel())
411                                        << "\" and \"" << to_utf8(it2->fulllabel())
412                                        << "\" share the same shortcut."
413                                        << endl;
414                         }
415                 }
416         }
417 }
418
419
420 void MenuBackend::specialMenu(Menu const & menu)
421 {
422         specialmenu_ = menu;
423 }
424
425
426 namespace {
427
428 class compare_format {
429 public:
430         bool operator()(Format const * p1, Format const * p2) {
431                 return *p1 < *p2;
432         }
433 };
434
435 docstring const limit_string_length(docstring const & str)
436 {
437         docstring::size_type const max_item_length = 45;
438
439         if (str.size() > max_item_length)
440                 return str.substr(0, max_item_length - 3) + "...";
441         else
442                 return str;
443 }
444
445
446 void expandLastfiles(Menu & tomenu)
447 {
448         lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
449         lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
450
451         int ii = 1;
452
453         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
454                 string const file = lfit->absFilename();
455                 docstring const label = convert<docstring>(ii) + ". "
456                         + makeDisplayPath(file, 30)
457                         + char_type('|') + convert<docstring>(ii);
458                 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
459         }
460 }
461
462
463 void expandDocuments(Menu & tomenu)
464 {
465         Buffer * first = theBufferList().first();
466         if (first) {
467                 Buffer * b = first;
468                 int ii = 1;
469                 
470                 // We cannot use a for loop as the buffer list cycles.
471                 do {
472                         docstring label = makeDisplayPath(b->fileName(), 20);
473                         if (!b->isClean()) label = label + "*";
474                         if (ii < 10)
475                                 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
476                         tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BUFFER_SWITCH, b->fileName())));
477                         
478                         b = theBufferList().next(b);
479                         ++ii;
480                 } while (b != first); 
481         } else {
482                 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
483                            FuncRequest(LFUN_NOACTION)));
484                 return;
485         }
486 }
487
488
489 void expandBookmarks(Menu & tomenu)
490 {
491         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
492
493         for (size_t i = 1; i <= bm.size(); ++i) {
494                 if (bm.isValid(i)) {
495                         docstring const label = convert<docstring>(i) + ". "
496                                 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
497                                 + char_type('|') + convert<docstring>(i);
498                         tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
499                                 convert<docstring>(i))));
500                 }
501         }
502 }
503
504
505 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
506 {
507         if (!buf && kind != MenuItem::ImportFormats) {
508                 tomenu.add(MenuItem(MenuItem::Command,
509                                     _("No Document Open!"),
510                                     FuncRequest(LFUN_NOACTION)));
511                 return;
512         }
513
514         typedef vector<Format const *> Formats;
515         Formats formats;
516         kb_action action;
517
518         switch (kind) {
519         case MenuItem::ImportFormats:
520                 formats = Importer::GetImportableFormats();
521                 action = LFUN_BUFFER_IMPORT;
522                 break;
523         case MenuItem::ViewFormats:
524                 formats = Exporter::getExportableFormats(*buf, true);
525                 action = LFUN_BUFFER_VIEW;
526                 break;
527         case MenuItem::UpdateFormats:
528                 formats = Exporter::getExportableFormats(*buf, true);
529                 action = LFUN_BUFFER_UPDATE;
530                 break;
531         default:
532                 formats = Exporter::getExportableFormats(*buf, false);
533                 action = LFUN_BUFFER_EXPORT;
534         }
535         sort(formats.begin(), formats.end(), compare_format());
536
537         Formats::const_iterator fit = formats.begin();
538         Formats::const_iterator end = formats.end();
539         for (; fit != end ; ++fit) {
540                 if ((*fit)->dummy())
541                         continue;
542                 docstring label = from_utf8((*fit)->prettyname());
543
544                 switch (kind) {
545                 case MenuItem::ImportFormats:
546                         // FIXME: This is a hack, we should rather solve
547                         // FIXME: bug 2488 instead.
548                         if ((*fit)->name() == "text")
549                                 label = _("Plain Text");
550                         else if ((*fit)->name() == "textparagraph")
551                                 label = _("Plain Text, Join Lines");
552                         label += "...";
553                         break;
554                 case MenuItem::ViewFormats:
555                 case MenuItem::ExportFormats:
556                 case MenuItem::UpdateFormats:
557                         if (!(*fit)->documentFormat())
558                                 continue;
559                         break;
560                 default:
561                         BOOST_ASSERT(false);
562                         break;
563                 }
564                 if (!(*fit)->shortcut().empty())
565                         label += char_type('|') + from_utf8((*fit)->shortcut());
566
567                 if (buf)
568                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
569                                 FuncRequest(action, (*fit)->name())));
570                 else
571                         tomenu.add(MenuItem(MenuItem::Command, label,
572                                 FuncRequest(action, (*fit)->name())));
573         }
574 }
575
576
577 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
578 {
579         if (!buf) {
580                 tomenu.add(MenuItem(MenuItem::Command,
581                                     _("No Document Open!"),
582                                     FuncRequest(LFUN_NOACTION)));
583                 return;
584         }
585
586         FloatList const & floats =
587                 buf->params().getTextClass().floats();
588         FloatList::const_iterator cit = floats.begin();
589         FloatList::const_iterator end = floats.end();
590         for (; cit != end; ++cit) {
591                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
592                                     _(cit->second.listName()),
593                                     FuncRequest(LFUN_FLOAT_LIST,
594                                                 cit->second.type())));
595         }
596 }
597
598
599 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
600 {
601         if (!buf) {
602                 tomenu.add(MenuItem(MenuItem::Command,
603                                     _("No Document Open!"),
604                                     FuncRequest(LFUN_NOACTION)));
605                 return;
606         }
607
608         FloatList const & floats =
609                 buf->params().getTextClass().floats();
610         FloatList::const_iterator cit = floats.begin();
611         FloatList::const_iterator end = floats.end();
612         for (; cit != end; ++cit) {
613                 // normal float
614                 docstring const label = _(cit->second.name());
615                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
616                                     FuncRequest(LFUN_FLOAT_INSERT,
617                                                 cit->second.type())));
618         }
619 }
620
621
622 void expandCharStyleInsert(Menu & tomenu, Buffer const * buf, std::string s)
623 {
624         if (!buf) {
625                 tomenu.add(MenuItem(MenuItem::Command,
626                                     _("No Document Open!"),
627                                     FuncRequest(LFUN_NOACTION)));
628                 return;
629         }
630         InsetLayouts const & insetlayouts =
631                 buf->params().getTextClass().insetlayouts();
632         InsetLayouts::const_iterator cit = insetlayouts.begin();
633         InsetLayouts::const_iterator end = insetlayouts.end();
634         for (; cit != end; ++cit) {
635                 docstring const label = cit->first;
636                 if (cit->second.lyxtype == s)
637                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, 
638                                 label, FuncRequest(LFUN_CHARSTYLE_INSERT,
639                                                 label)));
640         }
641 }
642
643
644 Menu::size_type const max_number_of_items = 25;
645
646 void expandToc2(Menu & tomenu,
647                 Toc const & toc_list,
648                 Toc::size_type from,
649                 Toc::size_type to, int depth)
650 {
651         int shortcut_count = 0;
652
653         // check whether depth is smaller than the smallest depth in toc.
654         int min_depth = 1000;
655         for (Toc::size_type i = from; i < to; ++i)
656                 min_depth = std::min(min_depth, toc_list[i].depth());
657         if (min_depth > depth)
658                 depth = min_depth;
659
660
661         if (to - from <= max_number_of_items) {
662                 for (Toc::size_type i = from; i < to; ++i) {
663                         docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
664                         label += limit_string_length(toc_list[i].str());
665                         if (toc_list[i].depth() == depth
666                             && shortcut_count < 9) {
667                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
668                                         label += char_type('|') + convert<docstring>(++shortcut_count);
669                         }
670                         tomenu.add(MenuItem(MenuItem::Command, label,
671                                             FuncRequest(toc_list[i].action())));
672                 }
673         } else {
674                 Toc::size_type pos = from;
675                 while (pos < to) {
676                         Toc::size_type new_pos = pos + 1;
677                         while (new_pos < to &&
678                                toc_list[new_pos].depth() > depth)
679                                 ++new_pos;
680
681                         docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
682                         label += limit_string_length(toc_list[pos].str());
683                         if (toc_list[pos].depth() == depth &&
684                             shortcut_count < 9) {
685                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
686                                         label += char_type('|') + convert<docstring>(++shortcut_count);
687                         }
688                         if (new_pos == pos + 1) {
689                                 tomenu.add(MenuItem(MenuItem::Command,
690                                                     label, FuncRequest(toc_list[pos].action())));
691                         } else {
692                                 MenuItem item(MenuItem::Submenu, label);
693                                 item.submenu(new Menu);
694                                 expandToc2(*item.submenu(),
695                                            toc_list, pos, new_pos, depth + 1);
696                                 tomenu.add(item);
697                         }
698                         pos = new_pos;
699                 }
700         }
701 }
702
703
704 void expandToc(Menu & tomenu, Buffer const * buf)
705 {
706         // To make things very cleanly, we would have to pass buf to
707         // all MenuItem constructors and to expandToc2. However, we
708         // know that all the entries in a TOC will be have status_ ==
709         // OK, so we avoid this unnecessary overhead (JMarc)
710
711         if (!buf) {
712                 tomenu.add(MenuItem(MenuItem::Command,
713                                     _("No Document Open!"),
714                                     FuncRequest(LFUN_NOACTION)));
715                 return;
716         }
717
718         Buffer* cbuf = const_cast<Buffer*>(buf);
719         cbuf->tocBackend().update();
720         cbuf->structureChanged();
721
722         // Add an entry for the master doc if this is a child doc
723         Buffer const * const master = buf->getMasterBuffer();
724         if (buf != master) {
725                 ParIterator const pit = par_iterator_begin(master->inset());
726                 string const arg = convert<string>(pit->id());
727                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
728                 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
729         }
730
731         FloatList const & floatlist = buf->params().getTextClass().floats();
732         TocList const & toc_list = buf->tocBackend().tocs();
733         TocList::const_iterator cit = toc_list.begin();
734         TocList::const_iterator end = toc_list.end();
735         for (; cit != end; ++cit) {
736                 // Handle this later
737                 if (cit->first == "tableofcontents")
738                         continue;
739
740                 // All the rest is for floats
741                 auto_ptr<Menu> menu(new Menu);
742                 TocIterator ccit = cit->second.begin();
743                 TocIterator eend = cit->second.end();
744                 for (; ccit != eend; ++ccit) {
745                         docstring const label = limit_string_length(ccit->str());
746                         menu->add(MenuItem(MenuItem::Command,
747                                            label,
748                                            FuncRequest(ccit->action())));
749                 }
750                 string const & floatName = floatlist.getType(cit->first).listName();
751                 docstring label;
752                 if (!floatName.empty())
753                         label = _(floatName);
754                 // BUG3633: listings is not a proper float so its name
755                 // is not shown in floatlist.
756                 else if (cit->first == "listing")
757                         label = _("List of listings");
758                 // this should not happen now, but if something else like
759                 // listings is added later, this can avoid an empty menu name.
760                 else
761                         label = _("Other floats");
762                 MenuItem item(MenuItem::Submenu, label);
763                 item.submenu(menu.release());
764                 tomenu.add(item);
765         }
766
767         // Handle normal TOC
768         cit = toc_list.find("tableofcontents");
769         if (cit == end) {
770                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
771                                     _("No Table of contents"),
772                                     FuncRequest()));
773         } else {
774                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
775         }
776 }
777
778
779 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
780 {
781         if (!buf)
782                 return;
783
784         vector<docstring> const sel =
785                 cap::availableSelections(*buf);
786
787         vector<docstring>::const_iterator cit = sel.begin();
788         vector<docstring>::const_iterator end = sel.end();
789
790         for (unsigned int index = 0; cit != end; ++cit, ++index) {
791                 tomenu.add(MenuItem(MenuItem::Command, *cit,
792                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
793         }
794 }
795
796
797 void expandToolbars(Menu & tomenu)
798 {
799         //
800         // extracts the toolbars from the backend
801         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
802         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
803
804         for (; cit != end; ++cit) {
805                 docstring label = _(cit->gui_name);
806                 // frontends are not supposed to turn on/off toolbars,
807                 // if they cannot update ToolbarBackend::flags. That
808                 // is to say, ToolbarsBackend::flags should reflect
809                 // the true state of toolbars.
810                 //
811                 // menu is displayed as
812                 //       on/off review
813                 // and
814                 //              review (auto)
815                 // in the case of auto.
816                 if (cit->flags & ToolbarInfo::AUTO)
817                         label += _(" (auto)");
818                 tomenu.add(MenuItem(MenuItem::Command, label,
819                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
820         }
821 }
822
823
824 void expandBranches(Menu & tomenu, Buffer const * buf)
825 {
826         if (!buf) {
827                 tomenu.add(MenuItem(MenuItem::Command,
828                                     _("No Document Open!"),
829                                     FuncRequest(LFUN_NOACTION)));
830                 return;
831         }
832
833         BufferParams const & params = buf->getMasterBuffer()->params();
834         if (params.branchlist().empty()) {
835                 tomenu.add(MenuItem(MenuItem::Command,
836                                     _("No Branch in Document!"),
837                                     FuncRequest(LFUN_NOACTION)));
838                 return;
839         }
840
841         BranchList::const_iterator cit = params.branchlist().begin();
842         BranchList::const_iterator end = params.branchlist().end();
843
844         for (int ii = 1; cit != end; ++cit, ++ii) {
845                 docstring label = cit->getBranch();
846                 if (ii < 10)
847                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
848                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
849                                     FuncRequest(LFUN_BRANCH_INSERT,
850                                                 cit->getBranch())));
851         }
852 }
853
854
855 } // namespace anon
856
857
858 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
859                          Buffer const * buf) const
860 {
861         if (!tomenu.empty())
862                 tomenu.clear();
863
864         for (Menu::const_iterator cit = frommenu.begin();
865              cit != frommenu.end() ; ++cit) {
866                 switch (cit->kind()) {
867                 case MenuItem::Lastfiles:
868                         expandLastfiles(tomenu);
869                         break;
870
871                 case MenuItem::Documents:
872                         expandDocuments(tomenu);
873                         break;
874
875                 case MenuItem::Bookmarks:
876                         expandBookmarks(tomenu);
877                         break;
878
879                 case MenuItem::ImportFormats:
880                 case MenuItem::ViewFormats:
881                 case MenuItem::UpdateFormats:
882                 case MenuItem::ExportFormats:
883                         expandFormats(cit->kind(), tomenu, buf);
884                         break;
885
886                 case MenuItem::CharStyles:
887                         expandCharStyleInsert(tomenu, buf, "charstyle");
888                         break;
889
890                 case MenuItem::Custom:
891                         expandCharStyleInsert(tomenu, buf, "custom");
892                         break;
893
894                 case MenuItem::FloatListInsert:
895                         expandFloatListInsert(tomenu, buf);
896                         break;
897
898                 case MenuItem::FloatInsert:
899                         expandFloatInsert(tomenu, buf);
900                         break;
901
902                 case MenuItem::PasteRecent:
903                         expandPasteRecent(tomenu, buf);
904                         break;
905
906                 case MenuItem::Toolbars:
907                         expandToolbars(tomenu);
908                         break;
909
910                 case MenuItem::Branches:
911                         expandBranches(tomenu, buf);
912                         break;
913
914                 case MenuItem::Toc:
915                         expandToc(tomenu, buf);
916                         break;
917
918                 case MenuItem::Submenu: {
919                         MenuItem item(*cit);
920                         item.submenu(new Menu(cit->submenuname()));
921                         expand(getMenu(cit->submenuname()),
922                                *item.submenu(), buf);
923                         tomenu.addWithStatusCheck(item);
924                 }
925                 break;
926
927                 case MenuItem::Separator:
928                         tomenu.addWithStatusCheck(*cit);
929                         break;
930
931                 case MenuItem::Command:
932                         if (!specialmenu_.hasFunc(cit->func()))
933                                 tomenu.addWithStatusCheck(*cit);
934                 }
935         }
936
937         // we do not want the menu to end with a separator
938         if (!tomenu.empty()
939             && tomenu.items_.back().kind() == MenuItem::Separator)
940                 tomenu.items_.pop_back();
941
942         // Check whether the shortcuts are unique
943         tomenu.checkShortcuts();
944 }
945
946
947 void MenuBackend::read(Lexer & lex)
948 {
949         enum Menutags {
950                 md_menu = 1,
951                 md_menubar,
952                 md_endmenuset,
953                 md_last
954         };
955
956         struct keyword_item menutags[md_last - 1] = {
957                 { "end", md_endmenuset },
958                 { "menu", md_menu },
959                 { "menubar", md_menubar }
960         };
961
962         //consistency check
963         if (compare_ascii_no_case(lex.getString(), "menuset")) {
964                 lyxerr << "Menubackend::read: ERROR wrong token:`"
965                        << lex.getString() << '\'' << endl;
966         }
967
968         lex.pushTable(menutags, md_last - 1);
969         if (lyxerr.debugging(Debug::PARSER))
970                 lex.printTable(lyxerr);
971
972         bool quit = false;
973
974         while (lex.isOK() && !quit) {
975                 switch (lex.lex()) {
976                 case md_menubar:
977                         menubar_.read(lex);
978                         break;
979                 case md_menu: {
980                         lex.next(true);
981                         docstring const name = lex.getDocString();
982                         if (hasMenu(name)) {
983                                 getMenu(name).read(lex);
984                         } else {
985                                 Menu menu(name);
986                                 menu.read(lex);
987                                 add(menu);
988                         }
989                         break;
990                 }
991                 case md_endmenuset:
992                         quit = true;
993                         break;
994                 default:
995                         lex.printError("menubackend::read: "
996                                        "Unknown menu tag: `$$Token'");
997                         break;
998                 }
999         }
1000         lex.popTable();
1001 }
1002
1003
1004 void MenuBackend::add(Menu const & menu)
1005 {
1006         menulist_.push_back(menu);
1007 }
1008
1009
1010 bool MenuBackend::hasMenu(docstring const & name) const
1011 {
1012         return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1013 }
1014
1015
1016 Menu const & MenuBackend::getMenu(docstring const & name) const
1017 {
1018         const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1019         if (cit == end())
1020                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1021         BOOST_ASSERT(cit != end());
1022         return (*cit);
1023 }
1024
1025
1026 Menu & MenuBackend::getMenu(docstring const & name)
1027 {
1028         iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1029         if (it == end())
1030                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1031         BOOST_ASSERT(it != end());
1032         return (*it);
1033 }
1034
1035
1036 Menu const & MenuBackend::getMenubar() const
1037 {
1038         return menubar_;
1039 }
1040
1041
1042 } // namespace lyx