3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
14 * \author Martin Vermeer
15 * \author Jürgen Vigna
17 * Full author contact details are available in file CREDITS.
24 #include "BranchList.h"
26 #include "buffer_funcs.h"
27 #include "bufferlist.h"
28 #include "bufferparams.h"
29 #include "BufferView.h"
32 #include "dispatchresult.h"
36 #include "funcrequest.h"
40 #include "iterators.h"
44 #include "LyXAction.h"
48 #include "lyxserver.h"
50 #include "paragraph.h"
51 #include "ParagraphParameters.h"
54 #include "insets/insetbox.h"
55 #include "insets/insetbranch.h"
56 #include "insets/insetcommand.h"
57 #include "insets/insetert.h"
58 #include "insets/insetexternal.h"
59 #include "insets/insetfloat.h"
60 #include "insets/insetgraphics.h"
61 #include "insets/insetnote.h"
62 #include "insets/insettabular.h"
63 #include "insets/insetvspace.h"
64 #include "insets/insetwrap.h"
66 #include "frontends/Alert.h"
67 #include "frontends/Dialogs.h"
68 #include "frontends/FileDialog.h"
69 #include "frontends/lyx_gui.h"
70 #include "frontends/LyXKeySym.h"
71 #include "frontends/LyXView.h"
72 #include "frontends/Menubar.h"
73 #include "frontends/Toolbar.h"
75 #include "support/FileInfo.h"
76 #include "support/filetools.h"
77 #include "support/forkedcontr.h"
78 #include "support/globbing.h"
79 #include "support/path.h"
80 #include "support/path_defines.h"
81 #include "support/tostr.h"
82 #include "support/std_sstream.h"
83 #include "support/os.h"
85 using bv_funcs::changeDepth;
86 using bv_funcs::currentState;
87 using bv_funcs::DEC_DEPTH;
88 using bv_funcs::freefont2string;
89 using bv_funcs::INC_DEPTH;
91 using lyx::support::AddName;
92 using lyx::support::AddPath;
93 using lyx::support::bformat;
94 using lyx::support::ChangeExtension;
95 using lyx::support::FileFilterList;
96 using lyx::support::FileInfo;
97 using lyx::support::FileSearch;
98 using lyx::support::ForkedcallsController;
99 using lyx::support::i18nLibFileSearch;
100 using lyx::support::IsDirWriteable;
101 using lyx::support::IsFileReadable;
102 using lyx::support::isStrInt;
103 using lyx::support::MakeAbsPath;
104 using lyx::support::MakeDisplayPath;
105 using lyx::support::Path;
106 using lyx::support::rtrim;
107 using lyx::support::split;
108 using lyx::support::strToInt;
109 using lyx::support::strToUnsignedInt;
110 using lyx::support::system_lyxdir;
111 using lyx::support::token;
112 using lyx::support::trim;
113 using lyx::support::user_lyxdir;
114 using lyx::support::prefixIs;
115 using lyx::support::os::getTmpDir;
118 using std::make_pair;
121 using std::istringstream;
124 extern BufferList bufferlist;
125 extern LyXServer * lyxserver;
126 extern bool selection_possible;
128 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
131 extern tex_accent_struct get_accent(kb_action action);
134 LyXFunc::LyXFunc(LyXView * lv)
137 keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
138 cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
139 meta_fake_bit(key_modifier::none)
144 void LyXFunc::handleKeyFunc(kb_action action)
146 char c = encoded_last_key;
148 if (keyseq.length()) {
152 owner->getIntl().getTransManager()
153 .deadkey(c, get_accent(action).accent, view()->getLyXText());
154 // Need to clear, in case the minibuffer calls these
157 // copied verbatim from do_accent_char
158 view()->cursor().resetAnchor();
163 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
165 lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
167 // Do nothing if we have nothing (JMarc)
168 if (!keysym->isOK()) {
169 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
174 if (keysym->isModifier()) {
175 lyxerr[Debug::KEY] << "isModifier true" << endl;
179 Encoding const * encoding = view()->getEncoding();
181 encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
183 // Do a one-deep top-level lookup for
184 // cancel and meta-fake keys. RVDK_PATCH_5
185 cancel_meta_seq.reset();
187 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
188 lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
190 // When not cancel or meta-fake, do the normal lookup.
191 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
192 // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
193 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
194 // remove Caps Lock and Mod2 as a modifiers
195 func = keyseq.addkey(keysym, (state | meta_fake_bit));
196 lyxerr[Debug::KEY] << "action now set to ["
197 << func.action << ']' << endl;
200 // Dont remove this unless you know what you are doing.
201 meta_fake_bit = key_modifier::none;
203 // can this happen now ?
204 if (func.action == LFUN_NOACTION) {
205 func = FuncRequest(LFUN_PREFIX);
208 if (lyxerr.debugging(Debug::KEY)) {
209 lyxerr << "Key [action="
210 << func.action << "]["
211 << keyseq.print() << ']'
215 // already here we know if it any point in going further
216 // why not return already here if action == -1 and
217 // num_bytes == 0? (Lgb)
219 if (keyseq.length() > 1) {
220 owner->message(keyseq.print());
224 // Maybe user can only reach the key via holding down shift.
225 // Let's see. But only if shift is the only modifier
226 if (func.action == LFUN_UNKNOWN_ACTION &&
227 state == key_modifier::shift) {
228 lyxerr[Debug::KEY] << "Trying without shift" << endl;
229 func = keyseq.addkey(keysym, key_modifier::none);
230 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
233 if (func.action == LFUN_UNKNOWN_ACTION) {
234 // Hmm, we didn't match any of the keysequences. See
235 // if it's normal insertable text not already covered
237 if (keysym->isText() && keyseq.length() == 1) {
238 lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
239 func = FuncRequest(LFUN_SELFINSERT);
241 lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
242 owner->message(_("Unknown function."));
247 if (func.action == LFUN_SELFINSERT) {
248 if (encoded_last_key != 0) {
249 string arg(1, encoded_last_key);
250 dispatch(FuncRequest(LFUN_SELFINSERT, arg));
252 << "SelfInsert arg[`" << arg << "']" << endl;
260 FuncStatus LyXFunc::getStatus(FuncRequest const & ev) const
263 Buffer * buf = owner->buffer();
264 LCursor & cur = view()->cursor();
266 if (ev.action == LFUN_NOACTION) {
267 setStatusMessage(N_("Nothing to do"));
273 case LFUN_UNKNOWN_ACTION:
274 #ifndef HAVE_LIBAIKSAURUS
275 case LFUN_THESAURUS_ENTRY:
281 flag |= lyx_gui::getStatus(ev);
284 if (flag.unknown()) {
285 setStatusMessage(N_("Unknown action"));
289 // the default error message if we disable the command
290 setStatusMessage(N_("Command disabled"));
292 // Check whether we need a buffer
293 if (!lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)) {
294 // Yes we need a buffer, do we have one?
297 // Can we use a readonly buffer?
298 if (buf->isReadonly() &&
299 !lyxaction.funcHasFlag(ev.action,
300 LyXAction::ReadOnly)) {
302 setStatusMessage(N_("Document is read-only"));
307 setStatusMessage(N_("Command not allowed with"
308 "out any document open"));
314 UpdatableInset * tli = cur.inset() ? cur.inset()->asUpdatableInset() : 0;
315 InsetTabular * tab = cur.innerInsetTabular();
317 // I would really like to avoid having this switch and rather try to
318 // encode this in the function itself.
319 bool disable = false;
322 disable = ev.argument != "custom"
323 && !Exporter::IsExportable(*buf, ev.argument);
326 disable = buf->undostack().empty();
329 disable = buf->redostack().empty();
333 if (tab && tab->hasSelection())
336 disable = cur.inTexted() && !cur.selection();
340 disable = !buf->isLatex() || lyxrc.chktex_command == "none";
344 disable = !Exporter::IsExportable(*buf, "program");
347 case LFUN_LAYOUT_TABULAR:
348 disable = !cur.innerInsetTabular();
352 disable = !changeDepthAllowed(view(), view()->getLyXText(), DEC_DEPTH);
355 case LFUN_DEPTH_PLUS:
356 disable = !changeDepthAllowed(view(), view()->getLyXText(), INC_DEPTH);
360 case LFUN_LAYOUT_PARAGRAPH:
361 disable = cur.inset()
362 && cur.inset()->forceDefaultParagraphs(cur.inset());
365 case LFUN_INSET_OPTARG:
366 disable = cur.inMathed()
367 || cur.paragraph().layout()->optionalargs == 0;
370 case LFUN_TABULAR_FEATURE:
372 if (cur.inMathed()) {
373 // FIXME: check temporarily disabled
375 char align = mathcursor::valign();
380 if (ev.argument.empty()) {
384 if (!contains("tcb", ev.argument[0])) {
388 flag.setOnOff(ev.argument[0] == align);
392 char align = mathcursor::halign();
397 if (ev.argument.empty()) {
401 if (!contains("lcr", ev.argument[0])) {
405 flag.setOnOff(ev.argument[0] == align);
407 disable = !mathcursor::halign();
413 //ret.disabled(true);
414 InsetTabular * tab = cur.innerInsetTabular();
416 ret = tab->getStatus(ev.argument);
423 static InsetTabular inset(*buf, 1, 1);
425 FuncStatus ret = inset.getStatus(ev.argument);
426 if (ret.onoff(true) || ret.onoff(false))
427 flag.setOnOff(false);
432 case LFUN_VC_REGISTER:
433 disable = buf->lyxvc().inUse();
435 case LFUN_VC_CHECKIN:
436 disable = !buf->lyxvc().inUse() || buf->isReadonly();
438 case LFUN_VC_CHECKOUT:
439 disable = !buf->lyxvc().inUse() || !buf->isReadonly();
443 disable = !buf->lyxvc().inUse();
445 case LFUN_MENURELOAD:
446 disable = buf->isUnnamed() || buf->isClean();
448 case LFUN_BOOKMARK_GOTO:
450 isSavedPosition(strToUnsignedInt(ev.argument));
453 case LFUN_MERGE_CHANGES:
454 case LFUN_ACCEPT_CHANGE:
455 case LFUN_REJECT_CHANGE:
456 case LFUN_ACCEPT_ALL_CHANGES:
457 case LFUN_REJECT_ALL_CHANGES:
458 disable = !buf->params().tracking_changes;
461 case LFUN_INSET_SETTINGS: {
465 UpdatableInset * inset = cur.inset()->asUpdatableInset();
469 // jump back to owner if an InsetText, so
470 // we get back to the InsetTabular or whatever
471 if (inset->lyxCode() == InsetOld::TEXT_CODE)
472 inset = inset->owner();
474 InsetOld::Code code = inset->lyxCode();
476 case InsetOld::TABULAR_CODE:
477 disable = ev.argument != "tabular";
479 case InsetOld::ERT_CODE:
480 disable = ev.argument != "ert";
482 case InsetOld::FLOAT_CODE:
483 disable = ev.argument != "float";
485 case InsetOld::WRAP_CODE:
486 disable = ev.argument != "wrap";
488 case InsetOld::NOTE_CODE:
489 disable = ev.argument != "note";
491 case InsetOld::BRANCH_CODE:
492 disable = ev.argument != "branch";
494 case InsetOld::BOX_CODE:
495 disable = ev.argument != "box";
503 case LFUN_MATH_MUTATE:
505 //flag.setOnOff(mathcursor::formula()->hullType() == ev.argument);
506 flag.setOnOff(false);
511 // we just need to be in math mode to enable that
513 case LFUN_MATH_SPACE:
514 case LFUN_MATH_LIMITS:
515 case LFUN_MATH_NONUMBER:
516 case LFUN_MATH_NUMBER:
517 case LFUN_MATH_EXTERN:
518 disable = cur.inTexted();
521 case LFUN_DIALOG_SHOW: {
522 string const name = ev.getArg(0);
524 disable = !(name == "aboutlyx" ||
527 name == "preferences" ||
532 if (name == "print") {
533 disable = !Exporter::IsExportable(*buf, "dvi") ||
534 lyxrc.print_command == "none";
535 } else if (name == "character") {
536 InsetBase * inset = cur.inset();
537 disable = inset && inset->lyxCode() == InsetOld::ERT_CODE;
538 } else if (name == "vclog") {
539 disable = !buf->lyxvc().inUse();
540 } else if (name == "latexlog") {
541 disable = !IsFileReadable(buf->getLogName().second);
550 // the functions which insert insets
551 InsetOld::Code code = InsetOld::NO_CODE;
553 case LFUN_DIALOG_SHOW_NEW_INSET:
554 if (ev.argument == "bibitem")
555 code = InsetOld::BIBITEM_CODE;
556 else if (ev.argument == "bibtex")
557 code = InsetOld::BIBTEX_CODE;
558 else if (ev.argument == "box")
559 code = InsetOld::BOX_CODE;
560 else if (ev.argument == "branch")
561 code = InsetOld::BRANCH_CODE;
562 else if (ev.argument == "citation")
563 code = InsetOld::CITE_CODE;
564 else if (ev.argument == "ert")
565 code = InsetOld::ERT_CODE;
566 else if (ev.argument == "external")
567 code = InsetOld::EXTERNAL_CODE;
568 else if (ev.argument == "float")
569 code = InsetOld::FLOAT_CODE;
570 else if (ev.argument == "graphics")
571 code = InsetOld::GRAPHICS_CODE;
572 else if (ev.argument == "include")
573 code = InsetOld::INCLUDE_CODE;
574 else if (ev.argument == "index")
575 code = InsetOld::INDEX_CODE;
576 else if (ev.argument == "label")
577 code = InsetOld::LABEL_CODE;
578 else if (ev.argument == "note")
579 code = InsetOld::NOTE_CODE;
580 else if (ev.argument == "ref")
581 code = InsetOld::REF_CODE;
582 else if (ev.argument == "toc")
583 code = InsetOld::TOC_CODE;
584 else if (ev.argument == "url")
585 code = InsetOld::URL_CODE;
586 else if (ev.argument == "vspace")
587 code = InsetOld::VSPACE_CODE;
588 else if (ev.argument == "wrap")
589 code = InsetOld::WRAP_CODE;
593 code = InsetOld::ERT_CODE;
595 case LFUN_INSET_FOOTNOTE:
596 code = InsetOld::FOOT_CODE;
598 case LFUN_TABULAR_INSERT:
599 code = InsetOld::TABULAR_CODE;
601 case LFUN_INSET_MARGINAL:
602 code = InsetOld::MARGIN_CODE;
604 case LFUN_INSET_FLOAT:
605 case LFUN_INSET_WIDE_FLOAT:
606 code = InsetOld::FLOAT_CODE;
608 case LFUN_INSET_WRAP:
609 code = InsetOld::WRAP_CODE;
611 case LFUN_FLOAT_LIST:
612 code = InsetOld::FLOAT_LIST_CODE;
615 case LFUN_INSET_LIST:
616 code = InsetOld::LIST_CODE;
618 case LFUN_INSET_THEOREM:
619 code = InsetOld::THEOREM_CODE;
622 case LFUN_INSET_CAPTION:
623 code = InsetOld::CAPTION_CODE;
625 case LFUN_INSERT_NOTE:
626 code = InsetOld::NOTE_CODE;
628 case LFUN_INSERT_CHARSTYLE:
629 code = InsetOld::CHARSTYLE_CODE;
630 if (buf->params().getLyXTextClass().charstyles().empty())
633 case LFUN_INSERT_BOX:
634 code = InsetOld::BOX_CODE;
636 case LFUN_INSERT_BRANCH:
637 code = InsetOld::BRANCH_CODE;
638 if (buf->params().branchlist().empty())
641 case LFUN_INSERT_LABEL:
642 code = InsetOld::LABEL_CODE;
644 case LFUN_INSET_OPTARG:
645 code = InsetOld::OPTARG_CODE;
647 case LFUN_ENVIRONMENT_INSERT:
648 code = InsetOld::BOX_CODE;
650 case LFUN_INDEX_INSERT:
651 code = InsetOld::INDEX_CODE;
653 case LFUN_INDEX_PRINT:
654 code = InsetOld::INDEX_PRINT_CODE;
656 case LFUN_TOC_INSERT:
657 code = InsetOld::TOC_CODE;
661 code = InsetOld::URL_CODE;
664 // always allow this, since we will inset a raw quote
665 // if an inset is not allowed.
667 case LFUN_HYPHENATION:
668 case LFUN_LIGATURE_BREAK:
670 case LFUN_MENU_SEPARATOR:
672 case LFUN_END_OF_SENTENCE:
673 code = InsetOld::SPECIALCHAR_CODE;
675 case LFUN_SPACE_INSERT:
676 // slight hack: we know this is allowed in math mode
678 code = InsetOld::SPACE_CODE;
680 case LFUN_INSET_DIALOG_SHOW: {
681 InsetBase * inset = cur.nextInset();
684 code = inset->lyxCode();
685 if (!(code == InsetOld::INCLUDE_CODE
686 || code == InsetOld::BIBTEX_CODE
687 || code == InsetOld::FLOAT_LIST_CODE
688 || code == InsetOld::TOC_CODE))
696 if (code != InsetOld::NO_CODE && tli && !tli->insetAllowed(code))
702 // A few general toggles
704 case LFUN_TOOLTIPS_TOGGLE:
705 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
708 case LFUN_READ_ONLY_TOGGLE:
709 flag.setOnOff(buf->isReadonly());
712 flag.setOnOff(cur.inTexted()
713 && cur.paragraph().params().startOfAppendix());
715 case LFUN_SWITCHBUFFER:
716 // toggle on the current buffer, but do not toggle off
717 // the other ones (is that a good idea?)
718 if (ev.argument == buf->fileName())
721 case LFUN_TRACK_CHANGES:
722 flag.setOnOff(buf->params().tracking_changes);
729 // the font related toggles
730 if (cur.inTexted()) {
731 LyXFont const & font = cur.text()->real_current_font;
734 flag.setOnOff(font.emph() == LyXFont::ON);
737 flag.setOnOff(font.noun() == LyXFont::ON);
740 flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
743 flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
746 flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
749 flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
755 string tc = mathcursor::getLastCode();
758 flag.setOnOff(tc == "mathbf");
761 flag.setOnOff(tc == "mathsf");
764 flag.setOnOff(tc == "mathcal");
767 flag.setOnOff(tc == "mathrm");
770 flag.setOnOff(tc == "mathtt");
773 flag.setOnOff(tc == "mathbb");
776 flag.setOnOff(tc == "mathnormal");
784 // this one is difficult to get right. As a half-baked
785 // solution, we consider only the first action of the sequence
786 if (ev.action == LFUN_SEQUENCE) {
787 // argument contains ';'-terminated commands
788 #warning LyXAction arguments not handled here.
789 flag = getStatus(FuncRequest(lyxaction.lookupFunc(token(ev.argument, ';', 0))));
798 bool ensureBufferClean(BufferView * bv)
800 Buffer & buf = *bv->buffer();
804 string const file = MakeDisplayPath(buf.fileName(), 30);
805 string text = bformat(_("The document %1$s has unsaved "
806 "changes.\n\nDo you want to save "
807 "the document?"), file);
808 int const ret = Alert::prompt(_("Save changed document?"),
809 text, 0, 1, _("&Save"),
813 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
815 return buf.isClean();
821 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
823 string argument = cmd.argument;
824 kb_action action = cmd.action;
826 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
827 //lyxerr << "*** LyXFunc::dispatch: cmd: " << cmd << endl;
829 // we have not done anything wrong yet.
831 dispatch_buffer.erase();
832 selection_possible = false;
834 // We cannot use this function here
835 if (getStatus(cmd).disabled()) {
836 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
837 << lyxaction.getActionName(action)
838 << " [" << action << "] is disabled at this location"
840 setErrorMessage(getStatusMessage());
844 if (view()->available())
845 view()->hideCursor();
850 if (!view()->available())
852 view()->cursor().pop();
853 // Tell the paragraph dialog that we changed paragraph
854 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
858 case LFUN_WORDFINDFORWARD:
859 case LFUN_WORDFINDBACKWARD: {
860 static string last_search;
861 string searched_string;
863 if (!argument.empty()) {
864 last_search = argument;
865 searched_string = argument;
867 searched_string = last_search;
869 if (searched_string.empty())
872 bool const fw = action == LFUN_WORDFINDFORWARD;
874 lyx::find::find2string(searched_string, true, false, fw);
875 view()->dispatch(FuncRequest(LFUN_WORD_FIND, data));
880 owner->message(keyseq.printOptions());
883 case LFUN_EXEC_COMMAND:
884 owner->focus_command_buffer();
889 meta_fake_bit = key_modifier::none;
890 if (view()->available())
891 // cancel any selection
892 dispatch(FuncRequest(LFUN_MARK_OFF));
893 setMessage(N_("Cancel"));
897 meta_fake_bit = key_modifier::alt;
898 setMessage(keyseq.print());
901 case LFUN_READ_ONLY_TOGGLE:
902 if (owner->buffer()->lyxvc().inUse())
903 owner->buffer()->lyxvc().toggleReadOnly();
905 owner->buffer()->setReadonly(
906 !owner->buffer()->isReadonly());
909 case LFUN_CENTER: // this is center and redraw.
913 // --- Menus -----------------------------------------------
915 menuNew(argument, false);
918 case LFUN_MENUNEWTMPLT:
919 menuNew(argument, true);
922 case LFUN_CLOSEBUFFER:
927 if (!owner->buffer()->isUnnamed()) {
928 string const str = bformat(_("Saving document %1$s..."),
929 MakeDisplayPath(owner->buffer()->fileName()));
931 MenuWrite(owner->buffer());
932 owner->message(str + _(" done."));
934 WriteAs(owner->buffer());
938 WriteAs(owner->buffer(), argument);
941 case LFUN_MENURELOAD: {
942 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
943 string text = bformat(_("Any changes will be lost. Are you sure "
944 "you want to revert to the saved version of the document %1$s?"), file);
945 int const ret = Alert::prompt(_("Revert to saved document?"),
946 text, 0, 1, _("&Revert"), _("&Cancel"));
954 Exporter::Export(owner->buffer(), argument, true);
955 view()->showErrorList(BufferFormat(*owner->buffer()));
959 Exporter::Preview(owner->buffer(), argument);
960 view()->showErrorList(BufferFormat(*owner->buffer()));
964 Exporter::Export(owner->buffer(), "program", true);
965 view()->showErrorList(_("Build"));
969 owner->buffer()->runChktex();
970 view()->showErrorList(_("ChkTeX"));
974 if (argument == "custom")
975 owner->getDialogs().showSendto();
977 Exporter::Export(owner->buffer(), argument, false);
978 view()->showErrorList(BufferFormat(*owner->buffer()));
991 InsetCommandParams p("tableofcontents");
992 string const data = InsetCommandMailer::params2string("toc", p);
993 owner->getDialogs().show("toc", data, 0);
1009 case LFUN_RECONFIGURE:
1010 Reconfigure(view());
1013 case LFUN_HELP_OPEN: {
1014 string const arg = argument;
1016 setErrorMessage(N_("Missing argument"));
1019 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1020 if (fname.empty()) {
1021 lyxerr << "LyX: unable to find documentation file `"
1022 << arg << "'. Bad installation?" << endl;
1025 owner->message(bformat(_("Opening help file %1$s..."),
1026 MakeDisplayPath(fname)));
1027 view()->loadLyXFile(fname, false);
1031 // --- version control -------------------------------
1032 case LFUN_VC_REGISTER:
1033 if (!ensureBufferClean(view()))
1035 if (!owner->buffer()->lyxvc().inUse()) {
1036 owner->buffer()->lyxvc().registrer();
1041 case LFUN_VC_CHECKIN:
1042 if (!ensureBufferClean(view()))
1044 if (owner->buffer()->lyxvc().inUse()
1045 && !owner->buffer()->isReadonly()) {
1046 owner->buffer()->lyxvc().checkIn();
1051 case LFUN_VC_CHECKOUT:
1052 if (!ensureBufferClean(view()))
1054 if (owner->buffer()->lyxvc().inUse()
1055 && owner->buffer()->isReadonly()) {
1056 owner->buffer()->lyxvc().checkOut();
1061 case LFUN_VC_REVERT:
1062 owner->buffer()->lyxvc().revert();
1067 owner->buffer()->lyxvc().undoLast();
1071 // --- buffers ----------------------------------------
1072 case LFUN_SWITCHBUFFER:
1073 view()->buffer(bufferlist.getBuffer(argument));
1077 NewFile(view(), argument);
1080 case LFUN_FILE_OPEN:
1084 case LFUN_LAYOUT_TABULAR:
1085 if (InsetTabular * tab = view()->cursor().innerInsetTabular())
1086 tab->openLayoutDialog(view());
1089 case LFUN_DROP_LAYOUTS_CHOICE:
1090 owner->getToolbar().openLayoutList();
1093 case LFUN_MENU_OPEN_BY_NAME:
1094 owner->getMenubar().openByName(argument);
1097 // --- lyxserver commands ----------------------------
1099 setMessage(owner->buffer()->fileName());
1100 lyxerr[Debug::INFO] << "FNAME["
1101 << owner->buffer()->fileName()
1106 dispatch_buffer = keyseq.print();
1107 lyxserver->notifyClient(dispatch_buffer);
1110 case LFUN_GOTOFILEROW: {
1113 istringstream is(argument);
1114 is >> file_name >> row;
1115 if (prefixIs(file_name, getTmpDir())) {
1116 // Needed by inverse dvi search. If it is a file
1117 // in tmpdir, call the apropriated function
1118 view()->buffer(bufferlist.getBufferFromTmp(file_name));
1120 // Must replace extension of the file to be .lyx
1121 // and get full path
1122 string const s = ChangeExtension(file_name, ".lyx");
1123 // Either change buffer or load the file
1124 if (bufferlist.exists(s)) {
1125 view()->buffer(bufferlist.getBuffer(s));
1127 view()->loadLyXFile(s);
1131 view()->setCursorFromRow(row);
1134 // see BufferView_pimpl::center()
1135 view()->updateScrollbar();
1139 case LFUN_GOTO_PARAGRAPH: {
1140 istringstream is(argument);
1143 ParIterator par = owner->buffer()->getParFromID(id);
1144 if (par == owner->buffer()->par_iterator_end()) {
1145 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1146 << id << ']' << endl;
1149 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1150 << " found." << endl;
1154 view()->setCursor(par, 0);
1156 view()->switchKeyMap();
1157 owner->view_state_changed();
1160 // see BufferView_pimpl::center()
1161 view()->updateScrollbar();
1165 // --- Mathed stuff. If we are here, there is no locked inset yet.
1166 case LFUN_MATH_EXTERN:
1167 case LFUN_MATH_NUMBER:
1168 case LFUN_MATH_NONUMBER:
1169 case LFUN_MATH_LIMITS:
1170 setErrorMessage(N_("This is only allowed in math mode!"));
1173 case LFUN_DIALOG_SHOW: {
1174 string const name = cmd.getArg(0);
1175 string data = trim(cmd.argument.substr(name.size()));
1177 if (name == "character") {
1178 data = freefont2string();
1180 owner->getDialogs().show("character", data);
1182 else if (name == "document")
1183 owner->getDialogs().showDocument();
1184 else if (name == "forks")
1185 owner->getDialogs().showForks();
1186 else if (name == "preamble")
1187 owner->getDialogs().showPreamble();
1188 else if (name == "preferences")
1189 owner->getDialogs().showPreferences();
1190 else if (name == "print")
1191 owner->getDialogs().showPrint();
1192 else if (name == "spellchecker")
1193 owner->getDialogs().showSpellchecker();
1195 else if (name == "latexlog") {
1196 pair<Buffer::LogType, string> const logfile =
1197 owner->buffer()->getLogName();
1198 switch (logfile.first) {
1199 case Buffer::latexlog:
1202 case Buffer::buildlog:
1206 data += logfile.second;
1207 owner->getDialogs().show("log", data);
1209 else if (name == "vclog") {
1210 string const data = "vc " +
1211 owner->buffer()->lyxvc().getLogFile();
1212 owner->getDialogs().show("log", data);
1215 owner->getDialogs().show(name, data);
1219 case LFUN_DIALOG_SHOW_NEW_INSET: {
1220 string const name = cmd.getArg(0);
1221 string data = trim(cmd.argument.substr(name.size()));
1222 if (name == "bibitem" ||
1224 name == "include" ||
1230 InsetCommandParams p(name);
1231 data = InsetCommandMailer::params2string(name, p);
1232 } else if (name == "box") {
1233 // \c data == "Boxed" || "Frameless" etc
1234 InsetBoxParams p(data);
1235 data = InsetBoxMailer::params2string(p);
1236 } else if (name == "branch") {
1237 InsetBranchParams p;
1238 data = InsetBranchMailer::params2string(p);
1239 } else if (name == "citation") {
1240 InsetCommandParams p("cite");
1241 data = InsetCommandMailer::params2string(name, p);
1242 } else if (name == "ert") {
1243 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1244 } else if (name == "external") {
1245 InsetExternalParams p;
1246 Buffer const & buffer = *owner->buffer();
1247 data = InsetExternalMailer::params2string(p, buffer);
1248 } else if (name == "float") {
1250 data = InsetFloatMailer::params2string(p);
1251 } else if (name == "graphics") {
1252 InsetGraphicsParams p;
1253 Buffer const & buffer = *owner->buffer();
1254 data = InsetGraphicsMailer::params2string(p, buffer);
1255 } else if (name == "note") {
1257 data = InsetNoteMailer::params2string(p);
1258 } else if (name == "vspace") {
1260 data = InsetVSpaceMailer::params2string(space);
1261 } else if (name == "wrap") {
1263 data = InsetWrapMailer::params2string(p);
1265 owner->getDialogs().show(name, data, 0);
1269 case LFUN_DIALOG_SHOW_NEXT_INSET:
1272 case LFUN_INSET_DIALOG_SHOW: {
1273 InsetBase * inset = view()->cursor().nextInset();
1275 inset->dispatch(view()->cursor(), FuncRequest(LFUN_INSET_DIALOG_SHOW));
1279 case LFUN_DIALOG_UPDATE: {
1280 string const & name = argument;
1281 // Can only update a dialog connected to an existing inset
1282 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1284 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1285 inset->dispatch(view()->cursor(), fr);
1286 } else if (name == "paragraph") {
1287 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1292 case LFUN_DIALOG_HIDE:
1293 Dialogs::hide(argument, 0);
1296 case LFUN_DIALOG_DISCONNECT_INSET:
1297 owner->getDialogs().disconnect(argument);
1300 case LFUN_CHILDOPEN: {
1301 string const filename =
1302 MakeAbsPath(argument, owner->buffer()->filePath());
1303 setMessage(N_("Opening child document ") +
1304 MakeDisplayPath(filename) + "...");
1305 view()->savePosition(0);
1306 string const parentfilename = owner->buffer()->fileName();
1307 if (bufferlist.exists(filename))
1308 view()->buffer(bufferlist.getBuffer(filename));
1310 view()->loadLyXFile(filename);
1311 // Set the parent name of the child document.
1312 // This makes insertion of citations and references in the child work,
1313 // when the target is in the parent or another child document.
1314 owner->buffer()->setParentName(parentfilename);
1318 case LFUN_TOGGLECURSORFOLLOW:
1319 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1323 owner->getIntl().KeyMapOn(false);
1326 case LFUN_KMAP_PRIM:
1327 owner->getIntl().KeyMapPrim();
1331 owner->getIntl().KeyMapSec();
1334 case LFUN_KMAP_TOGGLE:
1335 owner->getIntl().ToggleKeyMap();
1341 argument = split(argument, countstr, ' ');
1342 istringstream is(countstr);
1345 lyxerr << "repeat: count: " << count << " cmd: " << argument << endl;
1346 for (int i = 0; i < count; ++i)
1347 dispatch(lyxaction.lookupFunc(argument));
1352 // argument contains ';'-terminated commands
1353 while (!argument.empty()) {
1355 argument = split(argument, first, ';');
1356 dispatch(lyxaction.lookupFunc(first));
1360 case LFUN_SAVEPREFERENCES: {
1361 Path p(user_lyxdir());
1362 lyxrc.write("preferences");
1366 case LFUN_SCREEN_FONT_UPDATE:
1367 // handle the screen font changes.
1368 lyxrc.set_font_norm_type();
1369 lyx_gui::update_fonts();
1370 // All visible buffers will need resize
1374 case LFUN_SET_COLOR: {
1376 string const x11_name = split(argument, lyx_name, ' ');
1377 if (lyx_name.empty() || x11_name.empty()) {
1378 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1383 bool const graphicsbg_changed =
1384 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1385 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1387 LColor::color col = lcolor.getFromLyXName(lyx_name);
1388 if (!lcolor.setColor(col, x11_name)) {
1390 bformat(_("Set-color \"%1$s\" failed "
1391 "- color is undefined or "
1392 "may not be redefined"), lyx_name));
1396 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1398 if (graphicsbg_changed) {
1399 #ifdef WITH_WARNINGS
1400 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1403 lyx::graphics::GCache::get().changeDisplay(true);
1410 owner->message(argument);
1413 case LFUN_FORKS_KILL:
1414 if (isStrInt(argument))
1415 ForkedcallsController::get().kill(strToInt(argument));
1418 case LFUN_TOOLTIPS_TOGGLE:
1419 owner->getDialogs().toggleTooltips();
1422 case LFUN_EXTERNAL_EDIT:
1423 InsetExternal().dispatch(view()->cursor(), FuncRequest(action, argument));
1427 DispatchResult res = view()->cursor().dispatch(cmd);
1428 if (!res.dispatched());
1429 view()->dispatch(cmd);
1434 if (!view()->cursor().inMathed())
1435 view()->owner()->updateLayoutChoice();
1437 if (view()->available()) {
1438 view()->fitCursor();
1440 view()->cursor().updatePos();
1441 // if we executed a mutating lfun, mark the buffer as dirty
1442 if (!getStatus(cmd).disabled()
1443 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1444 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1445 view()->buffer()->markDirty();
1448 if (!view()->cursor().inMathed())
1449 sendDispatchMessage(getMessage(), cmd, verbose);
1453 void LyXFunc::sendDispatchMessage(string const & msg,
1454 FuncRequest const & cmd, bool verbose)
1456 owner->updateMenubar();
1457 owner->updateToolbar();
1459 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1460 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1462 owner->message(msg);
1466 string dispatch_msg = msg;
1467 if (!dispatch_msg.empty())
1468 dispatch_msg += ' ';
1470 string comname = lyxaction.getActionName(cmd.action);
1472 bool argsadded = false;
1474 if (!cmd.argument.empty()) {
1475 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1476 comname += ' ' + cmd.argument;
1481 string const shortcuts = toplevel_keymap->findbinding(cmd);
1483 if (!shortcuts.empty()) {
1484 comname += ": " + shortcuts;
1485 } else if (!argsadded && !cmd.argument.empty()) {
1486 comname += ' ' + cmd.argument;
1489 if (!comname.empty()) {
1490 comname = rtrim(comname);
1491 dispatch_msg += '(' + comname + ')';
1494 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1495 if (!dispatch_msg.empty())
1496 owner->message(dispatch_msg);
1500 void LyXFunc::setupLocalKeymap()
1502 keyseq.stdmap = toplevel_keymap.get();
1503 keyseq.curmap = toplevel_keymap.get();
1504 cancel_meta_seq.stdmap = toplevel_keymap.get();
1505 cancel_meta_seq.curmap = toplevel_keymap.get();
1509 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1511 string initpath = lyxrc.document_path;
1512 string filename(name);
1514 if (view()->available()) {
1515 string const trypath = owner->buffer()->filePath();
1516 // If directory is writeable, use this as default.
1517 if (IsDirWriteable(trypath))
1521 static int newfile_number;
1523 if (filename.empty()) {
1524 filename = AddName(lyxrc.document_path,
1525 "newfile" + tostr(++newfile_number) + ".lyx");
1526 FileInfo fi(filename);
1527 while (bufferlist.exists(filename) || fi.readable()) {
1529 filename = AddName(lyxrc.document_path,
1530 "newfile" + tostr(newfile_number) +
1532 fi.newFile(filename);
1536 // The template stuff
1539 FileDialog fileDlg(_("Select template file"),
1540 LFUN_SELECT_FILE_SYNC,
1541 make_pair(string(_("Documents|#o#O")),
1542 string(lyxrc.document_path)),
1543 make_pair(string(_("Templates|#T#t")),
1544 string(lyxrc.template_path)));
1546 FileDialog::Result result =
1547 fileDlg.open(lyxrc.template_path,
1548 FileFilterList(_("LyX Documents (*.lyx)")),
1551 if (result.first == FileDialog::Later)
1553 if (result.second.empty())
1555 templname = result.second;
1558 view()->newFile(filename, templname, !name.empty());
1562 void LyXFunc::open(string const & fname)
1564 string initpath = lyxrc.document_path;
1566 if (view()->available()) {
1567 string const trypath = owner->buffer()->filePath();
1568 // If directory is writeable, use this as default.
1569 if (IsDirWriteable(trypath))
1575 if (fname.empty()) {
1576 FileDialog fileDlg(_("Select document to open"),
1578 make_pair(string(_("Documents|#o#O")),
1579 string(lyxrc.document_path)),
1580 make_pair(string(_("Examples|#E#e")),
1581 string(AddPath(system_lyxdir(), "examples"))));
1583 FileDialog::Result result =
1584 fileDlg.open(initpath,
1585 FileFilterList(_("LyX Documents (*.lyx)")),
1588 if (result.first == FileDialog::Later)
1591 filename = result.second;
1593 // check selected filename
1594 if (filename.empty()) {
1595 owner->message(_("Canceled."));
1601 // get absolute path of file and add ".lyx" to the filename if
1603 string const fullpath = FileSearch(string(), filename, "lyx");
1604 if (!fullpath.empty()) {
1605 filename = fullpath;
1608 string const disp_fn(MakeDisplayPath(filename));
1610 // if the file doesn't exist, let the user create one
1611 FileInfo const f(filename, true);
1613 // the user specifically chose this name. Believe them.
1614 view()->newFile(filename, "", true);
1618 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1621 if (view()->loadLyXFile(filename)) {
1622 str2 = bformat(_("Document %1$s opened."), disp_fn);
1624 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1626 owner->message(str2);
1630 void LyXFunc::doImport(string const & argument)
1633 string filename = split(argument, format, ' ');
1635 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1636 << " file: " << filename << endl;
1638 // need user interaction
1639 if (filename.empty()) {
1640 string initpath = lyxrc.document_path;
1642 if (view()->available()) {
1643 string const trypath = owner->buffer()->filePath();
1644 // If directory is writeable, use this as default.
1645 if (IsDirWriteable(trypath))
1649 string const text = bformat(_("Select %1$s file to import"),
1650 formats.prettyName(format));
1652 FileDialog fileDlg(text,
1654 make_pair(string(_("Documents|#o#O")),
1655 string(lyxrc.document_path)),
1656 make_pair(string(_("Examples|#E#e")),
1657 string(AddPath(system_lyxdir(), "examples"))));
1659 string const filter = formats.prettyName(format)
1660 + " (*." + formats.extension(format) + ')';
1662 FileDialog::Result result =
1663 fileDlg.open(initpath,
1664 FileFilterList(filter),
1667 if (result.first == FileDialog::Later)
1670 filename = result.second;
1672 // check selected filename
1673 if (filename.empty())
1674 owner->message(_("Canceled."));
1677 if (filename.empty())
1680 // get absolute path of file
1681 filename = MakeAbsPath(filename);
1683 string const lyxfile = ChangeExtension(filename, ".lyx");
1685 // Check if the document already is open
1686 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1687 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1688 owner->message(_("Canceled."));
1693 // if the file exists already, and we didn't do
1694 // -i lyx thefile.lyx, warn
1695 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1696 string const file = MakeDisplayPath(lyxfile, 30);
1698 string text = bformat(_("The document %1$s already exists.\n\n"
1699 "Do you want to over-write that document?"), file);
1700 int const ret = Alert::prompt(_("Over-write document?"),
1701 text, 0, 1, _("&Over-write"), _("&Cancel"));
1704 owner->message(_("Canceled."));
1709 Importer::Import(owner, filename, format);
1713 void LyXFunc::closeBuffer()
1715 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1716 if (bufferlist.empty()) {
1717 // need this otherwise SEGV may occur while
1718 // trying to set variables that don't exist
1719 // since there's no current buffer
1720 owner->getDialogs().hideBufferDependent();
1722 view()->buffer(bufferlist.first());
1728 // Each "owner" should have it's own message method. lyxview and
1729 // the minibuffer would use the minibuffer, but lyxserver would
1730 // send an ERROR signal to its client. Alejandro 970603
1731 // This function is bit problematic when it comes to NLS, to make the
1732 // lyx servers client be language indepenent we must not translate
1733 // strings sent to this func.
1734 void LyXFunc::setErrorMessage(string const & m) const
1736 dispatch_buffer = m;
1741 void LyXFunc::setMessage(string const & m) const
1743 dispatch_buffer = m;
1747 void LyXFunc::setStatusMessage(string const & m) const
1753 string const LyXFunc::view_status_message()
1755 // When meta-fake key is pressed, show the key sequence so far + "M-".
1757 return keyseq.print() + "M-";
1760 // Else, when a non-complete key sequence is pressed,
1761 // show the available options.
1762 if (keyseq.length() > 0 && !keyseq.deleted()) {
1763 return keyseq.printOptions();
1766 if (!view()->available())
1767 return _("Welcome to LyX!");
1769 return currentState(view());
1773 BufferView * LyXFunc::view() const
1775 BOOST_ASSERT(owner);
1776 return owner->view().get();
1780 bool LyXFunc::wasMetaKey() const
1782 return (meta_fake_bit != key_modifier::none);