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);
1001 case LFUN_RECONFIGURE:
1002 Reconfigure(view());
1005 case LFUN_HELP_OPEN: {
1006 string const arg = argument;
1008 setErrorMessage(N_("Missing argument"));
1011 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1012 if (fname.empty()) {
1013 lyxerr << "LyX: unable to find documentation file `"
1014 << arg << "'. Bad installation?" << endl;
1017 owner->message(bformat(_("Opening help file %1$s..."),
1018 MakeDisplayPath(fname)));
1019 view()->loadLyXFile(fname, false);
1023 // --- version control -------------------------------
1024 case LFUN_VC_REGISTER:
1025 if (!ensureBufferClean(view()))
1027 if (!owner->buffer()->lyxvc().inUse()) {
1028 owner->buffer()->lyxvc().registrer();
1033 case LFUN_VC_CHECKIN:
1034 if (!ensureBufferClean(view()))
1036 if (owner->buffer()->lyxvc().inUse()
1037 && !owner->buffer()->isReadonly()) {
1038 owner->buffer()->lyxvc().checkIn();
1043 case LFUN_VC_CHECKOUT:
1044 if (!ensureBufferClean(view()))
1046 if (owner->buffer()->lyxvc().inUse()
1047 && owner->buffer()->isReadonly()) {
1048 owner->buffer()->lyxvc().checkOut();
1053 case LFUN_VC_REVERT:
1054 owner->buffer()->lyxvc().revert();
1059 owner->buffer()->lyxvc().undoLast();
1063 // --- buffers ----------------------------------------
1064 case LFUN_SWITCHBUFFER:
1065 view()->buffer(bufferlist.getBuffer(argument));
1069 NewFile(view(), argument);
1072 case LFUN_FILE_OPEN:
1076 case LFUN_LAYOUT_TABULAR:
1077 if (InsetTabular * tab = view()->cursor().innerInsetTabular())
1078 tab->openLayoutDialog(view());
1081 case LFUN_DROP_LAYOUTS_CHOICE:
1082 owner->getToolbar().openLayoutList();
1085 case LFUN_MENU_OPEN_BY_NAME:
1086 owner->getMenubar().openByName(argument);
1089 // --- lyxserver commands ----------------------------
1091 setMessage(owner->buffer()->fileName());
1092 lyxerr[Debug::INFO] << "FNAME["
1093 << owner->buffer()->fileName()
1098 dispatch_buffer = keyseq.print();
1099 lyxserver->notifyClient(dispatch_buffer);
1102 case LFUN_GOTOFILEROW: {
1105 istringstream is(argument);
1106 is >> file_name >> row;
1107 if (prefixIs(file_name, getTmpDir())) {
1108 // Needed by inverse dvi search. If it is a file
1109 // in tmpdir, call the apropriated function
1110 view()->buffer(bufferlist.getBufferFromTmp(file_name));
1112 // Must replace extension of the file to be .lyx
1113 // and get full path
1114 string const s = ChangeExtension(file_name, ".lyx");
1115 // Either change buffer or load the file
1116 if (bufferlist.exists(s)) {
1117 view()->buffer(bufferlist.getBuffer(s));
1119 view()->loadLyXFile(s);
1123 view()->setCursorFromRow(row);
1126 // see BufferView_pimpl::center()
1127 view()->updateScrollbar();
1131 case LFUN_GOTO_PARAGRAPH: {
1132 istringstream is(argument);
1135 ParIterator par = owner->buffer()->getParFromID(id);
1136 if (par == owner->buffer()->par_iterator_end()) {
1137 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1138 << id << ']' << endl;
1141 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1142 << " found." << endl;
1146 view()->setCursor(par, 0);
1148 view()->switchKeyMap();
1149 owner->view_state_changed();
1152 // see BufferView_pimpl::center()
1153 view()->updateScrollbar();
1157 case LFUN_DIALOG_SHOW: {
1158 string const name = cmd.getArg(0);
1159 string data = trim(cmd.argument.substr(name.size()));
1161 if (name == "character") {
1162 data = freefont2string();
1164 owner->getDialogs().show("character", data);
1166 else if (name == "document")
1167 owner->getDialogs().showDocument();
1168 else if (name == "forks")
1169 owner->getDialogs().showForks();
1170 else if (name == "preamble")
1171 owner->getDialogs().showPreamble();
1172 else if (name == "preferences")
1173 owner->getDialogs().showPreferences();
1174 else if (name == "print")
1175 owner->getDialogs().showPrint();
1176 else if (name == "spellchecker")
1177 owner->getDialogs().showSpellchecker();
1179 else if (name == "latexlog") {
1180 pair<Buffer::LogType, string> const logfile =
1181 owner->buffer()->getLogName();
1182 switch (logfile.first) {
1183 case Buffer::latexlog:
1186 case Buffer::buildlog:
1190 data += logfile.second;
1191 owner->getDialogs().show("log", data);
1193 else if (name == "vclog") {
1194 string const data = "vc " +
1195 owner->buffer()->lyxvc().getLogFile();
1196 owner->getDialogs().show("log", data);
1199 owner->getDialogs().show(name, data);
1203 case LFUN_DIALOG_SHOW_NEW_INSET: {
1204 string const name = cmd.getArg(0);
1205 string data = trim(cmd.argument.substr(name.size()));
1206 if (name == "bibitem" ||
1208 name == "include" ||
1214 InsetCommandParams p(name);
1215 data = InsetCommandMailer::params2string(name, p);
1216 } else if (name == "box") {
1217 // \c data == "Boxed" || "Frameless" etc
1218 InsetBoxParams p(data);
1219 data = InsetBoxMailer::params2string(p);
1220 } else if (name == "branch") {
1221 InsetBranchParams p;
1222 data = InsetBranchMailer::params2string(p);
1223 } else if (name == "citation") {
1224 InsetCommandParams p("cite");
1225 data = InsetCommandMailer::params2string(name, p);
1226 } else if (name == "ert") {
1227 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1228 } else if (name == "external") {
1229 InsetExternalParams p;
1230 Buffer const & buffer = *owner->buffer();
1231 data = InsetExternalMailer::params2string(p, buffer);
1232 } else if (name == "float") {
1234 data = InsetFloatMailer::params2string(p);
1235 } else if (name == "graphics") {
1236 InsetGraphicsParams p;
1237 Buffer const & buffer = *owner->buffer();
1238 data = InsetGraphicsMailer::params2string(p, buffer);
1239 } else if (name == "note") {
1241 data = InsetNoteMailer::params2string(p);
1242 } else if (name == "vspace") {
1244 data = InsetVSpaceMailer::params2string(space);
1245 } else if (name == "wrap") {
1247 data = InsetWrapMailer::params2string(p);
1249 owner->getDialogs().show(name, data, 0);
1253 case LFUN_DIALOG_SHOW_NEXT_INSET:
1256 case LFUN_INSET_DIALOG_SHOW: {
1257 InsetBase * inset = view()->cursor().nextInset();
1259 inset->dispatch(view()->cursor(), FuncRequest(LFUN_INSET_DIALOG_SHOW));
1263 case LFUN_DIALOG_UPDATE: {
1264 string const & name = argument;
1265 // Can only update a dialog connected to an existing inset
1266 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1268 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1269 inset->dispatch(view()->cursor(), fr);
1270 } else if (name == "paragraph") {
1271 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1276 case LFUN_DIALOG_HIDE:
1277 Dialogs::hide(argument, 0);
1280 case LFUN_DIALOG_DISCONNECT_INSET:
1281 owner->getDialogs().disconnect(argument);
1284 case LFUN_CHILDOPEN: {
1285 string const filename =
1286 MakeAbsPath(argument, owner->buffer()->filePath());
1287 setMessage(N_("Opening child document ") +
1288 MakeDisplayPath(filename) + "...");
1289 view()->savePosition(0);
1290 string const parentfilename = owner->buffer()->fileName();
1291 if (bufferlist.exists(filename))
1292 view()->buffer(bufferlist.getBuffer(filename));
1294 view()->loadLyXFile(filename);
1295 // Set the parent name of the child document.
1296 // This makes insertion of citations and references in the child work,
1297 // when the target is in the parent or another child document.
1298 owner->buffer()->setParentName(parentfilename);
1302 case LFUN_TOGGLECURSORFOLLOW:
1303 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1307 owner->getIntl().KeyMapOn(false);
1310 case LFUN_KMAP_PRIM:
1311 owner->getIntl().KeyMapPrim();
1315 owner->getIntl().KeyMapSec();
1318 case LFUN_KMAP_TOGGLE:
1319 owner->getIntl().ToggleKeyMap();
1325 argument = split(argument, countstr, ' ');
1326 istringstream is(countstr);
1329 lyxerr << "repeat: count: " << count << " cmd: " << argument << endl;
1330 for (int i = 0; i < count; ++i)
1331 dispatch(lyxaction.lookupFunc(argument));
1336 // argument contains ';'-terminated commands
1337 while (!argument.empty()) {
1339 argument = split(argument, first, ';');
1340 dispatch(lyxaction.lookupFunc(first));
1344 case LFUN_SAVEPREFERENCES: {
1345 Path p(user_lyxdir());
1346 lyxrc.write("preferences");
1350 case LFUN_SCREEN_FONT_UPDATE:
1351 // handle the screen font changes.
1352 lyxrc.set_font_norm_type();
1353 lyx_gui::update_fonts();
1354 // All visible buffers will need resize
1358 case LFUN_SET_COLOR: {
1360 string const x11_name = split(argument, lyx_name, ' ');
1361 if (lyx_name.empty() || x11_name.empty()) {
1362 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1367 bool const graphicsbg_changed =
1368 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1369 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1371 LColor::color col = lcolor.getFromLyXName(lyx_name);
1372 if (!lcolor.setColor(col, x11_name)) {
1374 bformat(_("Set-color \"%1$s\" failed "
1375 "- color is undefined or "
1376 "may not be redefined"), lyx_name));
1380 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1382 if (graphicsbg_changed) {
1383 #ifdef WITH_WARNINGS
1384 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1387 lyx::graphics::GCache::get().changeDisplay(true);
1394 owner->message(argument);
1397 case LFUN_FORKS_KILL:
1398 if (isStrInt(argument))
1399 ForkedcallsController::get().kill(strToInt(argument));
1402 case LFUN_TOOLTIPS_TOGGLE:
1403 owner->getDialogs().toggleTooltips();
1406 case LFUN_EXTERNAL_EDIT:
1407 InsetExternal().dispatch(view()->cursor(), FuncRequest(action, argument));
1411 DispatchResult res = view()->cursor().dispatch(cmd);
1412 if (!res.dispatched());
1413 view()->dispatch(cmd);
1418 if (view()->cursor().inTexted())
1419 view()->owner()->updateLayoutChoice();
1421 if (view()->available()) {
1422 view()->fitCursor();
1424 view()->cursor().updatePos();
1425 // if we executed a mutating lfun, mark the buffer as dirty
1426 if (!getStatus(cmd).disabled()
1427 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1428 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1429 view()->buffer()->markDirty();
1432 if (view()->cursor().inTexted())
1433 sendDispatchMessage(getMessage(), cmd, verbose);
1437 void LyXFunc::sendDispatchMessage(string const & msg,
1438 FuncRequest const & cmd, bool verbose)
1440 owner->updateMenubar();
1441 owner->updateToolbar();
1443 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1444 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1446 owner->message(msg);
1450 string dispatch_msg = msg;
1451 if (!dispatch_msg.empty())
1452 dispatch_msg += ' ';
1454 string comname = lyxaction.getActionName(cmd.action);
1456 bool argsadded = false;
1458 if (!cmd.argument.empty()) {
1459 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1460 comname += ' ' + cmd.argument;
1465 string const shortcuts = toplevel_keymap->findbinding(cmd);
1467 if (!shortcuts.empty()) {
1468 comname += ": " + shortcuts;
1469 } else if (!argsadded && !cmd.argument.empty()) {
1470 comname += ' ' + cmd.argument;
1473 if (!comname.empty()) {
1474 comname = rtrim(comname);
1475 dispatch_msg += '(' + comname + ')';
1478 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1479 if (!dispatch_msg.empty())
1480 owner->message(dispatch_msg);
1484 void LyXFunc::setupLocalKeymap()
1486 keyseq.stdmap = toplevel_keymap.get();
1487 keyseq.curmap = toplevel_keymap.get();
1488 cancel_meta_seq.stdmap = toplevel_keymap.get();
1489 cancel_meta_seq.curmap = toplevel_keymap.get();
1493 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1495 string initpath = lyxrc.document_path;
1496 string filename(name);
1498 if (view()->available()) {
1499 string const trypath = owner->buffer()->filePath();
1500 // If directory is writeable, use this as default.
1501 if (IsDirWriteable(trypath))
1505 static int newfile_number;
1507 if (filename.empty()) {
1508 filename = AddName(lyxrc.document_path,
1509 "newfile" + tostr(++newfile_number) + ".lyx");
1510 FileInfo fi(filename);
1511 while (bufferlist.exists(filename) || fi.readable()) {
1513 filename = AddName(lyxrc.document_path,
1514 "newfile" + tostr(newfile_number) +
1516 fi.newFile(filename);
1520 // The template stuff
1523 FileDialog fileDlg(_("Select template file"),
1524 LFUN_SELECT_FILE_SYNC,
1525 make_pair(string(_("Documents|#o#O")),
1526 string(lyxrc.document_path)),
1527 make_pair(string(_("Templates|#T#t")),
1528 string(lyxrc.template_path)));
1530 FileDialog::Result result =
1531 fileDlg.open(lyxrc.template_path,
1532 FileFilterList(_("LyX Documents (*.lyx)")),
1535 if (result.first == FileDialog::Later)
1537 if (result.second.empty())
1539 templname = result.second;
1542 view()->newFile(filename, templname, !name.empty());
1546 void LyXFunc::open(string const & fname)
1548 string initpath = lyxrc.document_path;
1550 if (view()->available()) {
1551 string const trypath = owner->buffer()->filePath();
1552 // If directory is writeable, use this as default.
1553 if (IsDirWriteable(trypath))
1559 if (fname.empty()) {
1560 FileDialog fileDlg(_("Select document to open"),
1562 make_pair(string(_("Documents|#o#O")),
1563 string(lyxrc.document_path)),
1564 make_pair(string(_("Examples|#E#e")),
1565 string(AddPath(system_lyxdir(), "examples"))));
1567 FileDialog::Result result =
1568 fileDlg.open(initpath,
1569 FileFilterList(_("LyX Documents (*.lyx)")),
1572 if (result.first == FileDialog::Later)
1575 filename = result.second;
1577 // check selected filename
1578 if (filename.empty()) {
1579 owner->message(_("Canceled."));
1585 // get absolute path of file and add ".lyx" to the filename if
1587 string const fullpath = FileSearch(string(), filename, "lyx");
1588 if (!fullpath.empty()) {
1589 filename = fullpath;
1592 string const disp_fn(MakeDisplayPath(filename));
1594 // if the file doesn't exist, let the user create one
1595 FileInfo const f(filename, true);
1597 // the user specifically chose this name. Believe them.
1598 view()->newFile(filename, "", true);
1602 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1605 if (view()->loadLyXFile(filename)) {
1606 str2 = bformat(_("Document %1$s opened."), disp_fn);
1608 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1610 owner->message(str2);
1614 void LyXFunc::doImport(string const & argument)
1617 string filename = split(argument, format, ' ');
1619 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1620 << " file: " << filename << endl;
1622 // need user interaction
1623 if (filename.empty()) {
1624 string initpath = lyxrc.document_path;
1626 if (view()->available()) {
1627 string const trypath = owner->buffer()->filePath();
1628 // If directory is writeable, use this as default.
1629 if (IsDirWriteable(trypath))
1633 string const text = bformat(_("Select %1$s file to import"),
1634 formats.prettyName(format));
1636 FileDialog fileDlg(text,
1638 make_pair(string(_("Documents|#o#O")),
1639 string(lyxrc.document_path)),
1640 make_pair(string(_("Examples|#E#e")),
1641 string(AddPath(system_lyxdir(), "examples"))));
1643 string const filter = formats.prettyName(format)
1644 + " (*." + formats.extension(format) + ')';
1646 FileDialog::Result result =
1647 fileDlg.open(initpath,
1648 FileFilterList(filter),
1651 if (result.first == FileDialog::Later)
1654 filename = result.second;
1656 // check selected filename
1657 if (filename.empty())
1658 owner->message(_("Canceled."));
1661 if (filename.empty())
1664 // get absolute path of file
1665 filename = MakeAbsPath(filename);
1667 string const lyxfile = ChangeExtension(filename, ".lyx");
1669 // Check if the document already is open
1670 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1671 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1672 owner->message(_("Canceled."));
1677 // if the file exists already, and we didn't do
1678 // -i lyx thefile.lyx, warn
1679 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1680 string const file = MakeDisplayPath(lyxfile, 30);
1682 string text = bformat(_("The document %1$s already exists.\n\n"
1683 "Do you want to over-write that document?"), file);
1684 int const ret = Alert::prompt(_("Over-write document?"),
1685 text, 0, 1, _("&Over-write"), _("&Cancel"));
1688 owner->message(_("Canceled."));
1693 Importer::Import(owner, filename, format);
1697 void LyXFunc::closeBuffer()
1699 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1700 if (bufferlist.empty()) {
1701 // need this otherwise SEGV may occur while
1702 // trying to set variables that don't exist
1703 // since there's no current buffer
1704 owner->getDialogs().hideBufferDependent();
1706 view()->buffer(bufferlist.first());
1712 // Each "owner" should have it's own message method. lyxview and
1713 // the minibuffer would use the minibuffer, but lyxserver would
1714 // send an ERROR signal to its client. Alejandro 970603
1715 // This function is bit problematic when it comes to NLS, to make the
1716 // lyx servers client be language indepenent we must not translate
1717 // strings sent to this func.
1718 void LyXFunc::setErrorMessage(string const & m) const
1720 dispatch_buffer = m;
1725 void LyXFunc::setMessage(string const & m) const
1727 dispatch_buffer = m;
1731 void LyXFunc::setStatusMessage(string const & m) const
1737 string const LyXFunc::view_status_message()
1739 // When meta-fake key is pressed, show the key sequence so far + "M-".
1741 return keyseq.print() + "M-";
1744 // Else, when a non-complete key sequence is pressed,
1745 // show the available options.
1746 if (keyseq.length() > 0 && !keyseq.deleted()) {
1747 return keyseq.printOptions();
1750 if (!view()->available())
1751 return _("Welcome to LyX!");
1753 return currentState(view());
1757 BufferView * LyXFunc::view() const
1759 BOOST_ASSERT(owner);
1760 return owner->view().get();
1764 bool LyXFunc::wasMetaKey() const
1766 return (meta_fake_bit != key_modifier::none);