]> git.lyx.org Git - lyx.git/blob - src/MenuBackend.cpp
Fix bug 3171: switching document jumps always back to last saved bookmark
[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_endmenu,
222                 md_exportformats,
223                 md_importformats,
224                 md_lastfiles,
225                 md_optitem,
226                 md_optsubmenu,
227                 md_separator,
228                 md_submenu,
229                 md_toc,
230                 md_updateformats,
231                 md_viewformats,
232                 md_floatlistinsert,
233                 md_floatinsert,
234                 md_pasterecent,
235                 md_toolbars,
236                 md_last
237         };
238
239         struct keyword_item menutags[md_last - 1] = {
240                 { "bookmarks", md_bookmarks },
241                 { "branches", md_branches },
242                 { "charstyles", md_charstyles },
243                 { "documents", md_documents },
244                 { "end", md_endmenu },
245                 { "exportformats", md_exportformats },
246                 { "floatinsert", md_floatinsert },
247                 { "floatlistinsert", md_floatlistinsert },
248                 { "importformats", md_importformats },
249                 { "item", md_item },
250                 { "lastfiles", md_lastfiles },
251                 { "optitem", md_optitem },
252                 { "optsubmenu", md_optsubmenu },
253                 { "pasterecent", md_pasterecent },
254                 { "separator", md_separator },
255                 { "submenu", md_submenu },
256                 { "toc", md_toc },
257                 { "toolbars", md_toolbars },
258                 { "updateformats", md_updateformats },
259                 { "viewformats", md_viewformats }
260         };
261
262         lex.pushTable(menutags, md_last - 1);
263         if (lyxerr.debugging(Debug::PARSER))
264                 lex.printTable(lyxerr);
265
266         bool quit = false;
267         bool optional = false;
268
269         while (lex.isOK() && !quit) {
270                 switch (lex.lex()) {
271                 case md_optitem:
272                         optional = true;
273                         // fallback to md_item
274                 case md_item: {
275                         lex.next(true);
276                         docstring const name = translateIfPossible(lex.getDocString());
277                         lex.next(true);
278                         string const command = lex.getString();
279                         FuncRequest func = lyxaction.lookupFunc(command);
280                         add(MenuItem(MenuItem::Command, name, func, optional));
281                         optional = false;
282                         break;
283                 }
284
285                 case md_separator:
286                         add(MenuItem(MenuItem::Separator));
287                         break;
288
289                 case md_lastfiles:
290                         add(MenuItem(MenuItem::Lastfiles));
291                         break;
292
293                 case md_charstyles:
294                         add(MenuItem(MenuItem::CharStyles));
295                         break;
296
297                 case md_documents:
298                         add(MenuItem(MenuItem::Documents));
299                         break;
300
301                 case md_bookmarks:
302                         add(MenuItem(MenuItem::Bookmarks));
303                         break;
304
305                 case md_toc:
306                         add(MenuItem(MenuItem::Toc));
307                         break;
308
309                 case md_viewformats:
310                         add(MenuItem(MenuItem::ViewFormats));
311                         break;
312
313                 case md_updateformats:
314                         add(MenuItem(MenuItem::UpdateFormats));
315                         break;
316
317                 case md_exportformats:
318                         add(MenuItem(MenuItem::ExportFormats));
319                         break;
320
321                 case md_importformats:
322                         add(MenuItem(MenuItem::ImportFormats));
323                         break;
324
325                 case md_floatlistinsert:
326                         add(MenuItem(MenuItem::FloatListInsert));
327                         break;
328
329                 case md_floatinsert:
330                         add(MenuItem(MenuItem::FloatInsert));
331                         break;
332
333                 case md_pasterecent:
334                         add(MenuItem(MenuItem::PasteRecent));
335                         break;
336
337                 case md_toolbars:
338                         add(MenuItem(MenuItem::Toolbars));
339                         break;
340
341                 case md_branches:
342                         add(MenuItem(MenuItem::Branches));
343                         break;
344
345                 case md_optsubmenu:
346                         optional = true;
347                         // fallback to md_submenu
348                 case md_submenu: {
349                         lex.next(true);
350                         docstring const mlabel = translateIfPossible(lex.getDocString());
351                         lex.next(true);
352                         docstring const mname = lex.getDocString();
353                         add(MenuItem(MenuItem::Submenu, mlabel, mname,
354                                      optional));
355                         optional = false;
356                         break;
357                 }
358
359                 case md_endmenu:
360                         quit = true;
361                         break;
362
363                 default:
364                         lex.printError("Menu::read: "
365                                        "Unknown menu tag: `$$Token'");
366                         break;
367                 }
368         }
369         lex.popTable();
370         return *this;
371 }
372
373
374 MenuItem const & Menu::operator[](size_type i) const
375 {
376         return items_[i];
377 }
378
379
380 bool Menu::hasFunc(FuncRequest const & func) const
381 {
382         return find_if(begin(), end(),
383                        bind(std::equal_to<FuncRequest>(),
384                             bind(&MenuItem::func, _1),
385                             func)) != end();
386 }
387
388 void Menu::checkShortcuts() const
389 {
390         // This is a quadratic algorithm, but we do not care because
391         // menus are short enough
392         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
393                 docstring shortcut = it1->shortcut();
394                 if (shortcut.empty())
395                         continue;
396                 if (!contains(it1->label(), shortcut))
397                         lyxerr << "Menu warning: menu entry \""
398                                << to_utf8(it1->label())
399                                << "\" does not contain shortcut `"
400                                << to_utf8(shortcut) << "'." << endl;
401                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
402                         if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
403                                 lyxerr << "Menu warning: menu entries "
404                                        << '"' << to_utf8(it1->fulllabel())
405                                        << "\" and \"" << to_utf8(it2->fulllabel())
406                                        << "\" share the same shortcut."
407                                        << endl;
408                         }
409                 }
410         }
411 }
412
413
414 void MenuBackend::specialMenu(Menu const & menu)
415 {
416         specialmenu_ = menu;
417 }
418
419
420 namespace {
421
422 class compare_format {
423 public:
424         bool operator()(Format const * p1, Format const * p2) {
425                 return *p1 < *p2;
426         }
427 };
428
429 docstring const limit_string_length(docstring const & str)
430 {
431         docstring::size_type const max_item_length = 45;
432
433         if (str.size() > max_item_length)
434                 return str.substr(0, max_item_length - 3) + "...";
435         else
436                 return str;
437 }
438
439
440 void expandLastfiles(Menu & tomenu)
441 {
442         lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
443         lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
444
445         int ii = 1;
446
447         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
448                 string const file = lfit->absFilename();
449                 docstring const label = convert<docstring>(ii) + ". "
450                         + makeDisplayPath(file, 30)
451                         + char_type('|') + convert<docstring>(ii);
452                 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
453         }
454 }
455
456
457 void expandDocuments(Menu & tomenu)
458 {
459         typedef vector<string> Strings;
460         Strings const names = theBufferList().getFileNames();
461
462         if (names.empty()) {
463                 tomenu.add(MenuItem(MenuItem::Command, _("No Document Open!"),
464                                     FuncRequest(LFUN_NOACTION)));
465                 return;
466         }
467
468         int ii = 1;
469         Strings::const_iterator docit = names.begin();
470         Strings::const_iterator end = names.end();
471         for (; docit != end; ++docit, ++ii) {
472                 docstring label = makeDisplayPath(*docit, 20);
473                 if (ii < 10)
474                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
475                 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BUFFER_SWITCH, *docit)));
476         }
477 }
478
479
480 void expandBookmarks(Menu & tomenu)
481 {
482         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
483
484         for (size_t i = 1; i <= bm.size(); ++i) {
485                 if (bm.isValid(i)) {
486                         docstring const label = convert<docstring>(i) + ". "
487                                 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
488                                 + char_type('|') + convert<docstring>(i);
489                         tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
490                                 convert<docstring>(i))));
491                 }
492         }
493 }
494
495
496 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
497 {
498         if (!buf && kind != MenuItem::ImportFormats) {
499                 tomenu.add(MenuItem(MenuItem::Command,
500                                     _("No Document Open!"),
501                                     FuncRequest(LFUN_NOACTION)));
502                 return;
503         }
504
505         typedef vector<Format const *> Formats;
506         Formats formats;
507         kb_action action;
508
509         switch (kind) {
510         case MenuItem::ImportFormats:
511                 formats = Importer::GetImportableFormats();
512                 action = LFUN_BUFFER_IMPORT;
513                 break;
514         case MenuItem::ViewFormats:
515                 formats = Exporter::getExportableFormats(*buf, true);
516                 action = LFUN_BUFFER_VIEW;
517                 break;
518         case MenuItem::UpdateFormats:
519                 formats = Exporter::getExportableFormats(*buf, true);
520                 action = LFUN_BUFFER_UPDATE;
521                 break;
522         default:
523                 formats = Exporter::getExportableFormats(*buf, false);
524                 action = LFUN_BUFFER_EXPORT;
525         }
526         sort(formats.begin(), formats.end(), compare_format());
527
528         Formats::const_iterator fit = formats.begin();
529         Formats::const_iterator end = formats.end();
530         for (; fit != end ; ++fit) {
531                 if ((*fit)->dummy())
532                         continue;
533                 docstring label = from_utf8((*fit)->prettyname());
534
535                 switch (kind) {
536                 case MenuItem::ImportFormats:
537                         // FIXME: This is a hack, we should rather solve
538                         // FIXME: bug 2488 instead.
539                         if ((*fit)->name() == "text")
540                                 label = _("Plain Text");
541                         else if ((*fit)->name() == "textparagraph")
542                                 label = _("Plain Text, Join Lines");
543                         label += "...";
544                         break;
545                 case MenuItem::ViewFormats:
546                 case MenuItem::ExportFormats:
547                 case MenuItem::UpdateFormats:
548                         if (!(*fit)->documentFormat())
549                                 continue;
550                         break;
551                 default:
552                         BOOST_ASSERT(false);
553                         break;
554                 }
555                 if (!(*fit)->shortcut().empty())
556                         label += char_type('|') + from_utf8((*fit)->shortcut());
557
558                 if (buf)
559                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
560                                 FuncRequest(action, (*fit)->name())));
561                 else
562                         tomenu.add(MenuItem(MenuItem::Command, label,
563                                 FuncRequest(action, (*fit)->name())));
564         }
565 }
566
567
568 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
569 {
570         if (!buf) {
571                 tomenu.add(MenuItem(MenuItem::Command,
572                                     _("No Document Open!"),
573                                     FuncRequest(LFUN_NOACTION)));
574                 return;
575         }
576
577         FloatList const & floats =
578                 buf->params().getTextClass().floats();
579         FloatList::const_iterator cit = floats.begin();
580         FloatList::const_iterator end = floats.end();
581         for (; cit != end; ++cit) {
582                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
583                                     _(cit->second.listName()),
584                                     FuncRequest(LFUN_FLOAT_LIST,
585                                                 cit->second.type())));
586         }
587 }
588
589
590 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
591 {
592         if (!buf) {
593                 tomenu.add(MenuItem(MenuItem::Command,
594                                     _("No Document Open!"),
595                                     FuncRequest(LFUN_NOACTION)));
596                 return;
597         }
598
599         FloatList const & floats =
600                 buf->params().getTextClass().floats();
601         FloatList::const_iterator cit = floats.begin();
602         FloatList::const_iterator end = floats.end();
603         for (; cit != end; ++cit) {
604                 // normal float
605                 docstring const label = _(cit->second.name());
606                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
607                                     FuncRequest(LFUN_FLOAT_INSERT,
608                                                 cit->second.type())));
609         }
610 }
611
612
613 void expandCharStyleInsert(Menu & tomenu, Buffer const * buf)
614 {
615         if (!buf) {
616                 tomenu.add(MenuItem(MenuItem::Command,
617                                     _("No Document Open!"),
618                                     FuncRequest(LFUN_NOACTION)));
619                 return;
620         }
621         CharStyles & charstyles =
622                 buf->params().getTextClass().charstyles();
623         CharStyles::iterator cit = charstyles.begin();
624         CharStyles::iterator end = charstyles.end();
625         for (; cit != end; ++cit) {
626                 docstring const label = from_utf8(cit->name);
627                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
628                                     FuncRequest(LFUN_CHARSTYLE_INSERT,
629                                                 label)));
630         }
631 }
632
633
634 Menu::size_type const max_number_of_items = 25;
635
636 void expandToc2(Menu & tomenu,
637                 Toc const & toc_list,
638                 Toc::size_type from,
639                 Toc::size_type to, int depth)
640 {
641         int shortcut_count = 0;
642
643         // check whether depth is smaller than the smallest depth in toc.
644         int min_depth = 1000;
645         for (Toc::size_type i = from; i < to; ++i)
646                 min_depth = std::min(min_depth, toc_list[i].depth());
647         if (min_depth > depth)
648                 depth = min_depth;
649
650
651         if (to - from <= max_number_of_items) {
652                 for (Toc::size_type i = from; i < to; ++i) {
653                         docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
654                         label += limit_string_length(toc_list[i].str());
655                         if (toc_list[i].depth() == depth
656                             && shortcut_count < 9) {
657                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
658                                         label += char_type('|') + convert<docstring>(++shortcut_count);
659                         }
660                         tomenu.add(MenuItem(MenuItem::Command, label,
661                                             FuncRequest(toc_list[i].action())));
662                 }
663         } else {
664                 Toc::size_type pos = from;
665                 while (pos < to) {
666                         Toc::size_type new_pos = pos + 1;
667                         while (new_pos < to &&
668                                toc_list[new_pos].depth() > depth)
669                                 ++new_pos;
670
671                         docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
672                         label += limit_string_length(toc_list[pos].str());
673                         if (toc_list[pos].depth() == depth &&
674                             shortcut_count < 9) {
675                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
676                                         label += char_type('|') + convert<docstring>(++shortcut_count);
677                         }
678                         if (new_pos == pos + 1) {
679                                 tomenu.add(MenuItem(MenuItem::Command,
680                                                     label, FuncRequest(toc_list[pos].action())));
681                         } else {
682                                 MenuItem item(MenuItem::Submenu, label);
683                                 item.submenu(new Menu);
684                                 expandToc2(*item.submenu(),
685                                            toc_list, pos, new_pos, depth + 1);
686                                 tomenu.add(item);
687                         }
688                         pos = new_pos;
689                 }
690         }
691 }
692
693
694 void expandToc(Menu & tomenu, Buffer const * buf)
695 {
696         // To make things very cleanly, we would have to pass buf to
697         // all MenuItem constructors and to expandToc2. However, we
698         // know that all the entries in a TOC will be have status_ ==
699         // OK, so we avoid this unnecessary overhead (JMarc)
700
701         if (!buf) {
702                 tomenu.add(MenuItem(MenuItem::Command,
703                                     _("No Document Open!"),
704                                     FuncRequest(LFUN_NOACTION)));
705                 return;
706         }
707
708         Buffer* cbuf = const_cast<Buffer*>(buf);
709         cbuf->tocBackend().update();
710         cbuf->structureChanged();
711
712         // Add an entry for the master doc if this is a child doc
713         Buffer const * const master = buf->getMasterBuffer();
714         if (buf != master) {
715                 ParIterator const pit = par_iterator_begin(master->inset());
716                 string const arg = convert<string>(pit->id());
717                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
718                 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
719         }
720
721         FloatList const & floatlist = buf->params().getTextClass().floats();
722         TocList const & toc_list = buf->tocBackend().tocs();
723         TocList::const_iterator cit = toc_list.begin();
724         TocList::const_iterator end = toc_list.end();
725         for (; cit != end; ++cit) {
726                 // Handle this later
727                 if (cit->first == "tableofcontents")
728                         continue;
729
730                 // All the rest is for floats
731                 auto_ptr<Menu> menu(new Menu);
732                 TocIterator ccit = cit->second.begin();
733                 TocIterator eend = cit->second.end();
734                 for (; ccit != eend; ++ccit) {
735                         docstring const label = limit_string_length(ccit->str());
736                         menu->add(MenuItem(MenuItem::Command,
737                                            label,
738                                            FuncRequest(ccit->action())));
739                 }
740                 string const & floatName = floatlist.getType(cit->first).listName();
741                 docstring label;
742                 if (!floatName.empty())
743                         label = _(floatName);
744                 // BUG3633: listings is not a proper float so its name
745                 // is not shown in floatlist.
746                 else if (cit->first == "listing")
747                         label = _("List of listings");
748                 // this should not happen now, but if something else like
749                 // listings is added later, this can avoid an empty menu name.
750                 else
751                         label = _("Other floats");
752                 MenuItem item(MenuItem::Submenu, label);
753                 item.submenu(menu.release());
754                 tomenu.add(item);
755         }
756
757         // Handle normal TOC
758         cit = toc_list.find("tableofcontents");
759         if (cit == end) {
760                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
761                                     _("No Table of contents"),
762                                     FuncRequest()));
763         } else {
764                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
765         }
766 }
767
768
769 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
770 {
771         if (!buf)
772                 return;
773
774         vector<docstring> const sel =
775                 cap::availableSelections(*buf);
776
777         vector<docstring>::const_iterator cit = sel.begin();
778         vector<docstring>::const_iterator end = sel.end();
779
780         for (unsigned int index = 0; cit != end; ++cit, ++index) {
781                 tomenu.add(MenuItem(MenuItem::Command, *cit,
782                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
783         }
784 }
785
786
787 void expandToolbars(Menu & tomenu)
788 {
789         //
790         // extracts the toolbars from the backend
791         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
792         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
793
794         for (; cit != end; ++cit) {
795                 docstring label = _(cit->gui_name);
796                 // frontends are not supposed to turn on/off toolbars,
797                 // if they cannot update ToolbarBackend::flags. That
798                 // is to say, ToolbarsBackend::flags should reflect
799                 // the true state of toolbars.
800                 //
801                 // menu is displayed as
802                 //       on/off review
803                 // and
804                 //              review (auto)
805                 // in the case of auto.
806                 if (cit->flags & ToolbarInfo::AUTO)
807                         label += _(" (auto)");
808                 tomenu.add(MenuItem(MenuItem::Command, label,
809                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
810         }
811 }
812
813
814 void expandBranches(Menu & tomenu, Buffer const * buf)
815 {
816         if (!buf) {
817                 tomenu.add(MenuItem(MenuItem::Command,
818                                     _("No Document Open!"),
819                                     FuncRequest(LFUN_NOACTION)));
820                 return;
821         }
822
823         BufferParams const & params = buf->getMasterBuffer()->params();
824         if (params.branchlist().empty()) {
825                 tomenu.add(MenuItem(MenuItem::Command,
826                                     _("No Branch in Document!"),
827                                     FuncRequest(LFUN_NOACTION)));
828                 return;
829         }
830
831         BranchList::const_iterator cit = params.branchlist().begin();
832         BranchList::const_iterator end = params.branchlist().end();
833
834         for (int ii = 1; cit != end; ++cit, ++ii) {
835                 docstring label = cit->getBranch();
836                 if (ii < 10)
837                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
838                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
839                                     FuncRequest(LFUN_BRANCH_INSERT,
840                                                 cit->getBranch())));
841         }
842 }
843
844
845 } // namespace anon
846
847
848 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
849                          Buffer const * buf) const
850 {
851         if (!tomenu.empty())
852                 tomenu.clear();
853
854         for (Menu::const_iterator cit = frommenu.begin();
855              cit != frommenu.end() ; ++cit) {
856                 switch (cit->kind()) {
857                 case MenuItem::Lastfiles:
858                         expandLastfiles(tomenu);
859                         break;
860
861                 case MenuItem::Documents:
862                         expandDocuments(tomenu);
863                         break;
864
865                 case MenuItem::Bookmarks:
866                         expandBookmarks(tomenu);
867                         break;
868
869                 case MenuItem::ImportFormats:
870                 case MenuItem::ViewFormats:
871                 case MenuItem::UpdateFormats:
872                 case MenuItem::ExportFormats:
873                         expandFormats(cit->kind(), tomenu, buf);
874                         break;
875
876                 case MenuItem::CharStyles:
877                         expandCharStyleInsert(tomenu, buf);
878                         break;
879
880                 case MenuItem::FloatListInsert:
881                         expandFloatListInsert(tomenu, buf);
882                         break;
883
884                 case MenuItem::FloatInsert:
885                         expandFloatInsert(tomenu, buf);
886                         break;
887
888                 case MenuItem::PasteRecent:
889                         expandPasteRecent(tomenu, buf);
890                         break;
891
892                 case MenuItem::Toolbars:
893                         expandToolbars(tomenu);
894                         break;
895
896                 case MenuItem::Branches:
897                         expandBranches(tomenu, buf);
898                         break;
899
900                 case MenuItem::Toc:
901                         expandToc(tomenu, buf);
902                         break;
903
904                 case MenuItem::Submenu: {
905                         MenuItem item(*cit);
906                         item.submenu(new Menu(cit->submenuname()));
907                         expand(getMenu(cit->submenuname()),
908                                *item.submenu(), buf);
909                         tomenu.addWithStatusCheck(item);
910                 }
911                 break;
912
913                 case MenuItem::Separator:
914                         tomenu.addWithStatusCheck(*cit);
915                         break;
916
917                 case MenuItem::Command:
918                         if (!specialmenu_.hasFunc(cit->func()))
919                                 tomenu.addWithStatusCheck(*cit);
920                 }
921         }
922
923         // we do not want the menu to end with a separator
924         if (!tomenu.empty()
925             && tomenu.items_.back().kind() == MenuItem::Separator)
926                 tomenu.items_.pop_back();
927
928         // Check whether the shortcuts are unique
929         tomenu.checkShortcuts();
930 }
931
932
933 void MenuBackend::read(Lexer & lex)
934 {
935         enum Menutags {
936                 md_menu = 1,
937                 md_menubar,
938                 md_endmenuset,
939                 md_last
940         };
941
942         struct keyword_item menutags[md_last - 1] = {
943                 { "end", md_endmenuset },
944                 { "menu", md_menu },
945                 { "menubar", md_menubar }
946         };
947
948         //consistency check
949         if (compare_ascii_no_case(lex.getString(), "menuset")) {
950                 lyxerr << "Menubackend::read: ERROR wrong token:`"
951                        << lex.getString() << '\'' << endl;
952         }
953
954         lex.pushTable(menutags, md_last - 1);
955         if (lyxerr.debugging(Debug::PARSER))
956                 lex.printTable(lyxerr);
957
958         bool quit = false;
959
960         while (lex.isOK() && !quit) {
961                 switch (lex.lex()) {
962                 case md_menubar:
963                         menubar_.read(lex);
964                         break;
965                 case md_menu: {
966                         lex.next(true);
967                         docstring const name = lex.getDocString();
968                         if (hasMenu(name)) {
969                                 getMenu(name).read(lex);
970                         } else {
971                                 Menu menu(name);
972                                 menu.read(lex);
973                                 add(menu);
974                         }
975                         break;
976                 }
977                 case md_endmenuset:
978                         quit = true;
979                         break;
980                 default:
981                         lex.printError("menubackend::read: "
982                                        "Unknown menu tag: `$$Token'");
983                         break;
984                 }
985         }
986         lex.popTable();
987 }
988
989
990 void MenuBackend::add(Menu const & menu)
991 {
992         menulist_.push_back(menu);
993 }
994
995
996 bool MenuBackend::hasMenu(docstring const & name) const
997 {
998         return find_if(begin(), end(), MenuNamesEqual(name)) != end();
999 }
1000
1001
1002 Menu const & MenuBackend::getMenu(docstring const & name) const
1003 {
1004         const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1005         if (cit == end())
1006                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1007         BOOST_ASSERT(cit != end());
1008         return (*cit);
1009 }
1010
1011
1012 Menu & MenuBackend::getMenu(docstring const & name)
1013 {
1014         iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1015         if (it == end())
1016                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1017         BOOST_ASSERT(it != end());
1018         return (*it);
1019 }
1020
1021
1022 Menu const & MenuBackend::getMenubar() const
1023 {
1024         return menubar_;
1025 }
1026
1027
1028 } // namespace lyx