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"
31 #include "CutAndPaste.h"
33 #include "dispatchresult.h"
35 #include "errorlist.h"
38 #include "funcrequest.h"
41 #include "insetiterator.h"
47 #include "LyXAction.h"
52 #include "lyxserver.h"
53 #include "lyxtextclasslist.h"
55 #include "paragraph.h"
56 #include "pariterator.h"
57 #include "ParagraphParameters.h"
60 #include "insets/insetbox.h"
61 #include "insets/insetbranch.h"
62 #include "insets/insetcommand.h"
63 #include "insets/insetert.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetfloat.h"
66 #include "insets/insetgraphics.h"
67 #include "insets/insetnote.h"
68 #include "insets/insettabular.h"
69 #include "insets/insetvspace.h"
70 #include "insets/insetwrap.h"
72 #include "frontends/Alert.h"
73 #include "frontends/Dialogs.h"
74 #include "frontends/FileDialog.h"
75 #include "frontends/lyx_gui.h"
76 #include "frontends/LyXKeySym.h"
77 #include "frontends/LyXView.h"
78 #include "frontends/Menubar.h"
79 #include "frontends/Toolbars.h"
81 #include "support/FileInfo.h"
82 #include "support/filetools.h"
83 #include "support/forkedcontr.h"
84 #include "support/globbing.h"
85 #include "support/lstrings.h"
86 #include "support/path.h"
87 #include "support/path_defines.h"
88 #include "support/systemcall.h"
89 #include "support/tostr.h"
90 #include "support/std_sstream.h"
91 #include "support/os.h"
93 using bv_funcs::freefont2string;
95 using lyx::support::AddName;
96 using lyx::support::AddPath;
97 using lyx::support::bformat;
98 using lyx::support::ChangeExtension;
99 using lyx::support::contains;
100 using lyx::support::FileFilterList;
101 using lyx::support::FileInfo;
102 using lyx::support::FileSearch;
103 using lyx::support::ForkedcallsController;
104 using lyx::support::i18nLibFileSearch;
105 using lyx::support::IsDirWriteable;
106 using lyx::support::IsFileReadable;
107 using lyx::support::isStrInt;
108 using lyx::support::MakeAbsPath;
109 using lyx::support::MakeDisplayPath;
110 using lyx::support::Path;
111 using lyx::support::QuoteName;
112 using lyx::support::rtrim;
113 using lyx::support::split;
114 using lyx::support::strToInt;
115 using lyx::support::strToUnsignedInt;
116 using lyx::support::subst;
117 using lyx::support::system_lyxdir;
118 using lyx::support::Systemcall;
119 using lyx::support::token;
120 using lyx::support::trim;
121 using lyx::support::user_lyxdir;
122 using lyx::support::prefixIs;
123 using lyx::support::os::getTmpDir;
126 using std::make_pair;
129 using std::istringstream;
132 extern BufferList bufferlist;
133 extern LyXServer * lyxserver;
134 extern bool selection_possible;
136 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
139 extern tex_accent_struct get_accent(kb_action action);
142 LyXFunc::LyXFunc(LyXView * lv)
145 keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
146 cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
147 meta_fake_bit(key_modifier::none)
152 void LyXFunc::handleKeyFunc(kb_action action)
154 char c = encoded_last_key;
156 if (keyseq.length()) {
160 owner->getIntl().getTransManager()
161 .deadkey(c, get_accent(action).accent, view()->getLyXText());
162 // Need to clear, in case the minibuffer calls these
165 // copied verbatim from do_accent_char
166 view()->cursor().resetAnchor();
171 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
173 lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
175 // Do nothing if we have nothing (JMarc)
176 if (!keysym->isOK()) {
177 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
182 if (keysym->isModifier()) {
183 lyxerr[Debug::KEY] << "isModifier true" << endl;
187 Encoding const * encoding = view()->cursor().getEncoding();
189 encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
191 // Do a one-deep top-level lookup for
192 // cancel and meta-fake keys. RVDK_PATCH_5
193 cancel_meta_seq.reset();
195 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
196 lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
198 // When not cancel or meta-fake, do the normal lookup.
199 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
200 // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
201 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
202 // remove Caps Lock and Mod2 as a modifiers
203 func = keyseq.addkey(keysym, (state | meta_fake_bit));
204 lyxerr[Debug::KEY] << "action now set to ["
205 << func.action << ']' << endl;
208 // Dont remove this unless you know what you are doing.
209 meta_fake_bit = key_modifier::none;
211 // can this happen now ?
212 if (func.action == LFUN_NOACTION) {
213 func = FuncRequest(LFUN_PREFIX);
216 if (lyxerr.debugging(Debug::KEY)) {
217 lyxerr << "Key [action="
218 << func.action << "]["
219 << keyseq.print() << ']'
223 // already here we know if it any point in going further
224 // why not return already here if action == -1 and
225 // num_bytes == 0? (Lgb)
227 if (keyseq.length() > 1) {
228 owner->message(keyseq.print());
232 // Maybe user can only reach the key via holding down shift.
233 // Let's see. But only if shift is the only modifier
234 if (func.action == LFUN_UNKNOWN_ACTION &&
235 state == key_modifier::shift) {
236 lyxerr[Debug::KEY] << "Trying without shift" << endl;
237 func = keyseq.addkey(keysym, key_modifier::none);
238 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
241 if (func.action == LFUN_UNKNOWN_ACTION) {
242 // Hmm, we didn't match any of the keysequences. See
243 // if it's normal insertable text not already covered
245 if (keysym->isText() && keyseq.length() == 1) {
246 lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
247 func = FuncRequest(LFUN_SELFINSERT);
249 lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
250 owner->message(_("Unknown function."));
255 if (func.action == LFUN_SELFINSERT) {
256 if (encoded_last_key != 0) {
257 string arg(1, encoded_last_key);
258 dispatch(FuncRequest(LFUN_SELFINSERT, arg));
260 << "SelfInsert arg[`" << arg << "']" << endl;
268 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
270 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
272 Buffer * buf = owner->buffer();
273 LCursor & cur = view()->cursor();
275 if (cmd.action == LFUN_NOACTION) {
276 setStatusMessage(N_("Nothing to do"));
281 switch (cmd.action) {
282 case LFUN_UNKNOWN_ACTION:
283 #ifndef HAVE_LIBAIKSAURUS
284 case LFUN_THESAURUS_ENTRY:
290 flag |= lyx_gui::getStatus(cmd);
293 if (flag.unknown()) {
294 setStatusMessage(N_("Unknown action"));
298 // the default error message if we disable the command
299 setStatusMessage(N_("Command disabled"));
301 // Check whether we need a buffer
302 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
304 setStatusMessage(N_("Command not allowed with"
305 "out any document open"));
310 // I would really like to avoid having this switch and rather try to
311 // encode this in the function itself.
312 // -- And I'd rather let an inset decide which LFUNs it is willing
313 // to handle (Andre')
315 switch (cmd.action) {
316 case LFUN_TOOLTIPS_TOGGLE:
317 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
320 case LFUN_READ_ONLY_TOGGLE:
321 flag.setOnOff(buf->isReadonly());
324 case LFUN_SWITCHBUFFER:
325 // toggle on the current buffer, but do not toggle off
326 // the other ones (is that a good idea?)
327 if (cmd.argument == buf->fileName())
332 enable = cmd.argument == "custom"
333 || Exporter::IsExportable(*buf, cmd.argument);
337 enable = cur.selection();
341 enable = buf->isLatex() && lyxrc.chktex_command != "none";
345 enable = Exporter::IsExportable(*buf, "program");
348 case LFUN_LAYOUT_TABULAR:
349 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
353 case LFUN_LAYOUT_PARAGRAPH:
354 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
357 case LFUN_VC_REGISTER:
358 enable = !buf->lyxvc().inUse();
360 case LFUN_VC_CHECKIN:
361 enable = buf->lyxvc().inUse() && !buf->isReadonly();
363 case LFUN_VC_CHECKOUT:
364 enable = buf->lyxvc().inUse() && buf->isReadonly();
368 enable = buf->lyxvc().inUse();
370 case LFUN_MENURELOAD:
371 enable = !buf->isUnnamed() && !buf->isClean();
375 case LFUN_INSET_SETTINGS: {
379 UpdatableInset * inset = cur.inset().asUpdatableInset();
380 lyxerr << "inset: " << inset << endl;
384 InsetOld::Code code = inset->lyxCode();
386 case InsetOld::TABULAR_CODE:
387 enable = cmd.argument == "tabular";
389 case InsetOld::ERT_CODE:
390 enable = cmd.argument == "ert";
392 case InsetOld::FLOAT_CODE:
393 enable = cmd.argument == "float";
395 case InsetOld::WRAP_CODE:
396 enable = cmd.argument == "wrap";
398 case InsetOld::NOTE_CODE:
399 enable = cmd.argument == "note";
401 case InsetOld::BRANCH_CODE:
402 enable = cmd.argument == "branch";
404 case InsetOld::BOX_CODE:
405 enable = cmd.argument == "box";
413 case LFUN_DIALOG_SHOW: {
414 string const name = cmd.getArg(0);
416 enable = name == "aboutlyx"
420 || name == "texinfo";
421 else if (name == "print")
422 enable = Exporter::IsExportable(*buf, "dvi")
423 && lyxrc.print_command != "none";
424 else if (name == "character")
425 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
426 else if (name == "vclog")
427 enable = buf->lyxvc().inUse();
428 else if (name == "latexlog")
429 enable = IsFileReadable(buf->getLogName().second);
433 case LFUN_DIALOG_UPDATE: {
434 string const name = cmd.getArg(0);
436 enable = name == "prefs";
440 // this one is difficult to get right. As a half-baked
441 // solution, we consider only the first action of the sequence
442 case LFUN_SEQUENCE: {
443 // argument contains ';'-terminated commands
444 string const firstcmd = token(cmd.argument, ';', 0);
445 flag = getStatus(lyxaction.lookupFunc(firstcmd));
449 case LFUN_MENUNEWTMPLT:
450 case LFUN_WORDFINDFORWARD:
451 case LFUN_WORDFINDBACKWARD:
453 case LFUN_EXEC_COMMAND:
456 case LFUN_CLOSEBUFFER:
465 case LFUN_RECONFIGURE:
469 case LFUN_DROP_LAYOUTS_CHOICE:
470 case LFUN_MENU_OPEN_BY_NAME:
473 case LFUN_GOTOFILEROW:
474 case LFUN_GOTO_PARAGRAPH:
475 case LFUN_DIALOG_SHOW_NEW_INSET:
476 case LFUN_DIALOG_SHOW_NEXT_INSET:
477 case LFUN_DIALOG_HIDE:
478 case LFUN_DIALOG_DISCONNECT_INSET:
480 case LFUN_TOGGLECURSORFOLLOW:
484 case LFUN_KMAP_TOGGLE:
486 case LFUN_EXPORT_CUSTOM:
488 case LFUN_SAVEPREFERENCES:
489 case LFUN_SCREEN_FONT_UPDATE:
492 case LFUN_EXTERNAL_EDIT:
493 case LFUN_GRAPHICS_EDIT:
494 case LFUN_ALL_INSETS_TOGGLE:
495 case LFUN_LANGUAGE_BUFFER:
496 case LFUN_TEXTCLASS_APPLY:
497 case LFUN_TEXTCLASS_LOAD:
498 case LFUN_SAVE_AS_DEFAULT:
499 case LFUN_BUFFERPARAMS_APPLY:
500 case LFUN_LYXRC_APPLY:
501 // these are handled in our dispatch()
506 cur.getStatus(cmd, flag);
508 flag = view()->getStatus(cmd);
514 // Can we use a readonly buffer?
515 if (buf && buf->isReadonly()
516 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
517 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
518 setStatusMessage(N_("Document is read-only"));
522 //lyxerr << "LyXFunc::getStatus: got: " << flag.enabled() << endl;
529 bool ensureBufferClean(BufferView * bv)
531 Buffer & buf = *bv->buffer();
535 string const file = MakeDisplayPath(buf.fileName(), 30);
536 string text = bformat(_("The document %1$s has unsaved "
537 "changes.\n\nDo you want to save "
538 "the document?"), file);
539 int const ret = Alert::prompt(_("Save changed document?"),
540 text, 0, 1, _("&Save"),
544 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
546 return buf.isClean();
550 void showPrintError(string const & name)
552 string str = bformat(_("Could not print the document %1$s.\n"
553 "Check that your printer is set up correctly."),
554 MakeDisplayPath(name, 50));
555 Alert::error(_("Print document failed"), str);
559 void loadTextclass(string const & name)
561 std::pair<bool, lyx::textclass_type> const tc_pair =
562 textclasslist.NumberOfClass(name);
564 if (!tc_pair.first) {
565 lyxerr << "Document class \"" << name
566 << "\" does not exist."
571 lyx::textclass_type const tc = tc_pair.second;
573 if (!textclasslist[tc].load()) {
574 string s = bformat(_("The document could not be converted\n"
575 "into the document class %1$s."),
576 textclasslist[tc].name());
577 Alert::error(_("Could not change class"), s);
584 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
586 string const argument = cmd.argument;
587 kb_action const action = cmd.action;
589 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
590 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
592 // we have not done anything wrong yet.
594 dispatch_buffer.erase();
595 selection_possible = false;
599 // We cannot use this function here
600 if (!getStatus(cmd).enabled()) {
601 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
602 << lyxaction.getActionName(action)
603 << " [" << action << "] is disabled at this location"
605 setErrorMessage(getStatusMessage());
609 if (view()->available())
610 view()->hideCursor();
614 case LFUN_WORDFINDFORWARD:
615 case LFUN_WORDFINDBACKWARD: {
616 static string last_search;
617 string searched_string;
619 if (!argument.empty()) {
620 last_search = argument;
621 searched_string = argument;
623 searched_string = last_search;
626 if (searched_string.empty())
629 bool const fw = action == LFUN_WORDFINDFORWARD;
631 lyx::find::find2string(searched_string, true, false, fw);
632 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
637 owner->message(keyseq.printOptions());
640 case LFUN_EXEC_COMMAND:
641 owner->getToolbars().display("minibuffer", true);
642 owner->focus_command_buffer();
647 meta_fake_bit = key_modifier::none;
648 if (view()->available())
649 // cancel any selection
650 dispatch(FuncRequest(LFUN_MARK_OFF));
651 setMessage(N_("Cancel"));
655 meta_fake_bit = key_modifier::alt;
656 setMessage(keyseq.print());
659 case LFUN_READ_ONLY_TOGGLE:
660 if (owner->buffer()->lyxvc().inUse())
661 owner->buffer()->lyxvc().toggleReadOnly();
663 owner->buffer()->setReadonly(
664 !owner->buffer()->isReadonly());
667 // --- Menus -----------------------------------------------
669 menuNew(argument, false);
672 case LFUN_MENUNEWTMPLT:
673 menuNew(argument, true);
676 case LFUN_CLOSEBUFFER:
681 if (!owner->buffer()->isUnnamed()) {
682 string const str = bformat(_("Saving document %1$s..."),
683 MakeDisplayPath(owner->buffer()->fileName()));
685 MenuWrite(owner->buffer());
686 owner->message(str + _(" done."));
688 WriteAs(owner->buffer());
692 WriteAs(owner->buffer(), argument);
695 case LFUN_MENURELOAD: {
696 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
697 string text = bformat(_("Any changes will be lost. Are you sure "
698 "you want to revert to the saved version of the document %1$s?"), file);
699 int const ret = Alert::prompt(_("Revert to saved document?"),
700 text, 0, 1, _("&Revert"), _("&Cancel"));
708 Exporter::Export(owner->buffer(), argument, true);
709 view()->showErrorList(BufferFormat(*owner->buffer()));
713 Exporter::Preview(owner->buffer(), argument);
714 view()->showErrorList(BufferFormat(*owner->buffer()));
718 Exporter::Export(owner->buffer(), "program", true);
719 view()->showErrorList(_("Build"));
723 owner->buffer()->runChktex();
724 view()->showErrorList(_("ChkTeX"));
728 if (argument == "custom")
729 owner->getDialogs().show("sendto");
731 Exporter::Export(owner->buffer(), argument, false);
732 view()->showErrorList(BufferFormat(*owner->buffer()));
736 case LFUN_EXPORT_CUSTOM: {
738 string command = split(argument, format_name, ' ');
739 Format const * format = formats.getFormat(format_name);
741 lyxerr << "Format \"" << format_name
742 << "\" not recognized!"
747 Buffer * buffer = owner->buffer();
749 // The name of the file created by the conversion process
752 // Output to filename
753 if (format->name() == "lyx") {
754 string const latexname =
755 buffer->getLatexName(false);
756 filename = ChangeExtension(latexname,
757 format->extension());
758 filename = AddName(buffer->temppath(), filename);
760 if (!buffer->writeFile(filename))
764 Exporter::Export(buffer, format_name, true,
768 // Substitute $$FName for filename
769 if (!contains(command, "$$FName"))
770 command = "( " + command + " ) < $$FName";
771 command = subst(command, "$$FName", filename);
773 // Execute the command in the background
775 call.startscript(Systemcall::DontWait, command);
782 string command = split(split(argument, target, ' '),
786 || target_name.empty()
787 || command.empty()) {
788 lyxerr << "Unable to parse \""
789 << argument << '"' << std::endl;
792 if (target != "printer" && target != "file") {
793 lyxerr << "Unrecognized target \""
794 << target << '"' << std::endl;
798 Buffer * buffer = owner->buffer();
800 if (!Exporter::Export(buffer, "dvi", true)) {
801 showPrintError(buffer->fileName());
805 // Push directory path.
806 string const path = buffer->temppath();
809 // there are three cases here:
810 // 1. we print to a file
811 // 2. we print directly to a printer
812 // 3. we print using a spool command (print to file first)
815 string const dviname =
816 ChangeExtension(buffer->getLatexName(true),
819 if (target == "printer") {
820 if (!lyxrc.print_spool_command.empty()) {
821 // case 3: print using a spool
822 string const psname =
823 ChangeExtension(dviname,".ps");
824 command += lyxrc.print_to_file
827 + QuoteName(dviname);
830 lyxrc.print_spool_command +' ';
831 if (target_name != "default") {
832 command2 += lyxrc.print_spool_printerprefix
836 command2 += QuoteName(psname);
838 // If successful, then spool command
839 res = one.startscript(
844 res = one.startscript(
845 Systemcall::DontWait,
848 // case 2: print directly to a printer
849 res = one.startscript(
850 Systemcall::DontWait,
851 command + QuoteName(dviname));
855 // case 1: print to a file
856 command += lyxrc.print_to_file
857 + QuoteName(MakeAbsPath(target_name,
860 + QuoteName(dviname);
861 res = one.startscript(Systemcall::DontWait,
866 showPrintError(buffer->fileName());
879 InsetCommandParams p("tableofcontents");
880 string const data = InsetCommandMailer::params2string("toc", p);
881 owner->getDialogs().show("toc", data, 0);
889 case LFUN_RECONFIGURE:
893 case LFUN_HELP_OPEN: {
894 string const arg = argument;
896 setErrorMessage(N_("Missing argument"));
899 string const fname = i18nLibFileSearch("doc", arg, "lyx");
901 lyxerr << "LyX: unable to find documentation file `"
902 << arg << "'. Bad installation?" << endl;
905 owner->message(bformat(_("Opening help file %1$s..."),
906 MakeDisplayPath(fname)));
907 view()->loadLyXFile(fname, false);
911 // --- version control -------------------------------
912 case LFUN_VC_REGISTER:
913 if (!ensureBufferClean(view()))
915 if (!owner->buffer()->lyxvc().inUse()) {
916 owner->buffer()->lyxvc().registrer();
921 case LFUN_VC_CHECKIN:
922 if (!ensureBufferClean(view()))
924 if (owner->buffer()->lyxvc().inUse()
925 && !owner->buffer()->isReadonly()) {
926 owner->buffer()->lyxvc().checkIn();
931 case LFUN_VC_CHECKOUT:
932 if (!ensureBufferClean(view()))
934 if (owner->buffer()->lyxvc().inUse()
935 && owner->buffer()->isReadonly()) {
936 owner->buffer()->lyxvc().checkOut();
942 owner->buffer()->lyxvc().revert();
947 owner->buffer()->lyxvc().undoLast();
951 // --- buffers ----------------------------------------
952 case LFUN_SWITCHBUFFER:
953 view()->setBuffer(bufferlist.getBuffer(argument));
957 NewFile(view(), argument);
964 case LFUN_DROP_LAYOUTS_CHOICE:
965 owner->getToolbars().openLayoutList();
968 case LFUN_MENU_OPEN_BY_NAME:
969 owner->getMenubar().openByName(argument);
972 // --- lyxserver commands ----------------------------
974 setMessage(owner->buffer()->fileName());
975 lyxerr[Debug::INFO] << "FNAME["
976 << owner->buffer()->fileName()
981 dispatch_buffer = keyseq.print();
982 lyxserver->notifyClient(dispatch_buffer);
985 case LFUN_GOTOFILEROW: {
988 istringstream is(argument);
989 is >> file_name >> row;
990 if (prefixIs(file_name, getTmpDir())) {
991 // Needed by inverse dvi search. If it is a file
992 // in tmpdir, call the apropriated function
993 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
995 // Must replace extension of the file to be .lyx
997 string const s = ChangeExtension(file_name, ".lyx");
998 // Either change buffer or load the file
999 if (bufferlist.exists(s)) {
1000 view()->setBuffer(bufferlist.getBuffer(s));
1002 view()->loadLyXFile(s);
1006 view()->setCursorFromRow(row);
1009 // see BufferView_pimpl::center()
1010 view()->updateScrollbar();
1014 case LFUN_GOTO_PARAGRAPH: {
1015 istringstream is(argument);
1018 ParIterator par = owner->buffer()->getParFromID(id);
1019 if (par == owner->buffer()->par_iterator_end()) {
1020 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1021 << id << ']' << endl;
1024 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1025 << " found." << endl;
1029 view()->setCursor(par, 0);
1031 view()->switchKeyMap();
1032 owner->view_state_changed();
1035 // see BufferView_pimpl::center()
1036 view()->updateScrollbar();
1040 case LFUN_DIALOG_SHOW: {
1041 string const name = cmd.getArg(0);
1042 string data = trim(cmd.argument.substr(name.size()));
1044 if (name == "character") {
1045 data = freefont2string();
1047 owner->getDialogs().show("character", data);
1050 else if (name == "latexlog") {
1051 pair<Buffer::LogType, string> const logfile =
1052 owner->buffer()->getLogName();
1053 switch (logfile.first) {
1054 case Buffer::latexlog:
1057 case Buffer::buildlog:
1061 data += logfile.second;
1062 owner->getDialogs().show("log", data);
1064 else if (name == "vclog") {
1065 string const data = "vc " +
1066 owner->buffer()->lyxvc().getLogFile();
1067 owner->getDialogs().show("log", data);
1070 owner->getDialogs().show(name, data);
1074 case LFUN_DIALOG_SHOW_NEW_INSET: {
1075 string const name = cmd.getArg(0);
1076 string data = trim(cmd.argument.substr(name.size()));
1077 if (name == "bibitem" ||
1079 name == "include" ||
1085 InsetCommandParams p(name);
1086 data = InsetCommandMailer::params2string(name, p);
1087 } else if (name == "box") {
1088 // \c data == "Boxed" || "Frameless" etc
1089 InsetBoxParams p(data);
1090 data = InsetBoxMailer::params2string(p);
1091 } else if (name == "branch") {
1092 InsetBranchParams p;
1093 data = InsetBranchMailer::params2string(p);
1094 } else if (name == "citation") {
1095 InsetCommandParams p("cite");
1096 data = InsetCommandMailer::params2string(name, p);
1097 } else if (name == "ert") {
1098 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1099 } else if (name == "external") {
1100 InsetExternalParams p;
1101 Buffer const & buffer = *owner->buffer();
1102 data = InsetExternalMailer::params2string(p, buffer);
1103 } else if (name == "float") {
1105 data = InsetFloatMailer::params2string(p);
1106 } else if (name == "graphics") {
1107 InsetGraphicsParams p;
1108 Buffer const & buffer = *owner->buffer();
1109 data = InsetGraphicsMailer::params2string(p, buffer);
1110 } else if (name == "note") {
1112 data = InsetNoteMailer::params2string(p);
1113 } else if (name == "vspace") {
1115 data = InsetVSpaceMailer::params2string(space);
1116 } else if (name == "wrap") {
1118 data = InsetWrapMailer::params2string(p);
1120 owner->getDialogs().show(name, data, 0);
1124 case LFUN_DIALOG_SHOW_NEXT_INSET:
1127 case LFUN_DIALOG_UPDATE: {
1128 string const & name = argument;
1129 // Can only update a dialog connected to an existing inset
1130 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1132 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1133 inset->dispatch(view()->cursor(), fr);
1134 } else if (name == "paragraph") {
1135 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1136 } else if (name == "prefs") {
1137 owner->getDialogs().update(name, string());
1142 case LFUN_DIALOG_HIDE:
1143 Dialogs::hide(argument, 0);
1146 case LFUN_DIALOG_DISCONNECT_INSET:
1147 owner->getDialogs().disconnect(argument);
1150 case LFUN_CHILDOPEN: {
1151 string const filename =
1152 MakeAbsPath(argument, owner->buffer()->filePath());
1153 setMessage(N_("Opening child document ") +
1154 MakeDisplayPath(filename) + "...");
1155 view()->savePosition(0);
1156 string const parentfilename = owner->buffer()->fileName();
1157 if (bufferlist.exists(filename))
1158 view()->setBuffer(bufferlist.getBuffer(filename));
1160 view()->loadLyXFile(filename);
1161 // Set the parent name of the child document.
1162 // This makes insertion of citations and references in the child work,
1163 // when the target is in the parent or another child document.
1164 owner->buffer()->setParentName(parentfilename);
1168 case LFUN_TOGGLECURSORFOLLOW:
1169 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1173 owner->getIntl().KeyMapOn(false);
1176 case LFUN_KMAP_PRIM:
1177 owner->getIntl().KeyMapPrim();
1181 owner->getIntl().KeyMapSec();
1184 case LFUN_KMAP_TOGGLE:
1185 owner->getIntl().ToggleKeyMap();
1191 string rest = split(argument, countstr, ' ');
1192 istringstream is(countstr);
1195 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1196 for (int i = 0; i < count; ++i)
1197 dispatch(lyxaction.lookupFunc(rest));
1201 case LFUN_SEQUENCE: {
1202 // argument contains ';'-terminated commands
1203 string arg = argument;
1204 while (!arg.empty()) {
1206 arg = split(arg, first, ';');
1207 dispatch(lyxaction.lookupFunc(first));
1212 case LFUN_SAVEPREFERENCES: {
1213 Path p(user_lyxdir());
1214 lyxrc.write("preferences", false);
1218 case LFUN_SCREEN_FONT_UPDATE:
1219 // handle the screen font changes.
1220 lyxrc.set_font_norm_type();
1221 lyx_gui::update_fonts();
1222 // All visible buffers will need resize
1226 case LFUN_SET_COLOR: {
1228 string const x11_name = split(argument, lyx_name, ' ');
1229 if (lyx_name.empty() || x11_name.empty()) {
1230 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1235 bool const graphicsbg_changed =
1236 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1237 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1239 if (!lcolor.setColor(lyx_name, x11_name)) {
1241 bformat(_("Set-color \"%1$s\" failed "
1242 "- color is undefined or "
1243 "may not be redefined"), lyx_name));
1247 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1249 if (graphicsbg_changed) {
1250 #ifdef WITH_WARNINGS
1251 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1254 lyx::graphics::GCache::get().changeDisplay(true);
1261 owner->message(argument);
1264 case LFUN_TOOLTIPS_TOGGLE:
1265 owner->getDialogs().toggleTooltips();
1268 case LFUN_EXTERNAL_EDIT: {
1269 FuncRequest fr(action, argument);
1270 InsetExternal().dispatch(view()->cursor(), fr);
1274 case LFUN_GRAPHICS_EDIT: {
1275 FuncRequest fr(action, argument);
1276 InsetGraphics().dispatch(view()->cursor(), fr);
1280 case LFUN_ALL_INSETS_TOGGLE: {
1282 string const name = split(argument, action, ' ');
1283 InsetBase::Code const inset_code =
1284 InsetBase::translate(name);
1286 LCursor & cur = view()->cursor();
1287 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1289 InsetBase & inset = owner->buffer()->inset();
1290 InsetIterator it = inset_iterator_begin(inset);
1291 InsetIterator const end = inset_iterator_end(inset);
1292 for (; it != end; ++it) {
1293 if (inset_code == InsetBase::NO_CODE
1294 || inset_code == it->lyxCode())
1295 it->dispatch(cur, fr);
1300 case LFUN_LANGUAGE_BUFFER: {
1301 Buffer & buffer = *owner->buffer();
1302 Language const * oldL = buffer.params().language;
1303 Language const * newL = languages.getLanguage(argument);
1304 if (!newL || oldL == newL)
1307 if (oldL->RightToLeft() == newL->RightToLeft()
1308 && !buffer.isMultiLingual())
1309 buffer.changeLanguage(oldL, newL);
1311 buffer.updateDocLang(newL);
1315 case LFUN_BUFFERPARAMS_APPLY: {
1316 istringstream ss(argument);
1319 int const unknown_tokens =
1320 owner->buffer()->readHeader(lex);
1322 if (unknown_tokens != 0) {
1323 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1324 << unknown_tokens << " unknown token"
1325 << (unknown_tokens == 1 ? "" : "s")
1331 case LFUN_TEXTCLASS_APPLY: {
1332 Buffer * buffer = owner->buffer();
1334 lyx::textclass_type const old_class =
1335 buffer->params().textclass;
1337 loadTextclass(argument);
1339 std::pair<bool, lyx::textclass_type> const tc_pair =
1340 textclasslist.NumberOfClass(argument);
1345 lyx::textclass_type const new_class = tc_pair.second;
1346 if (old_class == new_class)
1350 owner->message(_("Converting document to new document class..."));
1352 lyx::cap::SwitchLayoutsBetweenClasses(
1353 old_class, new_class,
1354 buffer->paragraphs(), el);
1356 bufferErrors(*buffer, el);
1357 view()->showErrorList(_("Class switch"));
1361 case LFUN_TEXTCLASS_LOAD:
1362 loadTextclass(argument);
1365 case LFUN_LYXRC_APPLY: {
1366 istringstream ss(argument);
1367 bool const success = lyxrc.read(ss) == 0;
1370 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1371 << "Unable to read lyxrc data"
1379 DispatchResult res = view()->cursor().dispatch(cmd);
1380 if (res.dispatched())
1381 update |= res.update();
1383 update |= view()->dispatch(cmd);
1389 if (view()->available()) {
1390 if (view()->fitCursor() || update)
1392 // if we executed a mutating lfun, mark the buffer as dirty
1393 if (getStatus(cmd).enabled()
1394 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1395 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1396 view()->buffer()->markDirty();
1399 if (view()->cursor().inTexted()) {
1400 view()->owner()->updateLayoutChoice();
1401 sendDispatchMessage(getMessage(), cmd, verbose);
1407 void LyXFunc::sendDispatchMessage(string const & msg,
1408 FuncRequest const & cmd, bool verbose)
1410 owner->updateMenubar();
1411 owner->updateToolbars();
1413 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1414 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1416 owner->message(msg);
1420 string dispatch_msg = msg;
1421 if (!dispatch_msg.empty())
1422 dispatch_msg += ' ';
1424 string comname = lyxaction.getActionName(cmd.action);
1426 bool argsadded = false;
1428 if (!cmd.argument.empty()) {
1429 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1430 comname += ' ' + cmd.argument;
1435 string const shortcuts = toplevel_keymap->findbinding(cmd);
1437 if (!shortcuts.empty()) {
1438 comname += ": " + shortcuts;
1439 } else if (!argsadded && !cmd.argument.empty()) {
1440 comname += ' ' + cmd.argument;
1443 if (!comname.empty()) {
1444 comname = rtrim(comname);
1445 dispatch_msg += '(' + comname + ')';
1448 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1449 if (!dispatch_msg.empty())
1450 owner->message(dispatch_msg);
1454 void LyXFunc::setupLocalKeymap()
1456 keyseq.stdmap = toplevel_keymap.get();
1457 keyseq.curmap = toplevel_keymap.get();
1458 cancel_meta_seq.stdmap = toplevel_keymap.get();
1459 cancel_meta_seq.curmap = toplevel_keymap.get();
1463 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1465 string initpath = lyxrc.document_path;
1466 string filename(name);
1468 if (view()->available()) {
1469 string const trypath = owner->buffer()->filePath();
1470 // If directory is writeable, use this as default.
1471 if (IsDirWriteable(trypath))
1475 static int newfile_number;
1477 if (filename.empty()) {
1478 filename = AddName(lyxrc.document_path,
1479 "newfile" + tostr(++newfile_number) + ".lyx");
1480 FileInfo fi(filename);
1481 while (bufferlist.exists(filename) || fi.readable()) {
1483 filename = AddName(lyxrc.document_path,
1484 "newfile" + tostr(newfile_number) +
1486 fi.newFile(filename);
1490 // The template stuff
1493 FileDialog fileDlg(_("Select template file"),
1494 LFUN_SELECT_FILE_SYNC,
1495 make_pair(string(_("Documents|#o#O")),
1496 string(lyxrc.document_path)),
1497 make_pair(string(_("Templates|#T#t")),
1498 string(lyxrc.template_path)));
1500 FileDialog::Result result =
1501 fileDlg.open(lyxrc.template_path,
1502 FileFilterList(_("LyX Documents (*.lyx)")),
1505 if (result.first == FileDialog::Later)
1507 if (result.second.empty())
1509 templname = result.second;
1512 view()->newFile(filename, templname, !name.empty());
1516 void LyXFunc::open(string const & fname)
1518 string initpath = lyxrc.document_path;
1520 if (view()->available()) {
1521 string const trypath = owner->buffer()->filePath();
1522 // If directory is writeable, use this as default.
1523 if (IsDirWriteable(trypath))
1529 if (fname.empty()) {
1530 FileDialog fileDlg(_("Select document to open"),
1532 make_pair(string(_("Documents|#o#O")),
1533 string(lyxrc.document_path)),
1534 make_pair(string(_("Examples|#E#e")),
1535 string(AddPath(system_lyxdir(), "examples"))));
1537 FileDialog::Result result =
1538 fileDlg.open(initpath,
1539 FileFilterList(_("LyX Documents (*.lyx)")),
1542 if (result.first == FileDialog::Later)
1545 filename = result.second;
1547 // check selected filename
1548 if (filename.empty()) {
1549 owner->message(_("Canceled."));
1555 // get absolute path of file and add ".lyx" to the filename if
1557 string const fullpath = FileSearch(string(), filename, "lyx");
1558 if (!fullpath.empty()) {
1559 filename = fullpath;
1562 string const disp_fn(MakeDisplayPath(filename));
1564 // if the file doesn't exist, let the user create one
1565 FileInfo const f(filename, true);
1567 // the user specifically chose this name. Believe them.
1568 view()->newFile(filename, "", true);
1572 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1575 if (view()->loadLyXFile(filename)) {
1576 str2 = bformat(_("Document %1$s opened."), disp_fn);
1578 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1580 owner->message(str2);
1584 void LyXFunc::doImport(string const & argument)
1587 string filename = split(argument, format, ' ');
1589 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1590 << " file: " << filename << endl;
1592 // need user interaction
1593 if (filename.empty()) {
1594 string initpath = lyxrc.document_path;
1596 if (view()->available()) {
1597 string const trypath = owner->buffer()->filePath();
1598 // If directory is writeable, use this as default.
1599 if (IsDirWriteable(trypath))
1603 string const text = bformat(_("Select %1$s file to import"),
1604 formats.prettyName(format));
1606 FileDialog fileDlg(text,
1608 make_pair(string(_("Documents|#o#O")),
1609 string(lyxrc.document_path)),
1610 make_pair(string(_("Examples|#E#e")),
1611 string(AddPath(system_lyxdir(), "examples"))));
1613 string const filter = formats.prettyName(format)
1614 + " (*." + formats.extension(format) + ')';
1616 FileDialog::Result result =
1617 fileDlg.open(initpath,
1618 FileFilterList(filter),
1621 if (result.first == FileDialog::Later)
1624 filename = result.second;
1626 // check selected filename
1627 if (filename.empty())
1628 owner->message(_("Canceled."));
1631 if (filename.empty())
1634 // get absolute path of file
1635 filename = MakeAbsPath(filename);
1637 string const lyxfile = ChangeExtension(filename, ".lyx");
1639 // Check if the document already is open
1640 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1641 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1642 owner->message(_("Canceled."));
1647 // if the file exists already, and we didn't do
1648 // -i lyx thefile.lyx, warn
1649 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1650 string const file = MakeDisplayPath(lyxfile, 30);
1652 string text = bformat(_("The document %1$s already exists.\n\n"
1653 "Do you want to over-write that document?"), file);
1654 int const ret = Alert::prompt(_("Over-write document?"),
1655 text, 0, 1, _("&Over-write"), _("&Cancel"));
1658 owner->message(_("Canceled."));
1663 Importer::Import(owner, filename, format);
1667 void LyXFunc::closeBuffer()
1669 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1670 if (bufferlist.empty()) {
1671 // need this otherwise SEGV may occur while
1672 // trying to set variables that don't exist
1673 // since there's no current buffer
1674 owner->getDialogs().hideBufferDependent();
1676 view()->setBuffer(bufferlist.first());
1682 // Each "owner" should have it's own message method. lyxview and
1683 // the minibuffer would use the minibuffer, but lyxserver would
1684 // send an ERROR signal to its client. Alejandro 970603
1685 // This function is bit problematic when it comes to NLS, to make the
1686 // lyx servers client be language indepenent we must not translate
1687 // strings sent to this func.
1688 void LyXFunc::setErrorMessage(string const & m) const
1690 dispatch_buffer = m;
1695 void LyXFunc::setMessage(string const & m) const
1697 dispatch_buffer = m;
1701 void LyXFunc::setStatusMessage(string const & m) const
1707 string const LyXFunc::viewStatusMessage()
1709 // When meta-fake key is pressed, show the key sequence so far + "M-".
1711 return keyseq.print() + "M-";
1713 // Else, when a non-complete key sequence is pressed,
1714 // show the available options.
1715 if (keyseq.length() > 0 && !keyseq.deleted())
1716 return keyseq.printOptions();
1718 if (!view()->available())
1719 return _("Welcome to LyX!");
1721 return view()->cursor().currentState();
1725 BufferView * LyXFunc::view() const
1727 BOOST_ASSERT(owner);
1728 return owner->view().get();
1732 bool LyXFunc::wasMetaKey() const
1734 return (meta_fake_bit != key_modifier::none);