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 XML elements to
152 insert into the document */
154 /** This is the list of floats that we can
155 insert a list for. */
157 /** This is the list of floats that we can
160 /** This is the list of selections that can
165 /** Available branches in document */
167 /** Available indices in document */
169 /** Context menu for indices in document */
171 /** Available index lists in document */
173 /** Context menu for available indices lists in document */
175 /** Available citation styles for a given citation */
177 /** Available arguments for a given info inset */
179 /** Available graphics groups */
181 /// Words suggested by the spellchecker.
183 /** Used Languages */
185 /** This is the list of arguments available
186 for insertion into the current layout. */
188 /** This is the list of arguments available
189 in the InsetArgument context menu. */
191 /** This is the list of captions available
192 in the current layout. */
194 /** This is the list of captions available
195 in the InsetCaption context menu. */
197 /** Commands to separate environments. */
198 EnvironmentSeparators,
199 /** Commands to separate environments (context menu version). */
200 EnvironmentSeparatorsContext,
201 /** This is the list of quotation marks available */
205 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
208 QString const & label,
209 QString const & submenu = QString(),
210 QString const & tooltip = QString(),
211 bool optional = false)
212 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
213 submenuname_(submenu), tooltip_(tooltip), optional_(optional)
215 LATTEST(kind == Submenu || kind == Help || kind == Info);
219 QString const & label,
220 FuncRequest const & func,
221 QString const & tooltip = QString(),
222 bool optional = false,
223 FuncRequest::Origin origin = FuncRequest::MENU)
224 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
225 tooltip_(tooltip), optional_(optional)
227 func_->setOrigin(origin);
230 /// The label of a given menuitem
231 QString label() const
233 int const index = label_.lastIndexOf('|');
234 return index == -1 ? label_ : label_.left(index);
237 /// The keyboard shortcut (usually underlined in the entry)
238 QString shortcut() const
240 int const index = label_.lastIndexOf('|');
241 return index == -1 ? QString() : label_.mid(index + 1);
243 /// The complete label, with label and shortcut separated by a '|'
244 QString fulllabel() const { return label_; }
245 /// The kind of entry
246 Kind kind() const { return kind_; }
247 /// the action (if relevant)
248 shared_ptr<FuncRequest const> func() const { return func_; }
250 QString const & tooltip() const { return tooltip_; }
251 /// returns true if the entry should be omitted when disabled
252 bool optional() const { return optional_; }
253 /// returns the status of the lfun associated with this entry
254 FuncStatus const & status() const { return status_; }
255 /// returns the status of the lfun associated with this entry
256 FuncStatus & status() { return status_; }
257 /// returns the status of the lfun associated with this entry
258 void status(FuncStatus const & status) { status_ = status; }
260 ///returns the binding associated to this action.
261 QString binding() const
263 if (kind_ != Command)
265 // Get the keys bound to this action, but keep only the
267 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
268 if (!bindings.empty())
269 return toqstr(bindings.begin()->print(KeySequence::ForGui));
271 LYXERR(Debug::KBMAP, "No binding for "
272 << lyxaction.getActionName(func_->action())
273 << '(' << func_->argument() << ')');
277 /// the description of the submenu (if relevant)
278 QString const & submenuname() const { return submenuname_; }
279 /// set the description of the submenu
280 void submenuname(QString const & name) { submenuname_ = name; }
282 bool hasSubmenu() const { return !submenu_.isEmpty(); }
284 MenuDefinition const & submenu() const { return submenu_.at(0); }
285 MenuDefinition & submenu() { return submenu_[0]; }
287 void setSubmenu(MenuDefinition const & menu)
290 submenu_.append(menu);
299 shared_ptr<FuncRequest> func_;// non-null
301 QString submenuname_;
308 /// contains 0 or 1 item.
309 QList<MenuDefinition> submenu_;
313 class MenuDefinition {
316 typedef std::vector<MenuItem> ItemList;
318 typedef ItemList::const_iterator const_iterator;
320 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
325 QString const & name() const { return name_; }
327 bool empty() const { return items_.empty(); }
328 /// Clear the menu content.
329 void clear() { items_.clear(); }
331 size_t size() const { return items_.size(); }
333 const_iterator begin() const { return items_.begin(); }
335 const_iterator end() const { return items_.end(); }
337 void cat(MenuDefinition const & other);
339 void catSub(docstring const & name);
341 // search for func in this menu iteratively, and put menu
343 bool searchMenu(FuncRequest const & func, docstring_list & names)
346 bool hasFunc(FuncRequest const &) const;
347 /// Add the menu item unconditionally
348 void add(MenuItem const & item) { items_.push_back(item); }
349 /// Checks the associated FuncRequest status before adding the
351 void addWithStatusCheck(MenuItem const &);
352 // Check whether the menu shortcuts are unique
353 void checkShortcuts() const;
355 void expandLastfiles();
356 void expandDocuments();
357 void expandBookmarks();
358 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
359 void expandFloatListInsert(Buffer const * buf);
360 void expandFloatInsert(Buffer const * buf);
361 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
362 void expandTocSubmenu(std::string const & type, Toc const & toc_list);
363 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
364 void expandToc(Buffer const * buf);
365 void expandPasteRecent(Buffer const * buf);
366 void expandToolbars();
367 void expandBranches(Buffer const * buf);
368 void expandIndices(Buffer const * buf, bool listof = false);
369 void expandIndicesContext(Buffer const * buf, bool listof = false);
370 void expandCiteStyles(BufferView const *);
371 void expandInfoArguments(BufferView const *);
372 void expandGraphicsGroups(BufferView const *);
373 void expandSpellingSuggestions(BufferView const *);
374 void expandLanguageSelector(Buffer const * buf);
375 void expandArguments(BufferView const *, bool switcharg = false);
376 void expandCaptions(Buffer const * buf, bool switchcap = false);
377 void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
378 void expandQuotes(BufferView const *);
386 /// Helper for std::find_if
390 MenuNamesEqual(QString const & name) : name_(name) {}
391 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
398 typedef std::vector<MenuDefinition> MenuList;
400 typedef MenuList::const_iterator const_iterator;
402 typedef MenuList::iterator iterator;
404 /////////////////////////////////////////////////////////////////////
405 // MenuDefinition implementation
406 /////////////////////////////////////////////////////////////////////
408 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
412 case MenuItem::Command: {
413 FuncStatus status = lyx::getStatus(*i.func());
414 if (status.unknown() || (!status.enabled() && i.optional()))
417 items_.back().status(status);
421 case MenuItem::Submenu: {
422 bool enabled = false;
423 if (i.hasSubmenu()) {
424 for (const_iterator cit = i.submenu().begin();
425 cit != i.submenu().end(); ++cit) {
426 // Only these kind of items affect the status of the submenu
427 if ((cit->kind() == MenuItem::Command
428 || cit->kind() == MenuItem::Submenu
429 || cit->kind() == MenuItem::Help)
430 && cit->status().enabled()) {
436 if (enabled || !i.optional()) {
438 items_.back().status().setEnabled(enabled);
443 case MenuItem::Separator:
444 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
454 void MenuDefinition::read(Lexer & lex)
472 md_indiceslistscontext,
487 md_spellingsuggestions,
494 md_env_separatorscontext,
498 LexerKeyword menutags[] = {
499 { "arguments", md_arguments },
500 { "bookmarks", md_bookmarks },
501 { "branches", md_branches },
502 { "captions", md_captions },
503 { "charstyles", md_charstyles },
504 { "citestyles", md_citestyles },
505 { "custom", md_custom },
506 { "documents", md_documents },
507 { "elements", md_elements },
508 { "end", md_endmenu },
509 { "environmentseparators", md_env_separators },
510 { "environmentseparatorscontext", md_env_separatorscontext },
511 { "exportformat", md_exportformat },
512 { "exportformats", md_exportformats },
513 { "floatinsert", md_floatinsert },
514 { "floatlistinsert", md_floatlistinsert },
515 { "graphicsgroups", md_graphicsgroups },
516 { "importformats", md_importformats },
517 { "indices", md_indices },
518 { "indicescontext", md_indicescontext },
519 { "indiceslists", md_indiceslists },
520 { "indiceslistscontext", md_indiceslistscontext },
521 { "infoarguments", md_infoarguments },
523 { "languageselector", md_languageselector },
524 { "lastfiles", md_lastfiles },
525 { "optitem", md_optitem },
526 { "optsubmenu", md_optsubmenu },
527 { "pasterecent", md_pasterecent },
528 { "separator", md_separator },
529 { "spellingsuggestions", md_spellingsuggestions },
530 { "submenu", md_submenu },
531 { "switcharguments", md_switcharguments },
532 { "switchcaptions", md_switchcaptions },
533 { "switchquotes", md_switchquotes },
535 { "toolbars", md_toolbars },
536 { "updateformats", md_updateformats },
537 { "viewformats", md_viewformats }
540 lex.pushTable(menutags);
541 lex.setContext("MenuDefinition::read: ");
544 while (lex.isOK() && md_type != md_endmenu) {
545 switch (md_type = lex.lex()) {
549 docstring const name = translateIfPossible(lex.getDocString());
551 string const command = lex.getString();
552 FuncRequest func = lyxaction.lookupFunc(command);
553 FuncRequest::Origin origin = FuncRequest::MENU;
554 if (name_.startsWith("context-toc-"))
555 origin = FuncRequest::TOC;
556 bool const optional = (md_type == md_optitem);
557 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
562 add(MenuItem(MenuItem::Separator));
566 add(MenuItem(MenuItem::Lastfiles));
570 add(MenuItem(MenuItem::CharStyles));
574 add(MenuItem(MenuItem::Custom));
578 add(MenuItem(MenuItem::Elements));
582 add(MenuItem(MenuItem::Documents));
586 add(MenuItem(MenuItem::Bookmarks));
590 add(MenuItem(MenuItem::Toc));
594 add(MenuItem(MenuItem::ViewFormats));
597 case md_updateformats:
598 add(MenuItem(MenuItem::UpdateFormats));
601 case md_exportformats:
602 add(MenuItem(MenuItem::ExportFormats));
605 case md_exportformat:
606 add(MenuItem(MenuItem::ExportFormat));
609 case md_importformats:
610 add(MenuItem(MenuItem::ImportFormats));
613 case md_floatlistinsert:
614 add(MenuItem(MenuItem::FloatListInsert));
618 add(MenuItem(MenuItem::FloatInsert));
622 add(MenuItem(MenuItem::PasteRecent));
626 add(MenuItem(MenuItem::Toolbars));
630 add(MenuItem(MenuItem::Branches));
634 add(MenuItem(MenuItem::CiteStyles));
637 case md_infoarguments:
638 add(MenuItem(MenuItem::InfoArguments));
642 case md_graphicsgroups:
643 add(MenuItem(MenuItem::GraphicsGroups));
646 case md_spellingsuggestions:
647 add(MenuItem(MenuItem::SpellingSuggestions));
650 case md_languageselector:
651 add(MenuItem(MenuItem::LanguageSelector));
655 add(MenuItem(MenuItem::Indices));
658 case md_indicescontext:
659 add(MenuItem(MenuItem::IndicesContext));
662 case md_indiceslists:
663 add(MenuItem(MenuItem::IndicesLists));
666 case md_indiceslistscontext:
667 add(MenuItem(MenuItem::IndicesListsContext));
671 add(MenuItem(MenuItem::Arguments));
674 case md_switcharguments:
675 add(MenuItem(MenuItem::SwitchArguments));
679 add(MenuItem(MenuItem::Captions));
682 case md_switchcaptions:
683 add(MenuItem(MenuItem::SwitchCaptions));
686 case md_env_separators:
687 add(MenuItem(MenuItem::EnvironmentSeparators));
690 case md_env_separatorscontext:
691 add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
694 case md_switchquotes:
695 add(MenuItem(MenuItem::SwitchQuotes));
701 docstring const mlabel = translateIfPossible(lex.getDocString());
703 docstring const mname = lex.getDocString();
704 bool const optional = (md_type == md_optsubmenu);
705 add(MenuItem(MenuItem::Submenu,
706 toqstr(mlabel), toqstr(mname), QString(), optional));
714 lex.printError("Unknown menu tag");
722 bool MenuDefinition::hasFunc(FuncRequest const & func) const
724 for (const_iterator it = begin(), et = end(); it != et; ++it)
725 if (*it->func() == func)
731 void MenuDefinition::catSub(docstring const & name)
733 add(MenuItem(MenuItem::Submenu,
734 qt_("More...|M"), toqstr(name), QString(), false));
737 void MenuDefinition::cat(MenuDefinition const & other)
739 const_iterator et = other.end();
740 for (const_iterator it = other.begin(); it != et; ++it)
745 void MenuDefinition::checkShortcuts() const
747 // This is a quadratic algorithm, but we do not care because
748 // menus are short enough
749 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
750 QString shortcut = it1->shortcut();
751 if (shortcut.isEmpty())
753 if (!it1->label().contains(shortcut))
754 LYXERR0("Menu warning: menu entry \""
756 << "\" does not contain shortcut `"
757 << shortcut << "'.");
758 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
759 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
760 LYXERR0("Menu warning: menu entries "
761 << '"' << it1->fulllabel()
762 << "\" and \"" << it2->fulllabel()
763 << "\" share the same shortcut.");
770 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
772 const_iterator m = begin();
773 const_iterator m_end = end();
774 for (; m != m_end; ++m) {
775 if (m->kind() == MenuItem::Command && *m->func() == func) {
776 names.push_back(qstring_to_ucs4(m->label()));
779 if (m->kind() == MenuItem::Submenu) {
780 names.push_back(qstring_to_ucs4(m->label()));
781 if (!m->hasSubmenu()) {
782 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
783 << m->label() << " name=" << m->submenuname());
787 if (m->submenu().searchMenu(func, names))
796 QString limitStringLength(docstring const & str)
798 size_t const max_item_length = 45;
799 docstring ret = str.substr(0, max_item_length + 1);
800 support::truncateWithEllipsis(ret, max_item_length);
805 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
810 graphics::getGraphicsGroups(bv->buffer(), grp);
814 set<string>::const_iterator it = grp.begin();
815 set<string>::const_iterator end = grp.end();
816 add(MenuItem(MenuItem::Command, qt_("No Group"),
817 FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
818 for (; it != end; ++it) {
819 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
820 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
825 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
829 Cursor const & cur = bv->cursor();
833 docstring_list suggestions;
834 Paragraph const & par = cur.paragraph();
835 pos_type from = cur.pos();
837 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
839 case SpellChecker::UNKNOWN_WORD:
840 if (lyxrc.spellcheck_continuously) {
841 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
842 docstring const & selection = cur.selectionAsString(false);
843 if (!cur.selection() || selection == wl.word()) {
845 size_t m = 10; // first submenu index
846 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
847 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
848 for (; i != suggestions.size(); ++i) {
849 docstring const & suggestion = suggestions[i];
850 LYXERR(Debug::GUI, suggestion);
851 MenuItem w(MenuItem::Command, toqstr(suggestion),
852 FuncRequest(LFUN_WORD_REPLACE,
853 replace2string(suggestion, selection,
854 true, // case sensitive
858 false))); // find next
862 item.submenu().add(w);
867 add(MenuItem(MenuItem::Separator));
868 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
869 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
870 FuncRequest(LFUN_SPELLING_ADD, arg)));
871 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
872 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
876 case SpellChecker::LEARNED_WORD: {
877 LYXERR(Debug::GUI, "Learned Word.");
878 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
879 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
880 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
883 case SpellChecker::NO_DICTIONARY:
884 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
886 case SpellChecker::WORD_OK:
887 case SpellChecker::COMPOUND_WORD:
888 case SpellChecker::ROOT_FOUND:
889 case SpellChecker::IGNORED_WORD:
894 struct sortLanguageByName {
895 bool operator()(const Language * a, const Language * b) const {
896 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
900 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
905 std::set<Language const *> languages_buffer =
906 buf->masterBuffer()->getLanguages();
908 if (languages_buffer.size() < 2)
911 std::set<Language const *, sortLanguageByName> langs;
913 std::set<Language const *>::const_iterator const beg =
914 languages_buffer.begin();
915 for (std::set<Language const *>::const_iterator cit = beg;
916 cit != languages_buffer.end(); ++cit) {
920 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
921 item.setSubmenu(MenuDefinition(qt_("Language")));
922 QString morelangs = qt_("More Languages ...|M");
923 QStringList accelerators;
924 if (morelangs.contains('|'))
925 accelerators.append(morelangs.section('|', -1));
926 std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
927 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
928 cit != langs.end(); ++cit) {
929 QString label = qt_((*cit)->display());
930 // try to add an accelerator
931 bool success = false;
932 // try capitals first
933 for (int i = 0; i < label.size(); ++i) {
934 QChar const ch = label[i];
937 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
938 label = label + toqstr("|") + ch;
939 accelerators.append(ch);
944 // if all capitals are taken, try the rest
946 for (int i = 0; i < label.size(); ++i) {
947 if (label[i].isSpace())
949 QString const ch = QString(label[i]);
950 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
951 label = label + toqstr("|") + ch;
952 accelerators.append(ch);
957 MenuItem w(MenuItem::Command, label,
958 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
959 item.submenu().addWithStatusCheck(w);
961 item.submenu().add(MenuItem(MenuItem::Separator));
962 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
963 FuncRequest(LFUN_DIALOG_SHOW, "character")));
968 void MenuDefinition::expandLastfiles()
970 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
971 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
975 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
976 string const file = lfit->absFileName();
977 QString const short_path = toqstr(makeDisplayPath(file, 30));
978 QString const long_path = toqstr(makeDisplayPath(file));
981 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
983 label = QString("%1. %2").arg(ii).arg(short_path);
984 add(MenuItem(MenuItem::Command, label,
985 FuncRequest(LFUN_FILE_OPEN, file), long_path));
990 void MenuDefinition::expandDocuments()
992 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
993 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
995 Buffer * first = theBufferList().first();
997 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
1003 if (!guiApp->currentView())
1005 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
1008 Buffer const & b = wa->bufferView().buffer();
1009 QString label = toqstr(b.fileName().displayName(20));
1012 if (b.notifiesExternalModification())
1013 label += QChar(0x26a0);
1015 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1016 add(MenuItem(MenuItem::Command, label,
1017 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1024 // We cannot use a for loop as the buffer list cycles.
1026 if (!(guiApp->currentView()
1027 && guiApp->currentView()->workArea(*b))) {
1028 QString label = toqstr(b->fileName().displayName(20));
1031 if (b->notifiesExternalModification())
1032 label += QChar(0x26a0);
1034 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1035 item.submenu().add(MenuItem(MenuItem::Command, label,
1036 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1039 b = theBufferList().next(b);
1040 } while (b != first);
1042 if (!item.submenu().empty())
1047 void MenuDefinition::expandBookmarks()
1049 lyx::BookmarksSection const & bm = theSession().bookmarks();
1052 for (size_t i = 1; i <= bm.size(); ++i) {
1053 if (bm.isValid(i)) {
1054 string const file = bm.bookmark(i).filename.absFileName();
1055 QString const label = QString("%1. %2|%3").arg(i)
1056 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1057 add(MenuItem(MenuItem::Command, label,
1058 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1063 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1067 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1069 if (!buf && kind != MenuItem::ImportFormats)
1073 FuncCode action = LFUN_NOACTION;
1076 case MenuItem::ImportFormats:
1077 formats = theConverters().importableFormats();
1078 action = LFUN_BUFFER_IMPORT;
1080 case MenuItem::ViewFormats:
1081 formats = buf->params().exportableFormats(true);
1082 action = LFUN_BUFFER_VIEW;
1084 case MenuItem::UpdateFormats:
1085 formats = buf->params().exportableFormats(true);
1086 action = LFUN_BUFFER_UPDATE;
1088 case MenuItem::ExportFormats:
1089 formats = buf->params().exportableFormats(false);
1090 action = LFUN_BUFFER_EXPORT;
1097 bool const view_update = (kind == MenuItem::ViewFormats
1098 || kind == MenuItem::UpdateFormats);
1102 smenue = (kind == MenuItem::ViewFormats
1103 ? qt_("View (Other Formats)|F")
1104 : qt_("Update (Other Formats)|p"));
1105 MenuItem item(MenuItem::Submenu, smenue);
1106 item.setSubmenu(MenuDefinition(smenue));
1108 for (Format const * f : formats) {
1112 docstring lab = f->prettyname();
1113 docstring const scut = from_utf8(f->shortcut());
1114 docstring const tmplab = lab;
1117 lab += char_type('|') + scut;
1118 docstring const lab_i18n = translateIfPossible(lab);
1119 docstring const shortcut = split(lab_i18n, lab, '|');
1121 bool const untranslated = (lab == lab_i18n);
1122 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1125 case MenuItem::ImportFormats:
1126 label += from_ascii("...");
1128 case MenuItem::ViewFormats:
1129 case MenuItem::UpdateFormats:
1130 if (f->name() == buf->params().getDefaultOutputFormat()) {
1131 docstring lbl = (kind == MenuItem::ViewFormats
1132 ? bformat(_("View [%1$s]|V"), label)
1133 : bformat(_("Update [%1$s]|U"), label));
1134 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1138 case MenuItem::ExportFormats:
1139 if (!f->inExportMenu())
1143 // we already asserted earlier in this case
1147 if (!shortcut.empty())
1148 label += '|' + shortcut;
1151 // note that at this point, we know that buf is not null
1153 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1154 toqstr(label), FuncRequest(action, f->name())));
1157 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1158 FuncRequest(action, f->name())));
1160 add(MenuItem(MenuItem::Command, toqstr(label),
1161 FuncRequest(action, f->name())));
1169 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1174 FloatList const & floats = buf->params().documentClass().floats();
1175 FloatList::const_iterator cit = floats.begin();
1176 FloatList::const_iterator end = floats.end();
1178 for (; cit != end; ++cit) {
1179 if (!cit->second.usesFloatPkg()) {
1180 // Different floats could declare the same ListCommand. We only
1181 // want it on the list once, though.
1182 string const & list_cmd = cit->second.listCommand();
1183 if (list_cmd.empty())
1184 // we do not know how to generate such a list
1186 // This form of insert returns an iterator pointing to the newly
1187 // inserted element OR the existing element with that value, and
1188 // a bool indicating whether we inserted a new element. So we can
1189 // see if one is there and insert it if not all at once.
1190 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1194 string const & list_name = cit->second.listName();
1195 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1196 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1201 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1206 FloatList const & floats = buf->params().documentClass().floats();
1207 FloatList::const_iterator cit = floats.begin();
1208 FloatList::const_iterator end = floats.end();
1209 for (; cit != end; ++cit) {
1211 QString const label = qt_(cit->second.name());
1212 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1213 FuncRequest(LFUN_FLOAT_INSERT,
1214 cit->second.floattype())));
1219 void MenuDefinition::expandFlexInsert(
1220 Buffer const * buf, InsetLayout::InsetLyXType type)
1225 TextClass::InsetLayouts const & insetLayouts =
1226 buf->params().documentClass().insetLayouts();
1227 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1228 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1229 for (; cit != end; ++cit) {
1230 if (cit->second.lyxtype() == type) {
1231 if (!cit->second.obsoleted_by().empty())
1233 docstring name = cit->first;
1234 // we remove the "Flex:" prefix, if it is present
1235 if (prefixIs(name, from_ascii("Flex:")))
1236 name = name.substr(5);
1237 docstring const label = (cit->second.menustring().empty()) ?
1239 : cit->second.menustring();
1240 addWithStatusCheck(MenuItem(MenuItem::Command,
1241 toqstr(translateIfPossible(label)),
1242 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(name))));
1245 // FIXME This is a little clunky.
1246 if (items_.empty() && type == InsetLayout::CUSTOM && !buf->hasReadonlyFlag())
1247 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1251 // Threshold before we stop displaying sub-items alongside items
1252 // (for display purposes). Ideally this should fit on a screen.
1253 size_t const max_number_of_items = 30;
1254 // Size limit for the menu. This is for performance purposes,
1255 // because qt already displays a scrollable menu when necessary.
1256 // Ideally this should be the menu size from which scrollable
1257 // menus become unpractical.
1258 size_t const menu_size_limit = 80;
1260 void MenuDefinition::expandToc2(Toc const & toc_list,
1261 size_t from, size_t to, int depth,
1264 int shortcut_count = 0;
1266 // check whether depth is smaller than the smallest depth in toc.
1267 int min_depth = 1000;
1268 for (size_t i = from; i < to; ++i)
1269 min_depth = min(min_depth, toc_list[i].depth());
1270 if (min_depth > depth)
1273 if (to - from <= max_number_of_items) {
1274 for (size_t i = from; i < to; ++i) {
1275 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1276 label += limitStringLength(toc_list[i].asString());
1277 if (toc_list[i].depth() == depth) {
1279 if (shortcut_count < 9) {
1280 if (label.contains(QString::number(shortcut_count + 1)))
1281 label += QString::number(++shortcut_count);
1284 add(MenuItem(MenuItem::Command, label,
1285 FuncRequest(toc_list[i].action())));
1286 // separator after the menu heading
1287 if (toc_list[i].depth() < depth)
1288 add(MenuItem(MenuItem::Separator));
1294 size_t new_pos = pos + 1;
1295 while (new_pos < to && toc_list[new_pos].depth() > depth)
1298 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1299 label += limitStringLength(toc_list[pos].asString());
1300 if (toc_list[pos].depth() == depth) {
1302 if (shortcut_count < 9) {
1303 if (label.contains(QString::number(shortcut_count + 1)))
1304 label += QString::number(++shortcut_count);
1307 if (size >= menu_size_limit) {
1308 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1309 add(MenuItem(MenuItem::Command, "...", f));
1312 if (new_pos == pos + 1) {
1313 add(MenuItem(MenuItem::Command,
1314 label, FuncRequest(toc_list[pos].action())));
1317 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1318 MenuItem item(MenuItem::Submenu, label);
1319 item.setSubmenu(sub);
1329 void MenuDefinition::expandToc(Buffer const * buf)
1331 // To make things very cleanly, we would have to pass buf to
1332 // all MenuItem constructors and to expandToc2. However, we
1333 // know that all the entries in a TOC will be have status_ ==
1334 // OK, so we avoid this unnecessary overhead (JMarc)
1336 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1339 // Add an entry for the master doc if this is a child doc
1340 Buffer const * const master = buf->masterBuffer();
1341 if (buf != master) {
1342 ParIterator const pit = par_iterator_begin(master->inset());
1343 string const arg = convert<string>(pit->id());
1344 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1345 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1348 MenuDefinition other_lists;
1349 // In the navigation menu, only add tocs from this document
1350 TocBackend const & backend = buf->tocBackend();
1351 TocList const & toc_list = backend.tocs();
1352 for (pair<string, shared_ptr<Toc>> const & toc : toc_list) {
1353 // Handle table of contents later
1354 if (toc.first == "tableofcontents" || toc.second->empty())
1356 MenuDefinition submenu;
1357 submenu.expandTocSubmenu(toc.first, *toc.second);
1358 docstring const toc_name = backend.outlinerName(toc.first);
1359 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1360 item.setSubmenu(submenu);
1361 // deserves to be in the main menu?
1362 if (!TocBackend::isOther(toc.first))
1365 other_lists.add(item);
1367 if (!other_lists.empty()) {
1368 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1369 item.setSubmenu(other_lists);
1372 // Handle normal TOC
1373 add(MenuItem(MenuItem::Separator));
1374 TocList::const_iterator cit = toc_list.find("tableofcontents");
1375 if (cit == toc_list.end())
1376 LYXERR(Debug::GUI, "No table of contents.");
1378 if (!cit->second->empty())
1379 expandToc2(*cit->second, 0, cit->second->size(), 0,
1382 add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1387 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1389 // "Open outliner..." entry
1390 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1391 add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1392 add(MenuItem(MenuItem::Separator));
1394 expandToc2(toc, 0, toc.size(), 0, type);
1398 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1400 docstring_list const sel = cap::availableSelections(buf);
1402 docstring_list::const_iterator cit = sel.begin();
1403 docstring_list::const_iterator end = sel.end();
1405 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1406 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1407 FuncRequest(LFUN_PASTE, convert<string>(index))));
1412 void MenuDefinition::expandToolbars()
1414 MenuDefinition other_lists;
1415 // extracts the toolbars from the backend
1416 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1417 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1418 for (; cit != end; ++cit) {
1419 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1420 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1421 if (guiApp->toolbars().isMainToolbar(cit->name))
1424 other_lists.add(item);
1427 if (!other_lists.empty()) {
1428 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1429 item.setSubmenu(other_lists);
1435 void MenuDefinition::expandBranches(Buffer const * buf)
1437 if (!buf || buf->hasReadonlyFlag())
1440 BranchList const & child_list = buf->params().branchlist();
1441 set<docstring> brset;
1443 for (auto const & b : child_list) {
1444 docstring const & bname = b.branch();
1445 // NUM. Branch Name + "|", which triggers an empty shortcut in
1446 // case that character should be in the branch name.
1447 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1448 // Add NUM as a keyboard shortcut if it's a single digit
1450 label += convert<docstring>(ii);
1452 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1453 FuncRequest(LFUN_BRANCH_INSERT, bname)));
1455 brset.insert(bname);
1459 set<Buffer const *> bufset;
1460 Buffer const * nextbuf = buf->parent();
1461 MenuDefinition master_branches;
1464 // recursive includes are a bad idea, but let's not crash
1466 if (bufset.count(nextbuf))
1469 for (auto const & b : nextbuf->params().branchlist()) {
1470 docstring const & bname = b.branch();
1471 // do not add it if we've already seen it
1472 if (brset.count(bname))
1475 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1477 label += convert<docstring>(ii);
1479 master_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1480 toqstr(label), FuncRequest(LFUN_BRANCH_INSERT, bname)));
1482 bufset.insert(nextbuf);
1483 brset.insert(bname);
1487 nextbuf = nextbuf->parent();
1490 if (!master_branches.empty()) {
1491 MenuItem item(MenuItem::Submenu, qt_("Master Documents"));
1492 item.setSubmenu(master_branches);
1498 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1503 BufferParams const & params = buf->masterBuffer()->params();
1504 if (!params.use_indices) {
1506 addWithStatusCheck(MenuItem(MenuItem::Command,
1507 qt_("Index List|I"),
1508 FuncRequest(LFUN_INDEX_PRINT,
1509 from_ascii("idx"))));
1511 addWithStatusCheck(MenuItem(MenuItem::Command,
1512 qt_("Index Entry|d"),
1513 FuncRequest(LFUN_INDEX_INSERT,
1514 from_ascii("idx"))));
1518 if (params.indiceslist().empty())
1521 IndicesList::const_iterator cit = params.indiceslist().begin();
1522 IndicesList::const_iterator end = params.indiceslist().end();
1524 for (int ii = 1; cit != end; ++cit, ++ii) {
1526 docstring const label =
1527 bformat(_("Index: %1$s"), cit->index());
1528 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1529 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1531 docstring const label =
1532 bformat(_("Index Entry (%1$s)"), cit->index());
1533 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1534 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1540 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1545 BufferParams const & params = buf->masterBuffer()->params();
1546 if (!params.use_indices || params.indiceslist().empty())
1549 IndicesList::const_iterator cit = params.indiceslist().begin();
1550 IndicesList::const_iterator end = params.indiceslist().end();
1552 for (int ii = 1; cit != end; ++cit, ++ii) {
1554 InsetCommandParams p(INDEX_PRINT_CODE);
1555 p["type"] = cit->shortcut();
1556 string const data = InsetCommand::params2string(p);
1557 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1558 FuncRequest(LFUN_INSET_MODIFY, data)));
1560 docstring const label =
1561 bformat(_("Index Entry (%1$s)"), cit->index());
1562 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1563 FuncRequest(LFUN_INSET_MODIFY,
1564 from_ascii("changetype ") + cit->shortcut())));
1570 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1575 Inset const * inset = bv->cursor().nextInset();
1576 if (!inset || inset->lyxCode() != CITE_CODE) {
1577 add(MenuItem(MenuItem::Command,
1578 qt_("No Citation in Scope!"),
1579 FuncRequest(LFUN_NOACTION)));
1582 InsetCitation const * citinset =
1583 static_cast<InsetCitation const *>(inset);
1585 Buffer const * buf = &bv->buffer();
1586 BufferParams const & bp = buf->masterParams();
1587 string const cmd = citinset->params().getCmdName();
1589 docstring const & key = citinset->getParam("key");
1591 add(MenuItem(MenuItem::Command,
1592 qt_("No citations selected!"),
1593 FuncRequest(LFUN_NOACTION)));
1597 bool const force = isUpperCase(cmd[0]);
1598 bool const star = suffixIs(cmd, '*');
1600 vector<docstring> const keys = getVectorFromString(key);
1602 vector<CitationStyle> const citeStyleList = bp.citeStyles();
1604 CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1605 bool const qualified = cs.hasQualifiedList
1607 || !citinset->getParam("pretextlist").empty()
1608 || !citinset->getParam("posttextlist").empty());
1609 std::map<docstring, docstring> pres =
1610 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1611 std::map<docstring, docstring> posts =
1612 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1615 ci.textBefore = citinset->getParam("before");
1616 ci.textAfter = citinset->getParam("after");
1617 ci.forceUpperCase = force;
1619 ci.context = CiteItem::Dialog;
1621 ci.isQualified = qualified;
1623 ci.posttexts = posts;
1624 BiblioInfo::CiteStringMap citeStrings =
1625 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1627 BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1628 BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1630 for (int ii = 1; cit != end; ++cit, ++ii) {
1631 docstring label = cit->second;
1632 CitationStyle ccs = citeStyleList[ii - 1];
1633 ccs.forceUpperCase &= force;
1634 ccs.hasStarredVersion &= star;
1635 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1636 FuncRequest(LFUN_INSET_MODIFY,
1637 "changetype " + from_utf8(citationStyleToString(ccs)))));
1640 if (cs.hasStarredVersion) {
1641 docstring starred = _("All authors|h");
1642 // Check if we have a custom string/tooltip for the starred version
1643 if (!cs.stardesc.empty()) {
1645 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1647 starred = translateIfPossible(from_utf8(val));
1648 // Transform qt-style accelerators to menu-style
1649 int const amps = count_char(starred, '&');
1652 starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1653 size_t nn = starred.find('&');
1654 char_type accel = char_type();
1655 if (nn != docstring::npos && nn < starred.size() - 1)
1656 accel = starred[nn + 1];
1657 starred = subst(starred, from_ascii("&"), from_ascii(""));
1659 starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1660 if (accel != char_type())
1661 starred = starred + '|' + accel;
1664 add(MenuItem(MenuItem::Separator));
1665 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1666 FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1669 if (cs.forceUpperCase) {
1670 if (!cs.hasStarredVersion)
1671 add(MenuItem(MenuItem::Separator));
1672 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1673 FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1678 void MenuDefinition::expandInfoArguments(BufferView const * bv)
1683 Inset const * inset = bv->cursor().nextInset();
1684 if (!inset || inset->lyxCode() != INFO_CODE) {
1685 add(MenuItem(MenuItem::Command,
1686 qt_("No Text Field in Scope!"),
1687 FuncRequest(LFUN_NOACTION)));
1690 InsetInfo const * iinset = static_cast<InsetInfo const *>(inset);
1692 string const type = iinset->params().infoType();
1693 vector<pair<string,docstring>> const args =
1694 iinset->params().getArguments(&bv->buffer(), type);
1696 // Don't generate a menu for big lists (such as lfuns and rcs)
1697 if (args.size() > 15)
1700 for (auto const & p : args) {
1701 if (p.first == "invalid")
1704 if (p.first == "custom") {
1705 add(MenuItem(MenuItem::Command, qt_("Custom..."),
1706 FuncRequest(LFUN_INSET_SETTINGS, "info")));
1709 docstring label = p.second;
1710 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1711 FuncRequest(LFUN_INSET_MODIFY, type + " " + p.first)));
1717 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1722 if (!bv->cursor().inTexted())
1725 Inset const * inset = &bv->cursor().inset();
1726 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1727 if (inset && args.empty())
1728 args = inset->getLayout().args();
1729 if (args.empty() || (switcharg && args.size() == 1))
1731 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1732 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1733 for (; lait != laend; ++lait) {
1734 Layout::latexarg arg = (*lait).second;
1735 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1736 QString item = toqstr(translateIfPossible(str));
1738 add(MenuItem(MenuItem::Command, item,
1739 FuncRequest(LFUN_INSET_MODIFY,
1740 from_ascii("changetype ")
1741 + from_ascii((*lait).first))));
1743 add(MenuItem(MenuItem::Command, item,
1744 FuncRequest(LFUN_ARGUMENT_INSERT,
1745 from_ascii((*lait).first))));
1750 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1755 DocumentClass const & dc = buf->params().documentClass();
1756 vector< pair<docstring, FuncRequest> > caps;
1757 for (pair<docstring, InsetLayout> const & il : dc.insetLayouts()) {
1759 docstring const type = split(il.first, instype, ':');
1760 if (instype == from_ascii("Caption")) {
1761 // skip forbidden caption types
1762 FuncRequest const cmd = switchcap
1763 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1764 : FuncRequest(LFUN_CAPTION_INSERT, type);
1765 if (getStatus(cmd).enabled())
1766 caps.push_back(make_pair(type, cmd));
1770 if (caps.empty() || (switchcap && caps.size() == 1))
1772 if (caps.size() == 1) {
1773 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1777 MenuDefinition captions;
1778 for (pair<docstring, FuncRequest> const & cap : caps) {
1779 docstring const type = cap.first;
1780 docstring const trtype = translateIfPossible(type);
1781 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1783 add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1785 captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1787 if (!captions.empty()) {
1788 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1789 item.setSubmenu(captions);
1795 void MenuDefinition::expandQuotes(BufferView const * bv)
1800 if (!bv->cursor().inTexted())
1803 Inset const * inset = bv->cursor().nextInset();
1804 if (!inset || inset->lyxCode() != QUOTE_CODE) {
1805 add(MenuItem(MenuItem::Command,
1806 qt_("No Quote in Scope!"),
1807 FuncRequest(LFUN_NOACTION)));
1810 InsetQuotes const * qinset =
1811 static_cast<InsetQuotes const *>(inset);
1813 map<string, docstring> styles = quoteparams.getTypes();
1814 string const qtype = qinset->getType();
1816 map<string, docstring>::const_iterator qq = styles.begin();
1817 map<string, docstring>::const_iterator end = styles.end();
1821 BufferParams const & bp = bv->buffer().masterBuffer()->params();
1823 // The global setting
1824 InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1825 char const globalqsc = quoteparams.getStyleChar(globalqs);
1827 // The current language's default
1828 InsetQuotesParams::QuoteStyle langdefqs =
1829 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1830 char const langqs = quoteparams.getStyleChar(langdefqs);
1832 bool main_global_qs = false;
1833 bool main_langdef_qs = false;
1834 bool main_dynamic_qs = false;
1835 docstring const subcmd = from_ascii("changetype ");
1836 docstring const wildcards = from_ascii("..");
1838 // First the top level menu (all glyphs of the current style) ...
1839 // Begin with dynamic (if they are current style),
1840 if (qtype[0] == 'x') {
1841 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1842 docstring desc = bformat(_("%1$s (dynamic)"),
1843 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1844 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1845 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1846 desc = bformat(_("%1$s (dynamic)"),
1847 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1848 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1849 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1850 desc = bformat(_("%1$s (dynamic)"),
1851 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1852 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1853 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1854 desc = bformat(_("%1$s (dynamic)"),
1855 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1856 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1857 main_dynamic_qs = true;
1859 // now traverse through the static styles ...
1860 for (; qq != end; ++qq) {
1861 docstring const style = from_ascii(qq->first);
1862 bool langdef = (style[0] == langqs);
1863 bool globaldef = (style[0] == globalqsc);
1865 if (prefixIs(style, qtype[0])) {
1866 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1867 docstring const desc = quoteparams.getShortGuiLabel(style);
1868 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1869 main_global_qs = globaldef;
1870 main_langdef_qs = langdef;
1872 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1873 docstring const desc =
1874 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1875 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1876 aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1880 add(MenuItem(MenuItem::Separator));
1882 bool display_static = false;
1883 // ... then potentially items to reset to the defaults and to dynamic style ...
1884 if (!main_dynamic_qs && globalqsc != 'x') {
1885 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1886 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1887 quoteparams.getGuiLabel(globalqs));
1888 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1889 display_static = true;
1891 if (!main_global_qs && langdefqs != globalqs) {
1892 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1893 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1894 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1895 quoteparams.getGuiLabel(globalqs), variant);
1896 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1898 if (!main_langdef_qs) {
1899 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1900 docstring const desc = (main_dynamic_qs || display_static)
1901 ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1902 quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1903 : bformat(_("Reset to language default (%1$s)|l"),
1904 quoteparams.getGuiLabel(langdefqs));
1905 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1908 add(MenuItem(MenuItem::Separator));
1910 // ... and a subitem with the rest
1911 MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1912 item.setSubmenu(aqs);
1917 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1922 Text const * text = bv->cursor().text();
1923 // no paragraphs and no separators exist in math
1927 pit_type pit = bv->cursor().selBegin().pit();
1928 Paragraph const & par = text->getPar(pit);
1929 docstring const curlayout = par.layout().name();
1930 docstring outerlayout;
1931 docstring prevlayout;
1932 depth_type current_depth = par.params().depth();
1933 // check if we have an environment in our scope
1934 Paragraph cpar = par;
1939 cpar = text->getPar(pit);
1940 if (cpar.layout().isEnvironment() && prevlayout.empty()
1941 && cpar.params().depth() <= current_depth)
1942 prevlayout = cpar.layout().name();
1943 if (cpar.params().depth() < current_depth
1944 && cpar.layout().isEnvironment()) {
1945 outerlayout = cpar.layout().name();
1946 current_depth = cpar.params().depth();
1948 if (cpar.params().depth() == 0)
1951 if (par.layout().isEnvironment()) {
1952 docstring label = contextmenu ?
1953 bformat(_("Insert Separated %1$s Above"),
1954 translateIfPossible(curlayout)) :
1955 bformat(_("Separated %1$s Above"),
1956 translateIfPossible(curlayout));
1957 add(MenuItem(MenuItem::Command, toqstr(label),
1958 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1959 from_ascii("before"))));
1960 label = contextmenu ?
1961 bformat(_("Insert Separated %1$s Below"),
1962 translateIfPossible(curlayout)):
1963 bformat(_("Separated %1$s Below"),
1964 translateIfPossible(curlayout));
1965 // We use command-alternatives here since this is how the binding is defined
1966 // (otherwise, the binding is not displayed in the menu)
1967 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1968 add(MenuItem(MenuItem::Command, toqstr(label),
1969 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1970 from_ascii("environment-split ; environment-split previous"))));
1972 else if (!prevlayout.empty()) {
1973 docstring const label = contextmenu ?
1974 bformat(_("Insert Separated %1$s Below"),
1975 translateIfPossible(prevlayout)) :
1976 bformat(_("Separated %1$s Below"),
1977 translateIfPossible(prevlayout));
1978 // We use command-alternatives here since this is how the binding is defined
1979 // (otherwise, the binding is not displayed in the menu)
1980 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1981 add(MenuItem(MenuItem::Command, toqstr(label),
1982 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1983 from_ascii("environment-split ; environment-split previous"))));
1985 if (!outerlayout.empty()) {
1988 label = (outerlayout == curlayout) ?
1989 bformat(_("Insert Separated Outer %1$s Below"),
1990 translateIfPossible(outerlayout)) :
1991 bformat(_("Insert Separated %1$s Below"),
1992 translateIfPossible(outerlayout));
1994 label = (outerlayout == curlayout) ?
1995 bformat(_("Separated Outer %1$s Below"),
1996 translateIfPossible(outerlayout)) :
1997 bformat(_("Separated %1$s Below"),
1998 translateIfPossible(outerlayout));
2000 add(MenuItem(MenuItem::Command, toqstr(label),
2001 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2002 from_ascii("outer"))));
2009 /////////////////////////////////////////////////////////////////////
2010 // Menu::Impl definition and implementation
2011 /////////////////////////////////////////////////////////////////////
2015 /// populates the menu or one of its submenu
2016 /// This is used as a recursive function
2017 void populate(QMenu * qMenu, MenuDefinition const & menu);
2019 /// Only needed for top level menus.
2020 MenuDefinition * top_level_menu;
2023 /// the name of this menu
2029 /// Get a MenuDefinition item label from the menu backend
2030 static QString label(MenuItem const & mi)
2032 QString label = mi.label();
2033 label.replace("&", "&&");
2035 QString shortcut = mi.shortcut();
2036 if (!shortcut.isEmpty()) {
2037 int pos = label.indexOf(shortcut);
2039 //label.insert(pos, 1, char_type('&'));
2040 label.replace(pos, 0, "&");
2043 QString const binding = mi.binding();
2044 if (!binding.isEmpty())
2045 label += '\t' + binding;
2050 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
2052 LYXERR(Debug::GUI, "populating menu " << menu.name());
2054 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
2057 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
2058 for (MenuItem const & m : menu)
2060 case MenuItem::Separator:
2061 qMenu->addSeparator();
2063 case MenuItem::Submenu: {
2064 QMenu * subMenu = qMenu->addMenu(label(m));
2065 populate(subMenu, m.submenu());
2066 subMenu->setEnabled(!subMenu->isEmpty());
2069 case MenuItem::Command:
2071 // FIXME: A previous comment assured that MenuItem::Command was the
2072 // only possible case in practice, but this is wrong. It would be
2073 // good to document which cases are actually treated here.
2074 qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2075 m.tooltip(), qMenu));
2080 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2081 class AlwaysMnemonicStyle : public QProxyStyle {
2083 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2084 QStyleHintReturn *returnData = 0) const
2086 if (hint == QStyle::SH_UnderlineShortcut)
2088 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2093 /////////////////////////////////////////////////////////////////////
2094 // Menu implementation
2095 /////////////////////////////////////////////////////////////////////
2097 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2098 : QMenu(gv), d(new Menu::Impl)
2100 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2102 setStyle(new AlwaysMnemonicStyle);
2106 d->top_level_menu = top_level? new MenuDefinition : 0;
2110 if (d->top_level_menu)
2111 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2117 delete d->top_level_menu;
2122 void Menu::updateView()
2124 guiApp->menus().updateMenu(this);
2130 QList<QAction *> items = actions();
2131 for (int i = 0; i != items.size(); ++i) {
2132 // QAction::menu() returns 0 if there's no submenu.
2133 delete items.at(i)->menu();
2139 /////////////////////////////////////////////////////////////////////
2140 // Menus::Impl definition and implementation
2141 /////////////////////////////////////////////////////////////////////
2143 struct Menus::Impl {
2145 bool hasMenu(QString const &) const;
2147 MenuDefinition & getMenu(QString const &);
2149 MenuDefinition const & getMenu(QString const &) const;
2151 /// Expands some special entries of the menu
2152 /** The entries with the following kind are expanded to a
2153 sequence of Command MenuItems: Lastfiles, Documents,
2154 ViewFormats, ExportFormats, UpdateFormats, Branches,
2155 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2156 EnvironmentSeparators
2158 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2159 BufferView const *) const;
2161 /// Initialize specific MACOS X menubar
2162 void macxMenuBarInit(QMenuBar * qmb);
2164 /// Mac special menu.
2165 /** This defines a menu whose entries list the FuncRequests
2166 that will be removed by expand() in other menus. This is
2167 used by the Qt/Mac code.
2169 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2170 such that the items will keep accessing the FuncRequests in
2171 the MenuDefinition. While Menus::Impl might be recreated,
2172 we keep mac_special_menu_ in memory by making it static.
2174 static MenuDefinition mac_special_menu_;
2179 MenuDefinition menubar_;
2181 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2183 /// name to menu for \c menu() method.
2188 MenuDefinition Menus::Impl::mac_special_menu_;
2192 Here is what the Qt documentation says about how a menubar is chosen:
2194 1) If the window has a QMenuBar then it is used. 2) If the window
2195 is a modal then its menubar is used. If no menubar is specified
2196 then a default menubar is used (as documented below) 3) If the
2197 window has no parent then the default menubar is used (as
2200 The above 3 steps are applied all the way up the parent window
2201 chain until one of the above are satisifed. If all else fails a
2202 default menubar will be created, the default menubar on Qt/Mac is
2203 an empty menubar, however you can create a different default
2204 menubar by creating a parentless QMenuBar, the first one created
2205 will thus be designated the default menubar, and will be used
2206 whenever a default menubar is needed.
2208 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2209 that this menubar will be used also when one of LyX' dialogs has
2212 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2214 /* Since Qt 4.2, the qt/mac menu code has special code for
2215 specifying the role of a menu entry. However, it does not
2216 work very well with our scheme of creating menus on demand,
2217 and therefore we need to put these entries in a special
2218 invisible menu. (JMarc)
2221 /* The entries of our special mac menu. If we add support for
2222 * special entries in Menus, we could imagine something
2224 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
2225 * and therefore avoid hardcoding. I am not sure it is worth
2226 * the hassle, though. (JMarc)
2228 struct MacMenuEntry {
2232 QAction::MenuRole role;
2235 static const MacMenuEntry entries[] = {
2236 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2237 QAction::AboutRole},
2238 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2239 QAction::PreferencesRole},
2240 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2241 /* This doesn't work with Cocoa. */
2242 {LFUN_RECONFIGURE, "", "Reconfigure",
2243 QAction::ApplicationSpecificRole},
2245 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2247 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2248 const bool first_call = mac_special_menu_.empty();
2250 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2251 // the special menu for Menus. Fill it up only once.
2253 for (size_t i = 0 ; i < num_entries ; ++i) {
2254 FuncRequest const func(entries[i].action,
2255 from_utf8(entries[i].arg));
2256 mac_special_menu_.add(MenuItem(MenuItem::Command,
2257 entries[i].label, func));
2261 // add the entries to a QMenu that will eventually be empty
2262 // and therefore invisible.
2263 QMenu * qMenu = qmb->addMenu("special");
2265 for (MenuItem const & m : mac_special_menu_) {
2266 Action * action = new Action(m.func(), QIcon(), m.label(),
2268 action->setMenuRole(entries[i].role);
2269 qMenu->addAction(action);
2275 void Menus::Impl::expand(MenuDefinition const & frommenu,
2276 MenuDefinition & tomenu, BufferView const * bv) const
2278 if (!tomenu.empty())
2281 for (MenuDefinition::const_iterator cit = frommenu.begin();
2282 cit != frommenu.end() ; ++cit) {
2283 Buffer const * buf = bv ? &bv->buffer() : 0;
2284 switch (cit->kind()) {
2285 case MenuItem::Lastfiles:
2286 tomenu.expandLastfiles();
2289 case MenuItem::Documents:
2290 tomenu.expandDocuments();
2293 case MenuItem::Bookmarks:
2294 tomenu.expandBookmarks();
2297 case MenuItem::ImportFormats:
2298 case MenuItem::ViewFormats:
2299 case MenuItem::UpdateFormats:
2300 case MenuItem::ExportFormats:
2301 tomenu.expandFormats(cit->kind(), buf);
2304 case MenuItem::ExportFormat: {
2307 string const format = buf->params().getDefaultOutputFormat();
2308 Format const * f = theFormats().getFormat(format);
2309 docstring const name = f ? f->prettyname() : from_utf8(format);
2310 docstring const label = bformat(_("Export [%1$s]|E"), name);
2311 MenuItem item(MenuItem::Command, toqstr(label),
2312 FuncRequest(LFUN_BUFFER_EXPORT));
2313 tomenu.addWithStatusCheck(item);
2317 case MenuItem::CharStyles:
2318 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2321 case MenuItem::Custom:
2322 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2325 case MenuItem::Elements:
2326 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2329 case MenuItem::FloatListInsert:
2330 tomenu.expandFloatListInsert(buf);
2333 case MenuItem::FloatInsert:
2334 tomenu.expandFloatInsert(buf);
2337 case MenuItem::PasteRecent:
2338 tomenu.expandPasteRecent(buf);
2341 case MenuItem::Toolbars:
2342 tomenu.expandToolbars();
2345 case MenuItem::Branches:
2346 tomenu.expandBranches(buf);
2349 case MenuItem::Indices:
2350 tomenu.expandIndices(buf);
2353 case MenuItem::IndicesContext:
2354 tomenu.expandIndicesContext(buf);
2357 case MenuItem::IndicesLists:
2358 tomenu.expandIndices(buf, true);
2361 case MenuItem::IndicesListsContext:
2362 tomenu.expandIndicesContext(buf, true);
2365 case MenuItem::CiteStyles:
2366 tomenu.expandCiteStyles(bv);
2369 case MenuItem::InfoArguments:
2370 tomenu.expandInfoArguments(bv);
2375 tomenu.expandToc(buf);
2378 case MenuItem::GraphicsGroups:
2379 tomenu.expandGraphicsGroups(bv);
2382 case MenuItem::SpellingSuggestions:
2383 tomenu.expandSpellingSuggestions(bv);
2386 case MenuItem::LanguageSelector:
2387 tomenu.expandLanguageSelector(buf);
2390 case MenuItem::Arguments:
2391 tomenu.expandArguments(bv, false);
2394 case MenuItem::SwitchArguments:
2395 tomenu.expandArguments(bv, true);
2398 case MenuItem::Captions:
2399 tomenu.expandCaptions(buf, false);
2402 case MenuItem::SwitchCaptions:
2403 tomenu.expandCaptions(buf, true);
2406 case MenuItem::EnvironmentSeparators:
2407 tomenu.expandEnvironmentSeparators(bv);
2410 case MenuItem::EnvironmentSeparatorsContext:
2411 tomenu.expandEnvironmentSeparators(bv, true);
2414 case MenuItem::SwitchQuotes:
2415 tomenu.expandQuotes(bv);
2418 case MenuItem::Submenu: {
2419 MenuItem item(*cit);
2420 item.setSubmenu(MenuDefinition(cit->submenuname()));
2421 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2422 tomenu.addWithStatusCheck(item);
2426 case MenuItem::Info:
2427 case MenuItem::Help:
2428 case MenuItem::Separator:
2429 tomenu.addWithStatusCheck(*cit);
2432 case MenuItem::Command:
2433 if (!mac_special_menu_.hasFunc(*cit->func()))
2434 tomenu.addWithStatusCheck(*cit);
2438 // we do not want the menu to end with a separator
2439 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2440 tomenu.items_.pop_back();
2442 // Check whether the shortcuts are unique
2443 tomenu.checkShortcuts();
2447 bool Menus::Impl::hasMenu(QString const & name) const
2449 return find_if(menulist_.begin(), menulist_.end(),
2450 MenuNamesEqual(name)) != menulist_.end();
2454 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2456 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2457 MenuNamesEqual(name));
2458 if (cit == menulist_.end()) {
2459 LYXERR0("No submenu named " << name);
2460 LASSERT(false, { static const MenuDefinition m; return m; });
2466 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2468 iterator it = find_if(menulist_.begin(), menulist_.end(),
2469 MenuNamesEqual(name));
2470 if (it == menulist_.end()) {
2471 LYXERR0("No submenu named " << name);
2472 LASSERT(false, { static MenuDefinition m; return m; });
2478 /////////////////////////////////////////////////////////////////////
2482 /////////////////////////////////////////////////////////////////////
2484 Menus::Menus() : d(new Impl) {}
2500 void Menus::read(Lexer & lex)
2508 LexerKeyword menutags[] = {
2509 { "end", md_endmenuset },
2510 { "menu", md_menu },
2511 { "menubar", md_menubar }
2514 // consistency check
2515 if (compare_ascii_no_case(lex.getString(), "menuset"))
2516 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2518 lex.pushTable(menutags);
2519 lex.setContext("Menus::read");
2523 while (lex.isOK() && !quit) {
2524 switch (lex.lex()) {
2526 d->menubar_.read(lex);
2530 QString const name = toqstr(lex.getDocString());
2531 if (d->hasMenu(name))
2532 d->getMenu(name).read(lex);
2534 MenuDefinition menu(name);
2536 d->menulist_.push_back(menu);
2544 lex.printError("Unknown menu tag");
2552 bool Menus::searchMenu(FuncRequest const & func,
2553 docstring_list & names, BufferView const * bv) const
2555 MenuDefinition menu;
2556 d->expand(d->menubar_, menu, bv);
2557 return menu.searchMenu(func, names);
2561 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2565 // setup special mac specific menu items, but only do this
2566 // the first time a QMenuBar is created. Otherwise Qt will
2567 // create duplicate items in the application menu. It seems
2568 // that Qt does not remove them when the QMenubar is cleared.
2569 d->macxMenuBarInit(qmb);
2572 // Clear all menubar contents before filling it.
2574 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2575 d->macxMenuBarInit(qmb);
2579 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2581 if (d->menubar_.empty()) {
2582 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2583 << d->menubar_.name());
2586 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2588 MenuDefinition menu;
2589 BufferView * bv = 0;
2591 bv = view->currentBufferView();
2592 d->expand(d->menubar_, menu, bv);
2594 MenuDefinition::const_iterator m = menu.begin();
2595 MenuDefinition::const_iterator end = menu.end();
2597 for (; m != end; ++m) {
2599 if (m->kind() != MenuItem::Submenu) {
2600 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2604 LYXERR(Debug::GUI, "menu bar item " << m->label()
2605 << " is a submenu named " << m->submenuname());
2607 QString name = m->submenuname();
2608 if (!d->hasMenu(name)) {
2609 LYXERR(Debug::GUI, "\tERROR: " << name
2610 << " submenu has no menu!");
2614 Menu * menuptr = new Menu(view, m->submenuname(), true);
2615 menuptr->setTitle(label(*m));
2617 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2618 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2619 // so we create a temporary one here
2620 QAction * action = new QAction(menuptr);
2621 menuptr->addAction(action);
2624 qmb->addMenu(menuptr);
2626 d->name_map_[view][name] = menuptr;
2631 void Menus::updateMenu(Menu * qmenu)
2633 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2636 if (qmenu->d->name.isEmpty())
2639 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2640 MenuDefinition fromLyxMenu(qmenu->d->name);
2641 while (!identifier.empty()) {
2642 docstring menu_name;
2643 identifier = split(identifier, menu_name, ';');
2645 if (!d->hasMenu(toqstr(menu_name))) {
2646 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2651 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2652 //FIXME: 50 is a wild guess. We should take into account here
2653 //the expansion of menu items, disabled optional items etc.
2654 bool const in_sub_menu = !fromLyxMenu.empty()
2655 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2657 fromLyxMenu.catSub(menu_name);
2659 fromLyxMenu.cat(cat_menu);
2660 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2663 if (fromLyxMenu.empty()) {
2664 qmenu->addAction(qt_("No Action Defined!"));
2668 BufferView * bv = 0;
2670 bv = qmenu->d->view->currentBufferView();
2671 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2672 qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2676 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2678 LYXERR(Debug::GUI, "Context menu requested: " << name);
2679 Menu * menu = d->name_map_[&view].value(name, 0);
2680 if (!menu && !name.startsWith("context-")) {
2681 LYXERR0("requested context menu not found: " << name);
2685 menu = new Menu(&view, name, true, keyboard);
2686 d->name_map_[&view][name] = menu;
2690 } // namespace frontend
2693 #include "moc_Menus.cpp"