3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Asger Alstrup
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Martin Vermeer
14 * Full author contact details are available in file CREDITS.
22 #include "GuiApplication.h"
24 #include "GuiWorkArea.h"
25 #include "qt_helpers.h"
27 #include "BiblioInfo.h"
28 #include "BranchList.h"
30 #include "BufferList.h"
31 #include "BufferParams.h"
32 #include "BufferView.h"
33 #include "Converter.h"
34 #include "CutAndPaste.h"
36 #include "FloatList.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "IndicesList.h"
45 #include "LyXAction.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
53 #include "SpellChecker.h"
54 #include "TextClass.h"
56 #include "TocBackend.h"
58 #include "WordLangTuple.h"
60 #include "insets/Inset.h"
61 #include "insets/InsetCitation.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetInfo.h"
64 #include "insets/InsetQuotes.h"
66 #include "support/lassert.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/docstring_list.h"
70 #include "support/filetools.h"
71 #include "support/gettext.h"
72 #include "support/lstrings.h"
79 #if QT_VERSION >= 0x040600
80 #include <QProxyStyle>
88 using namespace lyx::support;
96 // MacOSX specific stuff is at the end.
103 /// The type of elements that can be in a menu
111 /** This type of item explains why something is unavailable. If this
112 menuitem is in a submenu, the submenu is enabled to make sure the
113 user sees the information. */
115 /** This type of item merely shows that there might be a list or
116 something alike at this position, but the list is still empty.
117 If this item is in a submenu, the submenu will not always be
120 /** This is the list of last opened file,
121 typically for the File menu. */
123 /** This is the list of opened Documents,
124 typically for the Documents menu. */
126 /** This is the bookmarks */
130 /** This is a list of viewable formats
131 typically for the File->View menu. */
133 /** This is a list of updatable formats
134 typically for the File->Update menu. */
136 /** This is a list of exportable formats
137 typically for the File->Export menu. */
139 /** This exports the document default format
140 typically for the File->Export menu. */
142 /** This is a list of importable formats
143 typically for the File->Import menu. */
145 /** This is the list of elements available
146 * for insertion into document. */
148 /** This is the list of user-configurable
149 insets to insert into document */
151 /** This is the list of floats that we can
152 insert a list for. */
154 /** This is the list of floats that we can
157 /** This is the list of selections that can
162 /** Available branches in document */
164 /** Available indices in document */
166 /** Context menu for indices in document */
168 /** Available index lists in document */
170 /** Context menu for available indices lists in document */
172 /** Available citation styles for a given citation */
174 /** Available arguments for a given info inset */
176 /** Available graphics groups */
178 /// Words suggested by the spellchecker.
180 /** Used Languages */
182 /** This is the list of arguments available
183 for insertion into the current layout. */
185 /** This is the list of arguments available
186 in the InsetArgument context menu. */
188 /** This is the list of captions available
189 in the current layout. */
191 /** This is the list of captions available
192 in the InsetCaption context menu. */
194 /** Commands to separate environments. */
195 EnvironmentSeparators,
196 /** Commands to separate environments (context menu version). */
197 EnvironmentSeparatorsContext,
198 /** This is the list of quotation marks available */
202 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
205 QString const & label,
206 QString const & submenu = QString(),
207 QString const & tooltip = QString(),
208 bool optional = false)
209 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
210 submenuname_(submenu), tooltip_(tooltip), optional_(optional)
212 LATTEST(kind == Submenu || kind == Help || kind == Info);
216 QString const & label,
217 FuncRequest const & func,
218 QString const & tooltip = QString(),
219 bool optional = false,
220 FuncRequest::Origin origin = FuncRequest::MENU)
221 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
222 tooltip_(tooltip), optional_(optional)
224 func_->setOrigin(origin);
227 /// The label of a given menuitem
228 QString label() const
230 int const index = label_.lastIndexOf('|');
231 return index == -1 ? label_ : label_.left(index);
234 /// The keyboard shortcut (usually underlined in the entry)
235 QString shortcut() const
237 int const index = label_.lastIndexOf('|');
238 return index == -1 ? QString() : label_.mid(index + 1);
240 /// The complete label, with label and shortcut separated by a '|'
241 QString fulllabel() const { return label_; }
242 /// The kind of entry
243 Kind kind() const { return kind_; }
244 /// the action (if relevant)
245 shared_ptr<FuncRequest const> func() const { return func_; }
247 QString const & tooltip() const { return tooltip_; }
248 /// returns true if the entry should be omitted when disabled
249 bool optional() const { return optional_; }
250 /// returns the status of the lfun associated with this entry
251 FuncStatus const & status() const { return status_; }
252 /// returns the status of the lfun associated with this entry
253 FuncStatus & status() { return status_; }
254 /// returns the status of the lfun associated with this entry
255 void status(FuncStatus const & status) { status_ = status; }
257 ///returns the binding associated to this action.
258 QString binding() const
260 if (kind_ != Command)
262 // Get the keys bound to this action, but keep only the
264 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
265 if (!bindings.empty())
266 return toqstr(bindings.begin()->print(KeySequence::ForGui));
268 LYXERR(Debug::KBMAP, "No binding for "
269 << lyxaction.getActionName(func_->action())
270 << '(' << func_->argument() << ')');
274 /// the description of the submenu (if relevant)
275 QString const & submenuname() const { return submenuname_; }
276 /// set the description of the submenu
277 void submenuname(QString const & name) { submenuname_ = name; }
279 bool hasSubmenu() const { return !submenu_.isEmpty(); }
281 MenuDefinition const & submenu() const { return submenu_.at(0); }
282 MenuDefinition & submenu() { return submenu_[0]; }
284 void setSubmenu(MenuDefinition const & menu)
287 submenu_.append(menu);
296 shared_ptr<FuncRequest> func_;// non-null
298 QString submenuname_;
305 /// contains 0 or 1 item.
306 QList<MenuDefinition> submenu_;
310 class MenuDefinition {
313 typedef std::vector<MenuItem> ItemList;
315 typedef ItemList::const_iterator const_iterator;
317 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
322 QString const & name() const { return name_; }
324 bool empty() const { return items_.empty(); }
325 /// Clear the menu content.
326 void clear() { items_.clear(); }
328 size_t size() const { return items_.size(); }
330 const_iterator begin() const { return items_.begin(); }
332 const_iterator end() const { return items_.end(); }
334 void cat(MenuDefinition const & other);
336 void catSub(docstring const & name);
338 // search for func in this menu iteratively, and put menu
340 bool searchMenu(FuncRequest const & func, docstring_list & names)
343 bool hasFunc(FuncRequest const &) const;
344 /// Add the menu item unconditionally
345 void add(MenuItem const & item) { items_.push_back(item); }
346 /// Checks the associated FuncRequest status before adding the
348 void addWithStatusCheck(MenuItem const &);
349 // Check whether the menu shortcuts are unique
350 void checkShortcuts() const;
352 void expandLastfiles();
353 void expandDocuments();
354 void expandBookmarks();
355 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
356 void expandFloatListInsert(Buffer const * buf);
357 void expandFloatInsert(Buffer const * buf);
358 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
359 void expandTocSubmenu(std::string const & type, Toc const & toc_list);
360 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
361 void expandToc(Buffer const * buf);
362 void expandPasteRecent(Buffer const * buf);
363 void expandToolbars();
364 void expandBranches(Buffer const * buf);
365 void expandIndices(Buffer const * buf, bool listof = false);
366 void expandIndicesContext(Buffer const * buf, bool listof = false);
367 void expandCiteStyles(BufferView const *);
368 void expandInfoArguments(BufferView const *);
369 void expandGraphicsGroups(BufferView const *);
370 void expandSpellingSuggestions(BufferView const *);
371 void expandLanguageSelector(Buffer const * buf);
372 void expandArguments(BufferView const *, bool switcharg = false);
373 void expandCaptions(Buffer const * buf, bool switchcap = false);
374 void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
375 void expandQuotes(BufferView const *);
383 /// Helper for std::find_if
387 MenuNamesEqual(QString const & name) : name_(name) {}
388 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
395 typedef std::vector<MenuDefinition> MenuList;
397 typedef MenuList::const_iterator const_iterator;
399 typedef MenuList::iterator iterator;
401 /////////////////////////////////////////////////////////////////////
402 // MenuDefinition implementation
403 /////////////////////////////////////////////////////////////////////
405 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
409 case MenuItem::Command: {
410 FuncStatus status = lyx::getStatus(*i.func());
411 if (status.unknown() || (!status.enabled() && i.optional()))
414 items_.back().status(status);
418 case MenuItem::Submenu: {
419 bool enabled = false;
420 if (i.hasSubmenu()) {
421 for (const_iterator cit = i.submenu().begin();
422 cit != i.submenu().end(); ++cit) {
423 // Only these kind of items affect the status of the submenu
424 if ((cit->kind() == MenuItem::Command
425 || cit->kind() == MenuItem::Submenu
426 || cit->kind() == MenuItem::Help)
427 && cit->status().enabled()) {
433 if (enabled || !i.optional()) {
435 items_.back().status().setEnabled(enabled);
440 case MenuItem::Separator:
441 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
451 void MenuDefinition::read(Lexer & lex)
468 md_indiceslistscontext,
483 md_spellingsuggestions,
490 md_env_separatorscontext,
494 LexerKeyword menutags[] = {
495 { "arguments", md_arguments },
496 { "bookmarks", md_bookmarks },
497 { "branches", md_branches },
498 { "captions", md_captions },
499 { "charstyles", md_charstyles },
500 { "citestyles", md_citestyles },
501 { "custom", md_custom },
502 { "documents", md_documents },
503 { "end", md_endmenu },
504 { "environmentseparators", md_env_separators },
505 { "environmentseparatorscontext", md_env_separatorscontext },
506 { "exportformat", md_exportformat },
507 { "exportformats", md_exportformats },
508 { "floatinsert", md_floatinsert },
509 { "floatlistinsert", md_floatlistinsert },
510 { "graphicsgroups", md_graphicsgroups },
511 { "importformats", md_importformats },
512 { "indices", md_indices },
513 { "indicescontext", md_indicescontext },
514 { "indiceslists", md_indiceslists },
515 { "indiceslistscontext", md_indiceslistscontext },
516 { "infoarguments", md_infoarguments },
518 { "languageselector", md_languageselector },
519 { "lastfiles", md_lastfiles },
520 { "optitem", md_optitem },
521 { "optsubmenu", md_optsubmenu },
522 { "pasterecent", md_pasterecent },
523 { "separator", md_separator },
524 { "spellingsuggestions", md_spellingsuggestions },
525 { "submenu", md_submenu },
526 { "switcharguments", md_switcharguments },
527 { "switchcaptions", md_switchcaptions },
528 { "switchquotes", md_switchquotes },
530 { "toolbars", md_toolbars },
531 { "updateformats", md_updateformats },
532 { "viewformats", md_viewformats }
535 lex.pushTable(menutags);
536 lex.setContext("MenuDefinition::read: ");
539 while (lex.isOK() && md_type != md_endmenu) {
540 switch (md_type = lex.lex()) {
544 docstring const name = translateIfPossible(lex.getDocString());
546 string const command = lex.getString();
547 FuncRequest func = lyxaction.lookupFunc(command);
548 FuncRequest::Origin origin = FuncRequest::MENU;
549 if (name_.startsWith("context-toc-"))
550 origin = FuncRequest::TOC;
551 bool const optional = (md_type == md_optitem);
552 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
557 add(MenuItem(MenuItem::Separator));
561 add(MenuItem(MenuItem::Lastfiles));
565 add(MenuItem(MenuItem::CharStyles));
569 add(MenuItem(MenuItem::Custom));
573 add(MenuItem(MenuItem::Documents));
577 add(MenuItem(MenuItem::Bookmarks));
581 add(MenuItem(MenuItem::Toc));
585 add(MenuItem(MenuItem::ViewFormats));
588 case md_updateformats:
589 add(MenuItem(MenuItem::UpdateFormats));
592 case md_exportformats:
593 add(MenuItem(MenuItem::ExportFormats));
596 case md_exportformat:
597 add(MenuItem(MenuItem::ExportFormat));
600 case md_importformats:
601 add(MenuItem(MenuItem::ImportFormats));
604 case md_floatlistinsert:
605 add(MenuItem(MenuItem::FloatListInsert));
609 add(MenuItem(MenuItem::FloatInsert));
613 add(MenuItem(MenuItem::PasteRecent));
617 add(MenuItem(MenuItem::Toolbars));
621 add(MenuItem(MenuItem::Branches));
625 add(MenuItem(MenuItem::CiteStyles));
628 case md_infoarguments:
629 add(MenuItem(MenuItem::InfoArguments));
633 case md_graphicsgroups:
634 add(MenuItem(MenuItem::GraphicsGroups));
637 case md_spellingsuggestions:
638 add(MenuItem(MenuItem::SpellingSuggestions));
641 case md_languageselector:
642 add(MenuItem(MenuItem::LanguageSelector));
646 add(MenuItem(MenuItem::Indices));
649 case md_indicescontext:
650 add(MenuItem(MenuItem::IndicesContext));
653 case md_indiceslists:
654 add(MenuItem(MenuItem::IndicesLists));
657 case md_indiceslistscontext:
658 add(MenuItem(MenuItem::IndicesListsContext));
662 add(MenuItem(MenuItem::Arguments));
665 case md_switcharguments:
666 add(MenuItem(MenuItem::SwitchArguments));
670 add(MenuItem(MenuItem::Captions));
673 case md_switchcaptions:
674 add(MenuItem(MenuItem::SwitchCaptions));
677 case md_env_separators:
678 add(MenuItem(MenuItem::EnvironmentSeparators));
681 case md_env_separatorscontext:
682 add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
685 case md_switchquotes:
686 add(MenuItem(MenuItem::SwitchQuotes));
692 docstring const mlabel = translateIfPossible(lex.getDocString());
694 docstring const mname = lex.getDocString();
695 bool const optional = (md_type == md_optsubmenu);
696 add(MenuItem(MenuItem::Submenu,
697 toqstr(mlabel), toqstr(mname), QString(), optional));
705 lex.printError("Unknown menu tag");
713 bool MenuDefinition::hasFunc(FuncRequest const & func) const
715 for (const_iterator it = begin(), et = end(); it != et; ++it)
716 if (*it->func() == func)
722 void MenuDefinition::catSub(docstring const & name)
724 add(MenuItem(MenuItem::Submenu,
725 qt_("More...|M"), toqstr(name), QString(), false));
728 void MenuDefinition::cat(MenuDefinition const & other)
730 const_iterator et = other.end();
731 for (const_iterator it = other.begin(); it != et; ++it)
736 void MenuDefinition::checkShortcuts() const
738 // This is a quadratic algorithm, but we do not care because
739 // menus are short enough
740 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
741 QString shortcut = it1->shortcut();
742 if (shortcut.isEmpty())
744 if (!it1->label().contains(shortcut))
745 LYXERR0("Menu warning: menu entry \""
747 << "\" does not contain shortcut `"
748 << shortcut << "'.");
749 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
750 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
751 LYXERR0("Menu warning: menu entries "
752 << '"' << it1->fulllabel()
753 << "\" and \"" << it2->fulllabel()
754 << "\" share the same shortcut.");
761 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
763 const_iterator m = begin();
764 const_iterator m_end = end();
765 for (; m != m_end; ++m) {
766 if (m->kind() == MenuItem::Command && *m->func() == func) {
767 names.push_back(qstring_to_ucs4(m->label()));
770 if (m->kind() == MenuItem::Submenu) {
771 names.push_back(qstring_to_ucs4(m->label()));
772 if (!m->hasSubmenu()) {
773 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
774 << m->label() << " name=" << m->submenuname());
778 if (m->submenu().searchMenu(func, names))
787 QString limitStringLength(docstring const & str)
789 size_t const max_item_length = 45;
790 docstring ret = str.substr(0, max_item_length + 1);
791 support::truncateWithEllipsis(ret, max_item_length);
796 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
801 graphics::getGraphicsGroups(bv->buffer(), grp);
805 set<string>::const_iterator it = grp.begin();
806 set<string>::const_iterator end = grp.end();
807 add(MenuItem(MenuItem::Command, qt_("No Group"),
808 FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
809 for (; it != end; ++it) {
810 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
811 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
816 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
820 Cursor const & cur = bv->cursor();
824 docstring_list suggestions;
825 Paragraph const & par = cur.paragraph();
826 pos_type from = cur.pos();
828 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
830 case SpellChecker::UNKNOWN_WORD:
831 if (lyxrc.spellcheck_continuously) {
832 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
833 docstring const & selection = cur.selectionAsString(false);
834 if (!cur.selection() || selection == wl.word()) {
836 size_t m = 10; // first submenu index
837 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
838 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
839 for (; i != suggestions.size(); ++i) {
840 docstring const & suggestion = suggestions[i];
841 LYXERR(Debug::GUI, suggestion);
842 MenuItem w(MenuItem::Command, toqstr(suggestion),
843 FuncRequest(LFUN_WORD_REPLACE,
844 replace2string(suggestion, selection,
845 true, // case sensitive
849 false))); // find next
853 item.submenu().add(w);
858 add(MenuItem(MenuItem::Separator));
859 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
860 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
861 FuncRequest(LFUN_SPELLING_ADD, arg)));
862 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
863 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
867 case SpellChecker::LEARNED_WORD: {
868 LYXERR(Debug::GUI, "Learned Word.");
869 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
870 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
871 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
874 case SpellChecker::NO_DICTIONARY:
875 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
877 case SpellChecker::WORD_OK:
878 case SpellChecker::COMPOUND_WORD:
879 case SpellChecker::ROOT_FOUND:
880 case SpellChecker::IGNORED_WORD:
885 struct sortLanguageByName {
886 bool operator()(const Language * a, const Language * b) const {
887 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
891 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
896 std::set<Language const *> languages_buffer =
897 buf->masterBuffer()->getLanguages();
899 if (languages_buffer.size() < 2) {
900 add(MenuItem(MenuItem::Command, qt_("Switch Language...|L"),
901 FuncRequest(LFUN_DIALOG_SHOW, "character")));
905 std::set<Language const *, sortLanguageByName> langs;
907 std::set<Language const *>::const_iterator const beg =
908 languages_buffer.begin();
909 for (std::set<Language const *>::const_iterator cit = beg;
910 cit != languages_buffer.end(); ++cit) {
914 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
915 item.setSubmenu(MenuDefinition(qt_("Language")));
916 QString morelangs = qt_("More Languages ...|M");
917 QStringList accelerators;
918 if (morelangs.contains('|'))
919 accelerators.append(morelangs.section('|', -1));
920 std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
921 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
922 cit != langs.end(); ++cit) {
923 QString label = qt_((*cit)->display());
924 // try to add an accelerator
925 bool success = false;
926 // try capitals first
927 for (int i = 0; i < label.size(); ++i) {
928 QChar const ch = label[i];
931 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
932 label = label + toqstr("|") + ch;
933 accelerators.append(ch);
938 // if all capitals are taken, try the rest
940 for (int i = 0; i < label.size(); ++i) {
941 if (label[i].isSpace())
943 QString const ch = QString(label[i]);
944 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
945 label = label + toqstr("|") + ch;
946 accelerators.append(ch);
951 MenuItem w(MenuItem::Command, label,
952 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
953 item.submenu().addWithStatusCheck(w);
955 item.submenu().add(MenuItem(MenuItem::Separator));
956 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
957 FuncRequest(LFUN_DIALOG_SHOW, "character")));
962 void MenuDefinition::expandLastfiles()
964 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
965 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
969 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
970 string const file = lfit->absFileName();
971 QString const short_path = toqstr(makeDisplayPath(file, 30));
972 QString const long_path = toqstr(makeDisplayPath(file));
975 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
977 label = QString("%1. %2").arg(ii).arg(short_path);
978 add(MenuItem(MenuItem::Command, label,
979 FuncRequest(LFUN_FILE_OPEN, file), long_path));
984 void MenuDefinition::expandDocuments()
986 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
987 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
989 Buffer * first = theBufferList().first();
991 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
997 if (!guiApp->currentView())
999 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
1002 Buffer const & b = wa->bufferView().buffer();
1003 QString label = toqstr(b.fileName().displayName(20));
1006 if (b.notifiesExternalModification())
1007 label += QChar(0x26a0);
1009 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1010 add(MenuItem(MenuItem::Command, label,
1011 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1018 // We cannot use a for loop as the buffer list cycles.
1020 if (!(guiApp->currentView()
1021 && guiApp->currentView()->workArea(*b))) {
1022 QString label = toqstr(b->fileName().displayName(20));
1025 if (b->notifiesExternalModification())
1026 label += QChar(0x26a0);
1028 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1029 item.submenu().add(MenuItem(MenuItem::Command, label,
1030 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1033 b = theBufferList().next(b);
1034 } while (b != first);
1036 if (!item.submenu().empty())
1041 void MenuDefinition::expandBookmarks()
1043 lyx::BookmarksSection const & bm = theSession().bookmarks();
1046 for (size_t i = 1; i <= bm.size(); ++i) {
1047 if (bm.isValid(i)) {
1048 string const file = bm.bookmark(i).filename.absFileName();
1049 QString const label = QString("%1. %2|%3").arg(i)
1050 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1051 add(MenuItem(MenuItem::Command, label,
1052 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1057 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1061 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1063 if (!buf && kind != MenuItem::ImportFormats)
1067 FuncCode action = LFUN_NOACTION;
1070 case MenuItem::ImportFormats:
1071 formats = theConverters().importableFormats();
1072 action = LFUN_BUFFER_IMPORT;
1074 case MenuItem::ViewFormats:
1075 formats = buf->params().exportableFormats(true);
1076 action = LFUN_BUFFER_VIEW;
1078 case MenuItem::UpdateFormats:
1079 formats = buf->params().exportableFormats(true);
1080 action = LFUN_BUFFER_UPDATE;
1082 case MenuItem::ExportFormats:
1083 formats = buf->params().exportableFormats(false);
1084 action = LFUN_BUFFER_EXPORT;
1091 bool const view_update = (kind == MenuItem::ViewFormats
1092 || kind == MenuItem::UpdateFormats);
1096 smenue = (kind == MenuItem::ViewFormats
1097 ? qt_("View (Other Formats)|F")
1098 : qt_("Update (Other Formats)|p"));
1099 MenuItem item(MenuItem::Submenu, smenue);
1100 item.setSubmenu(MenuDefinition(smenue));
1102 for (Format const * f : formats) {
1106 docstring lab = f->prettyname();
1107 docstring const scut = from_utf8(f->shortcut());
1108 docstring const tmplab = lab;
1111 lab += char_type('|') + scut;
1112 docstring const lab_i18n = translateIfPossible(lab);
1113 docstring const shortcut = split(lab_i18n, lab, '|');
1115 bool const untranslated = (lab == lab_i18n);
1116 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1119 case MenuItem::ImportFormats:
1122 label += from_ascii("...");
1124 case MenuItem::ViewFormats:
1125 case MenuItem::UpdateFormats:
1126 if (f->name() == buf->params().getDefaultOutputFormat()) {
1127 docstring lbl = (kind == MenuItem::ViewFormats
1128 ? bformat(_("View [%1$s]|V"), label)
1129 : bformat(_("Update [%1$s]|U"), label));
1130 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1134 case MenuItem::ExportFormats:
1135 if (!f->inExportMenu())
1139 // we already asserted earlier in this case
1143 if (!shortcut.empty())
1144 label += '|' + shortcut;
1147 // note that at this point, we know that buf is not null
1149 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1150 toqstr(label), FuncRequest(action, f->name())));
1153 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1154 FuncRequest(action, f->name())));
1156 add(MenuItem(MenuItem::Command, toqstr(label),
1157 FuncRequest(action, f->name())));
1165 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1170 FloatList const & floats = buf->params().documentClass().floats();
1171 FloatList::const_iterator cit = floats.begin();
1172 FloatList::const_iterator end = floats.end();
1174 for (; cit != end; ++cit) {
1175 if (!cit->second.usesFloatPkg()) {
1176 // Different floats could declare the same ListCommand. We only
1177 // want it on the list once, though.
1178 string const & list_cmd = cit->second.listCommand();
1179 if (list_cmd.empty())
1180 // we do not know how to generate such a list
1182 // This form of insert returns an iterator pointing to the newly
1183 // inserted element OR the existing element with that value, and
1184 // a bool indicating whether we inserted a new element. So we can
1185 // see if one is there and insert it if not all at once.
1186 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1190 string const & list_name = cit->second.listName();
1191 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1192 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1197 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1202 FloatList const & floats = buf->params().documentClass().floats();
1203 FloatList::const_iterator cit = floats.begin();
1204 FloatList::const_iterator end = floats.end();
1205 for (; cit != end; ++cit) {
1207 if (cit->second.name().empty())
1209 QString const label = qt_(cit->second.name());
1210 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1211 FuncRequest(LFUN_FLOAT_INSERT,
1212 cit->second.floattype())));
1217 void MenuDefinition::expandFlexInsert(
1218 Buffer const * buf, InsetLayout::InsetLyXType type)
1223 TextClass::InsetLayouts const & insetLayouts =
1224 buf->params().documentClass().insetLayouts();
1225 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1226 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1227 for (; cit != end; ++cit) {
1228 if (cit->second.lyxtype() == type) {
1229 if (!cit->second.obsoleted_by().empty())
1231 docstring name = cit->first;
1232 // we remove the "Flex:" prefix, if it is present
1233 if (prefixIs(name, from_ascii("Flex:")))
1234 name = name.substr(5);
1235 docstring const label = (cit->second.menustring().empty()) ?
1237 : cit->second.menustring();
1238 addWithStatusCheck(MenuItem(MenuItem::Command,
1239 toqstr(translateIfPossible(label)),
1240 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(name))));
1243 // FIXME This is a little clunky.
1244 if (items_.empty() && type == InsetLayout::CUSTOM && !buf->hasReadonlyFlag())
1245 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1249 // Threshold before we stop displaying sub-items alongside items
1250 // (for display purposes). Ideally this should fit on a screen.
1251 size_t const max_number_of_items = 30;
1252 // Size limit for the menu. This is for performance purposes,
1253 // because qt already displays a scrollable menu when necessary.
1254 // Ideally this should be the menu size from which scrollable
1255 // menus become unpractical.
1256 size_t const menu_size_limit = 80;
1258 void MenuDefinition::expandToc2(Toc const & toc_list,
1259 size_t from, size_t to, int depth,
1262 int shortcut_count = 0;
1264 // check whether depth is smaller than the smallest depth in toc.
1265 int min_depth = 1000;
1266 for (size_t i = from; i < to; ++i)
1267 min_depth = min(min_depth, toc_list[i].depth());
1268 if (min_depth > depth)
1271 if (to - from <= max_number_of_items) {
1272 for (size_t i = from; i < to; ++i) {
1273 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1274 label += limitStringLength(toc_list[i].asString());
1275 if (toc_list[i].depth() == depth) {
1277 if (shortcut_count < 9) {
1278 if (label.contains(QString::number(shortcut_count + 1)))
1279 label += QString::number(++shortcut_count);
1282 add(MenuItem(MenuItem::Command, label,
1283 FuncRequest(toc_list[i].action())));
1284 // separator after the menu heading
1285 if (toc_list[i].depth() < depth)
1286 add(MenuItem(MenuItem::Separator));
1292 size_t new_pos = pos + 1;
1293 while (new_pos < to && toc_list[new_pos].depth() > depth)
1296 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1297 label += limitStringLength(toc_list[pos].asString());
1298 if (toc_list[pos].depth() == depth) {
1300 if (shortcut_count < 9) {
1301 if (label.contains(QString::number(shortcut_count + 1)))
1302 label += QString::number(++shortcut_count);
1305 if (size >= menu_size_limit) {
1306 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1307 add(MenuItem(MenuItem::Command, "...", f));
1310 if (new_pos == pos + 1) {
1311 add(MenuItem(MenuItem::Command,
1312 label, FuncRequest(toc_list[pos].action())));
1315 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1316 MenuItem item(MenuItem::Submenu, label);
1317 item.setSubmenu(sub);
1327 void MenuDefinition::expandToc(Buffer const * buf)
1329 // To make things very cleanly, we would have to pass buf to
1330 // all MenuItem constructors and to expandToc2. However, we
1331 // know that all the entries in a TOC will be have status_ ==
1332 // OK, so we avoid this unnecessary overhead (JMarc)
1334 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1337 // Add an entry for the master doc if this is a child doc
1338 Buffer const * const master = buf->masterBuffer();
1339 if (buf != master) {
1340 ParIterator const pit = par_iterator_begin(master->inset());
1341 string const arg = convert<string>(pit->id());
1342 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1343 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1346 MenuDefinition other_lists;
1347 // In the navigation menu, only add tocs from this document
1348 TocBackend const & backend = buf->tocBackend();
1349 TocList const & toc_list = backend.tocs();
1350 for (pair<const string, shared_ptr<Toc>> const & toc : toc_list) {
1351 // Handle table of contents later
1352 if (toc.first == "tableofcontents" || toc.second->empty())
1354 MenuDefinition submenu;
1355 submenu.expandTocSubmenu(toc.first, *toc.second);
1356 docstring const toc_name = backend.outlinerName(toc.first);
1357 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1358 item.setSubmenu(submenu);
1359 // deserves to be in the main menu?
1360 if (!TocBackend::isOther(toc.first))
1363 other_lists.add(item);
1365 if (!other_lists.empty()) {
1366 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1367 item.setSubmenu(other_lists);
1370 // Handle normal TOC
1371 add(MenuItem(MenuItem::Separator));
1372 TocList::const_iterator cit = toc_list.find("tableofcontents");
1373 if (cit == toc_list.end())
1374 LYXERR(Debug::GUI, "No table of contents.");
1376 if (!cit->second->empty())
1377 expandToc2(*cit->second, 0, cit->second->size(), 0,
1380 add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1385 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1387 // "Open outliner..." entry
1388 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1389 add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1390 add(MenuItem(MenuItem::Separator));
1392 expandToc2(toc, 0, toc.size(), 0, type);
1396 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1398 docstring_list const sel = cap::availableSelections(buf);
1400 docstring_list::const_iterator cit = sel.begin();
1401 docstring_list::const_iterator end = sel.end();
1403 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1404 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1405 FuncRequest(LFUN_PASTE, convert<string>(index))));
1410 void MenuDefinition::expandToolbars()
1412 MenuDefinition other_lists;
1413 // extracts the toolbars from the backend
1414 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1415 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1416 for (; cit != end; ++cit) {
1417 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1418 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1419 if (guiApp->toolbars().isMainToolbar(cit->name))
1422 other_lists.add(item);
1425 if (!other_lists.empty()) {
1426 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1427 item.setSubmenu(other_lists);
1433 void MenuDefinition::expandBranches(Buffer const * buf)
1435 if (!buf || buf->hasReadonlyFlag())
1438 BranchList const & child_list = buf->params().branchlist();
1439 set<docstring> brset;
1441 for (auto const & b : child_list) {
1442 docstring const & bname = b.branch();
1443 // NUM. Branch Name + "|", which triggers an empty shortcut in
1444 // case that character should be in the branch name.
1445 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1446 // Add NUM as a keyboard shortcut if it's a single digit
1448 label += convert<docstring>(ii);
1450 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1451 FuncRequest(LFUN_BRANCH_INSERT, bname)));
1453 brset.insert(bname);
1457 set<Buffer const *> bufset;
1458 Buffer const * nextbuf = buf->parent();
1459 MenuDefinition master_branches;
1462 // recursive includes are a bad idea, but let's not crash
1464 if (bufset.count(nextbuf))
1467 for (auto const & b : nextbuf->params().branchlist()) {
1468 docstring const & bname = b.branch();
1469 // do not add it if we've already seen it
1470 if (brset.count(bname))
1473 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1475 label += convert<docstring>(ii);
1477 master_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1478 toqstr(label), FuncRequest(LFUN_BRANCH_INSERT, bname)));
1480 bufset.insert(nextbuf);
1481 brset.insert(bname);
1485 nextbuf = nextbuf->parent();
1488 if (!master_branches.empty()) {
1489 MenuItem item(MenuItem::Submenu, qt_("Master Documents"));
1490 item.setSubmenu(master_branches);
1496 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1501 BufferParams const & params = buf->masterBuffer()->params();
1502 if (!params.use_indices) {
1504 addWithStatusCheck(MenuItem(MenuItem::Command,
1505 qt_("Index List|I"),
1506 FuncRequest(LFUN_INDEX_PRINT,
1507 from_ascii("idx"))));
1509 addWithStatusCheck(MenuItem(MenuItem::Command,
1510 qt_("Index Entry|d"),
1511 FuncRequest(LFUN_INDEX_INSERT,
1512 from_ascii("idx"))));
1516 if (params.indiceslist().empty())
1519 IndicesList::const_iterator cit = params.indiceslist().begin();
1520 IndicesList::const_iterator end = params.indiceslist().end();
1522 for (int ii = 1; cit != end; ++cit, ++ii) {
1524 docstring const label =
1525 bformat(_("Index: %1$s"), cit->index());
1526 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1527 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1529 docstring const label =
1530 bformat(_("Index Entry (%1$s)"), cit->index());
1531 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1532 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1538 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1543 BufferParams const & params = buf->masterBuffer()->params();
1544 if (!params.use_indices || params.indiceslist().empty())
1547 IndicesList::const_iterator cit = params.indiceslist().begin();
1548 IndicesList::const_iterator end = params.indiceslist().end();
1550 for (int ii = 1; cit != end; ++cit, ++ii) {
1552 InsetCommandParams p(INDEX_PRINT_CODE);
1553 p["type"] = cit->shortcut();
1554 string const data = InsetCommand::params2string(p);
1555 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1556 FuncRequest(LFUN_INSET_MODIFY, data)));
1558 docstring const label =
1559 bformat(_("Index Entry (%1$s)"), cit->index());
1560 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1561 FuncRequest(LFUN_INSET_MODIFY,
1562 from_ascii("changetype ") + cit->shortcut())));
1568 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1573 Inset const * inset = bv->cursor().nextInset();
1574 if (!inset || inset->lyxCode() != CITE_CODE) {
1575 add(MenuItem(MenuItem::Command,
1576 qt_("No Citation in Scope!"),
1577 FuncRequest(LFUN_NOACTION)));
1580 InsetCitation const * citinset =
1581 static_cast<InsetCitation const *>(inset);
1583 Buffer const * buf = &bv->buffer();
1584 BufferParams const & bp = buf->masterParams();
1585 string const cmd = citinset->params().getCmdName();
1587 docstring const & key = citinset->getParam("key");
1589 add(MenuItem(MenuItem::Command,
1590 qt_("No citations selected!"),
1591 FuncRequest(LFUN_NOACTION)));
1595 bool const force = isUpperCase(cmd[0]);
1596 bool const star = suffixIs(cmd, '*');
1598 vector<docstring> const keys = getVectorFromString(key);
1600 vector<CitationStyle> const citeStyleList = bp.citeStyles();
1602 CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1603 bool const qualified = cs.hasQualifiedList
1605 || !citinset->getParam("pretextlist").empty()
1606 || !citinset->getParam("posttextlist").empty());
1607 vector<pair<docstring, docstring>> pres =
1608 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1609 vector<pair<docstring, docstring>> posts =
1610 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1613 ci.textBefore = citinset->getParam("before");
1614 ci.textAfter = citinset->getParam("after");
1615 ci.forceUpperCase = force;
1617 ci.context = CiteItem::Dialog;
1619 ci.isQualified = qualified;
1621 ci.posttexts = posts;
1622 BiblioInfo::CiteStringMap citeStrings =
1623 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1625 BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1626 BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1628 for (int ii = 1; cit != end; ++cit, ++ii) {
1629 docstring label = cit->second;
1630 CitationStyle ccs = citeStyleList[ii - 1];
1631 ccs.forceUpperCase &= force;
1632 ccs.hasStarredVersion &= star;
1633 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1634 FuncRequest(LFUN_INSET_MODIFY,
1635 "changetype " + from_utf8(citationStyleToString(ccs)))));
1638 if (cs.hasStarredVersion) {
1639 docstring starred = _("All authors|h");
1640 // Check if we have a custom string/tooltip for the starred version
1641 if (!cs.stardesc.empty()) {
1643 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1645 starred = translateIfPossible(from_utf8(val));
1646 // Transform qt-style accelerators to menu-style
1647 int const amps = count_char(starred, '&');
1650 starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1651 size_t nn = starred.find('&');
1652 char_type accel = char_type();
1653 if (nn != docstring::npos && nn < starred.size() - 1)
1654 accel = starred[nn + 1];
1655 starred = subst(starred, from_ascii("&"), from_ascii(""));
1657 starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1658 if (accel != char_type())
1659 starred = starred + '|' + accel;
1662 add(MenuItem(MenuItem::Separator));
1663 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1664 FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1667 if (cs.forceUpperCase) {
1668 if (!cs.hasStarredVersion)
1669 add(MenuItem(MenuItem::Separator));
1670 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1671 FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1676 void MenuDefinition::expandInfoArguments(BufferView const * bv)
1681 Inset const * inset = bv->cursor().nextInset();
1682 if (!inset || inset->lyxCode() != INFO_CODE) {
1683 add(MenuItem(MenuItem::Command,
1684 qt_("No Text Field in Scope!"),
1685 FuncRequest(LFUN_NOACTION)));
1688 InsetInfo const * iinset = static_cast<InsetInfo const *>(inset);
1690 string const type = iinset->params().infoType();
1691 vector<pair<string,docstring>> const args =
1692 iinset->params().getArguments(&bv->buffer(), type);
1694 // Don't generate a menu for big lists (such as lfuns and rcs)
1695 if (args.size() > 15)
1698 for (auto const & p : args) {
1699 if (p.first == "invalid")
1702 if (p.first == "custom") {
1703 add(MenuItem(MenuItem::Command, qt_("Custom..."),
1704 FuncRequest(LFUN_INSET_SETTINGS, "info")));
1707 docstring label = p.second;
1708 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1709 FuncRequest(LFUN_INSET_MODIFY, type + " " + p.first)));
1715 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1720 if (!bv->cursor().inTexted())
1723 Inset const * inset = &bv->cursor().inset();
1724 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1725 if (inset && args.empty())
1726 args = inset->getLayout().args();
1727 if (args.empty() || (switcharg && args.size() == 1))
1729 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1730 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1731 for (; lait != laend; ++lait) {
1732 Layout::latexarg arg = (*lait).second;
1733 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1734 QString item = toqstr(translateIfPossible(str));
1736 add(MenuItem(MenuItem::Command, item,
1737 FuncRequest(LFUN_INSET_MODIFY,
1738 from_ascii("changetype ")
1739 + from_ascii((*lait).first))));
1741 add(MenuItem(MenuItem::Command, item,
1742 FuncRequest(LFUN_ARGUMENT_INSERT,
1743 from_ascii((*lait).first))));
1748 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1753 DocumentClass const & dc = buf->params().documentClass();
1754 vector< pair<docstring, FuncRequest> > caps;
1755 for (pair<const docstring, InsetLayout> const & il : dc.insetLayouts()) {
1757 docstring const type = split(il.first, instype, ':');
1758 if (instype == from_ascii("Caption")) {
1759 // skip forbidden caption types
1760 FuncRequest const cmd = switchcap
1761 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1762 : FuncRequest(LFUN_CAPTION_INSERT, type);
1763 if (getStatus(cmd).enabled())
1764 caps.push_back(make_pair(type, cmd));
1768 if (caps.empty() || (switchcap && caps.size() == 1))
1770 if (caps.size() == 1) {
1771 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1775 MenuDefinition captions;
1776 for (pair<docstring, FuncRequest> const & cap : caps) {
1777 docstring const type = cap.first;
1778 docstring const trtype = translateIfPossible(type);
1779 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1781 add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1783 captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1785 if (!captions.empty()) {
1786 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1787 item.setSubmenu(captions);
1793 void MenuDefinition::expandQuotes(BufferView const * bv)
1798 if (!bv->cursor().inTexted())
1801 Inset const * inset = bv->cursor().nextInset();
1802 if (!inset || inset->lyxCode() != QUOTE_CODE) {
1803 add(MenuItem(MenuItem::Command,
1804 qt_("No Quote in Scope!"),
1805 FuncRequest(LFUN_NOACTION)));
1808 InsetQuotes const * qinset =
1809 static_cast<InsetQuotes const *>(inset);
1811 map<string, docstring> styles = quoteparams.getTypes();
1812 string const qtype = qinset->getType();
1814 map<string, docstring>::const_iterator qq = styles.begin();
1815 map<string, docstring>::const_iterator end = styles.end();
1819 BufferParams const & bp = bv->buffer().masterBuffer()->params();
1821 // The global setting
1822 InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1823 char const globalqsc = quoteparams.getStyleChar(globalqs);
1825 // The current language's default
1826 InsetQuotesParams::QuoteStyle langdefqs =
1827 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1828 char const langqs = quoteparams.getStyleChar(langdefqs);
1830 bool main_global_qs = false;
1831 bool main_langdef_qs = false;
1832 bool main_dynamic_qs = false;
1833 docstring const subcmd = from_ascii("changetype ");
1834 docstring const wildcards = from_ascii("..");
1836 // First the top level menu (all glyphs of the current style) ...
1837 // Begin with dynamic (if they are current style),
1838 if (qtype[0] == 'x') {
1839 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1840 docstring desc = bformat(_("%1$s (dynamic)"),
1841 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1842 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1843 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1844 desc = bformat(_("%1$s (dynamic)"),
1845 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1846 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1847 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1848 desc = bformat(_("%1$s (dynamic)"),
1849 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1850 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1851 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1852 desc = bformat(_("%1$s (dynamic)"),
1853 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1854 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1855 main_dynamic_qs = true;
1857 // now traverse through the static styles ...
1858 for (; qq != end; ++qq) {
1859 docstring const style = from_ascii(qq->first);
1860 bool langdef = (style[0] == langqs);
1861 bool globaldef = (style[0] == globalqsc);
1863 if (prefixIs(style, qtype[0])) {
1864 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1865 docstring const desc = quoteparams.getShortGuiLabel(style);
1866 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1867 main_global_qs = globaldef;
1868 main_langdef_qs = langdef;
1870 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1871 docstring const desc =
1872 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1873 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1874 aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1878 add(MenuItem(MenuItem::Separator));
1880 bool display_static = false;
1881 // ... then potentially items to reset to the defaults and to dynamic style ...
1882 if (!main_dynamic_qs && globalqsc != 'x') {
1883 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1884 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1885 quoteparams.getGuiLabel(globalqs));
1886 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1887 display_static = true;
1889 if (!main_global_qs && langdefqs != globalqs) {
1890 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1891 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1892 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1893 quoteparams.getGuiLabel(globalqs), variant);
1894 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1896 if (!main_langdef_qs) {
1897 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1898 docstring const desc = (main_dynamic_qs || display_static)
1899 ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1900 quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1901 : bformat(_("Reset to language default (%1$s)|l"),
1902 quoteparams.getGuiLabel(langdefqs));
1903 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1906 add(MenuItem(MenuItem::Separator));
1908 // ... and a subitem with the rest
1909 MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1910 item.setSubmenu(aqs);
1915 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1920 Text const * text = bv->cursor().text();
1921 // no paragraphs and no separators exist in math
1925 pit_type pit = bv->cursor().selBegin().pit();
1926 Paragraph const & par = text->getPar(pit);
1927 docstring const curlayout = par.layout().name();
1928 docstring outerlayout;
1929 docstring prevlayout;
1930 depth_type current_depth = par.params().depth();
1931 // check if we have an environment in our scope
1932 Paragraph cpar = par;
1937 cpar = text->getPar(pit);
1938 if (cpar.layout().isEnvironment() && prevlayout.empty()
1939 && cpar.params().depth() <= current_depth)
1940 prevlayout = cpar.layout().name();
1941 if (cpar.params().depth() < current_depth
1942 && cpar.layout().isEnvironment()) {
1943 outerlayout = cpar.layout().name();
1944 current_depth = cpar.params().depth();
1946 if (cpar.params().depth() == 0)
1949 if (par.layout().isEnvironment()) {
1950 docstring label = contextmenu ?
1951 bformat(_("Insert Separated %1$s Above"),
1952 translateIfPossible(curlayout)) :
1953 bformat(_("Separated %1$s Above"),
1954 translateIfPossible(curlayout));
1955 add(MenuItem(MenuItem::Command, toqstr(label),
1956 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1957 from_ascii("before"))));
1958 label = contextmenu ?
1959 bformat(_("Insert Separated %1$s Below"),
1960 translateIfPossible(curlayout)):
1961 bformat(_("Separated %1$s Below"),
1962 translateIfPossible(curlayout));
1963 // We use command-alternatives here since this is how the binding is defined
1964 // (otherwise, the binding is not displayed in the menu)
1965 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1966 add(MenuItem(MenuItem::Command, toqstr(label),
1967 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1968 from_ascii("environment-split ; environment-split previous"))));
1970 else if (!prevlayout.empty()) {
1971 docstring const label = contextmenu ?
1972 bformat(_("Insert Separated %1$s Below"),
1973 translateIfPossible(prevlayout)) :
1974 bformat(_("Separated %1$s Below"),
1975 translateIfPossible(prevlayout));
1976 // We use command-alternatives here since this is how the binding is defined
1977 // (otherwise, the binding is not displayed in the menu)
1978 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1979 add(MenuItem(MenuItem::Command, toqstr(label),
1980 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1981 from_ascii("environment-split ; environment-split previous"))));
1983 if (!outerlayout.empty()) {
1986 label = (outerlayout == curlayout) ?
1987 bformat(_("Insert Separated Outer %1$s Below"),
1988 translateIfPossible(outerlayout)) :
1989 bformat(_("Insert Separated %1$s Below"),
1990 translateIfPossible(outerlayout));
1992 label = (outerlayout == curlayout) ?
1993 bformat(_("Separated Outer %1$s Below"),
1994 translateIfPossible(outerlayout)) :
1995 bformat(_("Separated %1$s Below"),
1996 translateIfPossible(outerlayout));
1998 add(MenuItem(MenuItem::Command, toqstr(label),
1999 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2000 from_ascii("outer"))));
2007 /////////////////////////////////////////////////////////////////////
2008 // Menu::Impl definition and implementation
2009 /////////////////////////////////////////////////////////////////////
2013 /// populates the menu or one of its submenu
2014 /// This is used as a recursive function
2015 void populate(QMenu * qMenu, MenuDefinition const & menu);
2017 /// Only needed for top level menus.
2018 MenuDefinition * top_level_menu;
2021 /// the name of this menu
2027 /// Get a MenuDefinition item label from the menu backend
2028 static QString label(MenuItem const & mi)
2030 QString label = mi.label();
2031 label.replace("&", "&&");
2033 QString shortcut = mi.shortcut();
2034 if (!shortcut.isEmpty()) {
2035 int pos = label.indexOf(shortcut);
2037 //label.insert(pos, 1, char_type('&'));
2038 label.replace(pos, 0, "&");
2041 QString const binding = mi.binding();
2042 if (!binding.isEmpty())
2043 label += '\t' + binding;
2048 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
2050 LYXERR(Debug::GUI, "populating menu " << menu.name());
2052 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
2055 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
2056 for (MenuItem const & m : menu)
2058 case MenuItem::Separator:
2059 qMenu->addSeparator();
2061 case MenuItem::Submenu: {
2062 QMenu * subMenu = qMenu->addMenu(label(m));
2063 populate(subMenu, m.submenu());
2064 subMenu->setEnabled(!subMenu->isEmpty());
2067 case MenuItem::Command:
2069 // FIXME: A previous comment assured that MenuItem::Command was the
2070 // only possible case in practice, but this is wrong. It would be
2071 // good to document which cases are actually treated here.
2072 qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2073 m.tooltip(), qMenu));
2078 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2079 class AlwaysMnemonicStyle : public QProxyStyle {
2081 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2082 QStyleHintReturn *returnData = 0) const
2084 if (hint == QStyle::SH_UnderlineShortcut)
2086 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2091 /////////////////////////////////////////////////////////////////////
2092 // Menu implementation
2093 /////////////////////////////////////////////////////////////////////
2095 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2096 : QMenu(gv), d(new Menu::Impl)
2098 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2100 setStyle(new AlwaysMnemonicStyle);
2104 d->top_level_menu = top_level? new MenuDefinition : 0;
2108 if (d->top_level_menu)
2109 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2115 delete d->top_level_menu;
2120 void Menu::updateView()
2122 guiApp->menus().updateMenu(this);
2128 QList<QAction *> items = actions();
2129 for (int i = 0; i != items.size(); ++i) {
2130 // QAction::menu() returns 0 if there's no submenu.
2131 delete items.at(i)->menu();
2137 /////////////////////////////////////////////////////////////////////
2138 // Menus::Impl definition and implementation
2139 /////////////////////////////////////////////////////////////////////
2141 struct Menus::Impl {
2143 bool hasMenu(QString const &) const;
2145 MenuDefinition & getMenu(QString const &);
2147 MenuDefinition const & getMenu(QString const &) const;
2149 /// Expands some special entries of the menu
2150 /** The entries with the following kind are expanded to a
2151 sequence of Command MenuItems: Lastfiles, Documents,
2152 ViewFormats, ExportFormats, UpdateFormats, Branches,
2153 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2154 EnvironmentSeparators
2156 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2157 BufferView const *) const;
2159 /// Initialize specific MACOS X menubar
2160 void macxMenuBarInit(QMenuBar * qmb);
2162 /// Mac special menu.
2163 /** This defines a menu whose entries list the FuncRequests
2164 that will be removed by expand() in other menus. This is
2165 used by the Qt/Mac code.
2167 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2168 such that the items will keep accessing the FuncRequests in
2169 the MenuDefinition. While Menus::Impl might be recreated,
2170 we keep mac_special_menu_ in memory by making it static.
2172 static MenuDefinition mac_special_menu_;
2177 MenuDefinition menubar_;
2179 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2181 /// name to menu for \c menu() method.
2186 MenuDefinition Menus::Impl::mac_special_menu_;
2190 Here is what the Qt documentation says about how a menubar is chosen:
2192 1) If the window has a QMenuBar then it is used. 2) If the window
2193 is a modal then its menubar is used. If no menubar is specified
2194 then a default menubar is used (as documented below) 3) If the
2195 window has no parent then the default menubar is used (as
2198 The above 3 steps are applied all the way up the parent window
2199 chain until one of the above are satisfied. If all else fails a
2200 default menubar will be created, the default menubar on Qt/Mac is
2201 an empty menubar, however you can create a different default
2202 menubar by creating a parentless QMenuBar, the first one created
2203 will thus be designated the default menubar, and will be used
2204 whenever a default menubar is needed.
2206 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2207 that this menubar will be used also when one of LyX' dialogs has
2210 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2212 /* Since Qt 4.2, the qt/mac menu code has special code for
2213 specifying the role of a menu entry. However, it does not
2214 work very well with our scheme of creating menus on demand,
2215 and therefore we need to put these entries in a special
2216 invisible menu. (JMarc)
2219 /* The entries of our special mac menu. If we add support for
2220 * special entries in Menus, we could imagine something
2222 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
2223 * and therefore avoid hardcoding. I am not sure it is worth
2224 * the hassle, though. (JMarc)
2226 struct MacMenuEntry {
2230 QAction::MenuRole role;
2233 static const MacMenuEntry entries[] = {
2234 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2235 QAction::AboutRole},
2236 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2237 QAction::PreferencesRole},
2238 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2239 /* This doesn't work with Cocoa. */
2240 {LFUN_RECONFIGURE, "", "Reconfigure",
2241 QAction::ApplicationSpecificRole},
2243 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2245 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2246 const bool first_call = mac_special_menu_.empty();
2248 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2249 // the special menu for Menus. Fill it up only once.
2251 for (size_t i = 0 ; i < num_entries ; ++i) {
2252 FuncRequest const func(entries[i].action,
2253 from_utf8(entries[i].arg));
2254 mac_special_menu_.add(MenuItem(MenuItem::Command,
2255 entries[i].label, func));
2259 // add the entries to a QMenu that will eventually be empty
2260 // and therefore invisible.
2261 QMenu * qMenu = qmb->addMenu("special");
2263 for (MenuItem const & m : mac_special_menu_) {
2264 Action * action = new Action(m.func(), QIcon(), m.label(),
2266 action->setMenuRole(entries[i].role);
2267 qMenu->addAction(action);
2273 void Menus::Impl::expand(MenuDefinition const & frommenu,
2274 MenuDefinition & tomenu, BufferView const * bv) const
2276 if (!tomenu.empty())
2279 for (MenuDefinition::const_iterator cit = frommenu.begin();
2280 cit != frommenu.end() ; ++cit) {
2281 Buffer const * buf = bv ? &bv->buffer() : 0;
2282 switch (cit->kind()) {
2283 case MenuItem::Lastfiles:
2284 tomenu.expandLastfiles();
2287 case MenuItem::Documents:
2288 tomenu.expandDocuments();
2291 case MenuItem::Bookmarks:
2292 tomenu.expandBookmarks();
2295 case MenuItem::ImportFormats:
2296 case MenuItem::ViewFormats:
2297 case MenuItem::UpdateFormats:
2298 case MenuItem::ExportFormats:
2299 tomenu.expandFormats(cit->kind(), buf);
2302 case MenuItem::ExportFormat: {
2305 string const format = buf->params().getDefaultOutputFormat();
2306 Format const * f = theFormats().getFormat(format);
2307 docstring const name = f ? f->prettyname() : from_utf8(format);
2308 docstring const label = bformat(_("Export [%1$s]|E"), name);
2309 MenuItem item(MenuItem::Command, toqstr(label),
2310 FuncRequest(LFUN_BUFFER_EXPORT));
2311 tomenu.addWithStatusCheck(item);
2315 case MenuItem::CharStyles:
2316 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2319 case MenuItem::Custom:
2320 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2323 case MenuItem::FloatListInsert:
2324 tomenu.expandFloatListInsert(buf);
2327 case MenuItem::FloatInsert:
2328 tomenu.expandFloatInsert(buf);
2331 case MenuItem::PasteRecent:
2332 tomenu.expandPasteRecent(buf);
2335 case MenuItem::Toolbars:
2336 tomenu.expandToolbars();
2339 case MenuItem::Branches:
2340 tomenu.expandBranches(buf);
2343 case MenuItem::Indices:
2344 tomenu.expandIndices(buf);
2347 case MenuItem::IndicesContext:
2348 tomenu.expandIndicesContext(buf);
2351 case MenuItem::IndicesLists:
2352 tomenu.expandIndices(buf, true);
2355 case MenuItem::IndicesListsContext:
2356 tomenu.expandIndicesContext(buf, true);
2359 case MenuItem::CiteStyles:
2360 tomenu.expandCiteStyles(bv);
2363 case MenuItem::InfoArguments:
2364 tomenu.expandInfoArguments(bv);
2369 tomenu.expandToc(buf);
2372 case MenuItem::GraphicsGroups:
2373 tomenu.expandGraphicsGroups(bv);
2376 case MenuItem::SpellingSuggestions:
2377 tomenu.expandSpellingSuggestions(bv);
2380 case MenuItem::LanguageSelector:
2381 tomenu.expandLanguageSelector(buf);
2384 case MenuItem::Arguments:
2385 tomenu.expandArguments(bv, false);
2388 case MenuItem::SwitchArguments:
2389 tomenu.expandArguments(bv, true);
2392 case MenuItem::Captions:
2393 tomenu.expandCaptions(buf, false);
2396 case MenuItem::SwitchCaptions:
2397 tomenu.expandCaptions(buf, true);
2400 case MenuItem::EnvironmentSeparators:
2401 tomenu.expandEnvironmentSeparators(bv);
2404 case MenuItem::EnvironmentSeparatorsContext:
2405 tomenu.expandEnvironmentSeparators(bv, true);
2408 case MenuItem::SwitchQuotes:
2409 tomenu.expandQuotes(bv);
2412 case MenuItem::Submenu: {
2413 MenuItem item(*cit);
2414 item.setSubmenu(MenuDefinition(cit->submenuname()));
2415 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2416 tomenu.addWithStatusCheck(item);
2420 case MenuItem::Info:
2421 case MenuItem::Help:
2422 case MenuItem::Separator:
2423 tomenu.addWithStatusCheck(*cit);
2426 case MenuItem::Command:
2427 if (!mac_special_menu_.hasFunc(*cit->func()))
2428 tomenu.addWithStatusCheck(*cit);
2432 // we do not want the menu to end with a separator
2433 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2434 tomenu.items_.pop_back();
2436 // Check whether the shortcuts are unique
2437 tomenu.checkShortcuts();
2441 bool Menus::Impl::hasMenu(QString const & name) const
2443 return find_if(menulist_.begin(), menulist_.end(),
2444 MenuNamesEqual(name)) != menulist_.end();
2448 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2450 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2451 MenuNamesEqual(name));
2452 if (cit == menulist_.end()) {
2453 LYXERR0("No submenu named " << name);
2454 LASSERT(false, { static const MenuDefinition m; return m; });
2460 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2462 iterator it = find_if(menulist_.begin(), menulist_.end(),
2463 MenuNamesEqual(name));
2464 if (it == menulist_.end()) {
2465 LYXERR0("No submenu named " << name);
2466 LASSERT(false, { static MenuDefinition m; return m; });
2472 /////////////////////////////////////////////////////////////////////
2476 /////////////////////////////////////////////////////////////////////
2478 Menus::Menus() : d(new Impl) {}
2494 void Menus::read(Lexer & lex)
2502 LexerKeyword menutags[] = {
2503 { "end", md_endmenuset },
2504 { "menu", md_menu },
2505 { "menubar", md_menubar }
2508 // consistency check
2509 if (compare_ascii_no_case(lex.getString(), "menuset"))
2510 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2512 lex.pushTable(menutags);
2513 lex.setContext("Menus::read");
2517 while (lex.isOK() && !quit) {
2518 switch (lex.lex()) {
2520 d->menubar_.read(lex);
2524 QString const name = toqstr(lex.getDocString());
2525 if (d->hasMenu(name))
2526 d->getMenu(name).read(lex);
2528 MenuDefinition menu(name);
2530 d->menulist_.push_back(menu);
2538 lex.printError("Unknown menu tag");
2546 bool Menus::searchMenu(FuncRequest const & func,
2547 docstring_list & names, BufferView const * bv) const
2549 MenuDefinition menu;
2550 d->expand(d->menubar_, menu, bv);
2551 return menu.searchMenu(func, names);
2555 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2559 // setup special mac specific menu items, but only do this
2560 // the first time a QMenuBar is created. Otherwise Qt will
2561 // create duplicate items in the application menu. It seems
2562 // that Qt does not remove them when the QMenubar is cleared.
2563 d->macxMenuBarInit(qmb);
2566 // Clear all menubar contents before filling it.
2568 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2569 d->macxMenuBarInit(qmb);
2573 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2575 if (d->menubar_.empty()) {
2576 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2577 << d->menubar_.name());
2580 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2582 MenuDefinition menu;
2583 BufferView * bv = 0;
2585 bv = view->currentBufferView();
2586 d->expand(d->menubar_, menu, bv);
2588 MenuDefinition::const_iterator m = menu.begin();
2589 MenuDefinition::const_iterator end = menu.end();
2591 for (; m != end; ++m) {
2593 if (m->kind() != MenuItem::Submenu) {
2594 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2598 LYXERR(Debug::GUI, "menu bar item " << m->label()
2599 << " is a submenu named " << m->submenuname());
2601 QString name = m->submenuname();
2602 if (!d->hasMenu(name)) {
2603 LYXERR(Debug::GUI, "\tERROR: " << name
2604 << " submenu has no menu!");
2608 Menu * menuptr = new Menu(view, m->submenuname(), true);
2609 menuptr->setTitle(label(*m));
2611 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2612 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2613 // so we create a temporary one here
2614 QAction * action = new QAction(menuptr);
2615 menuptr->addAction(action);
2618 qmb->addMenu(menuptr);
2620 d->name_map_[view][name] = menuptr;
2625 void Menus::updateMenu(Menu * qmenu)
2627 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2630 if (qmenu->d->name.isEmpty())
2633 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2634 MenuDefinition fromLyxMenu(qmenu->d->name);
2635 while (!identifier.empty()) {
2636 docstring menu_name;
2637 identifier = split(identifier, menu_name, ';');
2639 if (!d->hasMenu(toqstr(menu_name))) {
2640 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2645 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2646 //FIXME: 50 is a wild guess. We should take into account here
2647 //the expansion of menu items, disabled optional items etc.
2648 bool const in_sub_menu = !fromLyxMenu.empty()
2649 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2651 fromLyxMenu.catSub(menu_name);
2653 fromLyxMenu.cat(cat_menu);
2654 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2657 if (fromLyxMenu.empty()) {
2658 qmenu->addAction(qt_("No Action Defined!"));
2662 BufferView * bv = 0;
2664 bv = qmenu->d->view->currentBufferView();
2665 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2666 qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2670 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2672 LYXERR(Debug::GUI, "Context menu requested: " << name);
2673 Menu * menu = d->name_map_[&view].value(name, 0);
2674 if (!menu && !name.startsWith("context-")) {
2675 LYXERR0("requested context menu not found: " << name);
2679 menu = new Menu(&view, name, true, keyboard);
2680 d->name_map_[&view][name] = menu;
2684 } // namespace frontend
2687 #include "moc_Menus.cpp"