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/Toolbar.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())
331 case LFUN_TRACK_CHANGES:
332 flag.setOnOff(buf->params().tracking_changes);
336 enable = cmd.argument == "custom"
337 || Exporter::IsExportable(*buf, cmd.argument);
340 enable = !buf->undostack().empty();
343 enable = !buf->redostack().empty();
347 enable = cur.selection();
351 enable = buf->isLatex() && lyxrc.chktex_command != "none";
355 enable = Exporter::IsExportable(*buf, "program");
358 case LFUN_LAYOUT_TABULAR:
359 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
363 case LFUN_LAYOUT_PARAGRAPH:
364 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
367 case LFUN_VC_REGISTER:
368 enable = !buf->lyxvc().inUse();
370 case LFUN_VC_CHECKIN:
371 enable = buf->lyxvc().inUse() && !buf->isReadonly();
373 case LFUN_VC_CHECKOUT:
374 enable = buf->lyxvc().inUse() && buf->isReadonly();
378 enable = buf->lyxvc().inUse();
380 case LFUN_MENURELOAD:
381 enable = !buf->isUnnamed() && !buf->isClean();
383 case LFUN_BOOKMARK_GOTO:
384 enable = view()->isSavedPosition(strToUnsignedInt(cmd.argument));
387 case LFUN_MERGE_CHANGES:
388 case LFUN_ACCEPT_CHANGE:
389 case LFUN_REJECT_CHANGE:
390 case LFUN_ACCEPT_ALL_CHANGES:
391 case LFUN_REJECT_ALL_CHANGES:
392 enable = buf && buf->params().tracking_changes;
395 case LFUN_INSET_SETTINGS: {
399 UpdatableInset * inset = cur.inset().asUpdatableInset();
400 lyxerr << "inset: " << inset << endl;
404 InsetOld::Code code = inset->lyxCode();
406 case InsetOld::TABULAR_CODE:
407 enable = cmd.argument == "tabular";
409 case InsetOld::ERT_CODE:
410 enable = cmd.argument == "ert";
412 case InsetOld::FLOAT_CODE:
413 enable = cmd.argument == "float";
415 case InsetOld::WRAP_CODE:
416 enable = cmd.argument == "wrap";
418 case InsetOld::NOTE_CODE:
419 enable = cmd.argument == "note";
421 case InsetOld::BRANCH_CODE:
422 enable = cmd.argument == "branch";
424 case InsetOld::BOX_CODE:
425 enable = cmd.argument == "box";
433 case LFUN_DIALOG_SHOW: {
434 string const name = cmd.getArg(0);
436 enable = name == "aboutlyx"
440 || name == "texinfo";
441 else if (name == "print")
442 enable = Exporter::IsExportable(*buf, "dvi")
443 && lyxrc.print_command != "none";
444 else if (name == "character")
445 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
446 else if (name == "vclog")
447 enable = buf->lyxvc().inUse();
448 else if (name == "latexlog")
449 enable = IsFileReadable(buf->getLogName().second);
454 case LFUN_MENUNEWTMPLT:
455 case LFUN_WORDFINDFORWARD:
456 case LFUN_WORDFINDBACKWARD:
458 case LFUN_EXEC_COMMAND:
461 case LFUN_CLOSEBUFFER:
470 case LFUN_RECONFIGURE:
474 case LFUN_DROP_LAYOUTS_CHOICE:
475 case LFUN_MENU_OPEN_BY_NAME:
478 case LFUN_GOTOFILEROW:
479 case LFUN_GOTO_PARAGRAPH:
480 case LFUN_DIALOG_SHOW_NEW_INSET:
481 case LFUN_DIALOG_SHOW_NEXT_INSET:
482 case LFUN_DIALOG_UPDATE:
483 case LFUN_DIALOG_HIDE:
484 case LFUN_DIALOG_DISCONNECT_INSET:
486 case LFUN_TOGGLECURSORFOLLOW:
490 case LFUN_KMAP_TOGGLE:
492 case LFUN_EXPORT_CUSTOM:
495 case LFUN_SAVEPREFERENCES:
496 case LFUN_SCREEN_FONT_UPDATE:
499 case LFUN_EXTERNAL_EDIT:
500 case LFUN_FILE_INSERT:
501 case LFUN_FILE_INSERT_ASCII:
502 case LFUN_FILE_INSERT_ASCII_PARA:
503 case LFUN_ALL_INSETS_TOGGLE:
504 case LFUN_LANGUAGE_BUFFER:
505 case LFUN_TEXTCLASS_APPLY:
506 case LFUN_TEXTCLASS_LOAD:
507 case LFUN_SAVE_AS_DEFAULT:
508 case LFUN_BUFFERPARAMS_APPLY:
509 case LFUN_LYXRC_APPLY:
511 case LFUN_WORD_REPLACE:
512 // these are handled in our dispatch()
516 cur.getStatus(cmd, flag);
522 // Can we use a readonly buffer?
523 if (buf && buf->isReadonly()
524 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
525 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
526 setStatusMessage(N_("Document is read-only"));
536 bool ensureBufferClean(BufferView * bv)
538 Buffer & buf = *bv->buffer();
542 string const file = MakeDisplayPath(buf.fileName(), 30);
543 string text = bformat(_("The document %1$s has unsaved "
544 "changes.\n\nDo you want to save "
545 "the document?"), file);
546 int const ret = Alert::prompt(_("Save changed document?"),
547 text, 0, 1, _("&Save"),
551 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
553 return buf.isClean();
557 void showPrintError(string const & name)
559 string str = bformat(_("Could not print the document %1$s.\n"
560 "Check that your printer is set up correctly."),
561 MakeDisplayPath(name, 50));
562 Alert::error(_("Print document failed"), str);
566 void loadTextclass(string const & name)
568 std::pair<bool, lyx::textclass_type> const tc_pair =
569 textclasslist.NumberOfClass(name);
571 if (!tc_pair.first) {
572 lyxerr << "Document class \"" << name
573 << "\" does not exist."
578 lyx::textclass_type const tc = tc_pair.second;
580 if (!textclasslist[tc].load()) {
581 string s = bformat(_("The document could not be converted\n"
582 "into the document class %1$s."),
583 textclasslist[tc].name());
584 Alert::error(_("Could not change class"), s);
591 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
593 string const argument = cmd.argument;
594 kb_action const action = cmd.action;
596 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
597 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
599 // we have not done anything wrong yet.
601 dispatch_buffer.erase();
602 selection_possible = false;
604 // We cannot use this function here
605 if (!getStatus(cmd).enabled()) {
606 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
607 << lyxaction.getActionName(action)
608 << " [" << action << "] is disabled at this location"
610 setErrorMessage(getStatusMessage());
614 if (view()->available())
615 view()->hideCursor();
619 case LFUN_WORDFINDFORWARD:
620 case LFUN_WORDFINDBACKWARD: {
621 static string last_search;
622 string searched_string;
624 if (!argument.empty()) {
625 last_search = argument;
626 searched_string = argument;
628 searched_string = last_search;
631 if (searched_string.empty())
634 bool const fw = action == LFUN_WORDFINDFORWARD;
636 lyx::find::find2string(searched_string, true, false, fw);
637 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
642 owner->message(keyseq.printOptions());
645 case LFUN_EXEC_COMMAND:
646 owner->focus_command_buffer();
651 meta_fake_bit = key_modifier::none;
652 if (view()->available())
653 // cancel any selection
654 dispatch(FuncRequest(LFUN_MARK_OFF));
655 setMessage(N_("Cancel"));
659 meta_fake_bit = key_modifier::alt;
660 setMessage(keyseq.print());
663 case LFUN_READ_ONLY_TOGGLE:
664 if (owner->buffer()->lyxvc().inUse())
665 owner->buffer()->lyxvc().toggleReadOnly();
667 owner->buffer()->setReadonly(
668 !owner->buffer()->isReadonly());
671 // --- Menus -----------------------------------------------
673 menuNew(argument, false);
676 case LFUN_MENUNEWTMPLT:
677 menuNew(argument, true);
680 case LFUN_CLOSEBUFFER:
685 if (!owner->buffer()->isUnnamed()) {
686 string const str = bformat(_("Saving document %1$s..."),
687 MakeDisplayPath(owner->buffer()->fileName()));
689 MenuWrite(owner->buffer());
690 owner->message(str + _(" done."));
692 WriteAs(owner->buffer());
696 WriteAs(owner->buffer(), argument);
699 case LFUN_MENURELOAD: {
700 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
701 string text = bformat(_("Any changes will be lost. Are you sure "
702 "you want to revert to the saved version of the document %1$s?"), file);
703 int const ret = Alert::prompt(_("Revert to saved document?"),
704 text, 0, 1, _("&Revert"), _("&Cancel"));
712 Exporter::Export(owner->buffer(), argument, true);
713 view()->showErrorList(BufferFormat(*owner->buffer()));
717 Exporter::Preview(owner->buffer(), argument);
718 view()->showErrorList(BufferFormat(*owner->buffer()));
722 Exporter::Export(owner->buffer(), "program", true);
723 view()->showErrorList(_("Build"));
727 owner->buffer()->runChktex();
728 view()->showErrorList(_("ChkTeX"));
732 if (argument == "custom")
733 owner->getDialogs().show("sendto");
735 Exporter::Export(owner->buffer(), argument, false);
736 view()->showErrorList(BufferFormat(*owner->buffer()));
740 case LFUN_EXPORT_CUSTOM: {
742 string command = split(argument, format_name, ' ');
743 Format const * format = formats.getFormat(format_name);
745 lyxerr << "Format \"" << format_name
746 << "\" not recognized!"
751 Buffer * buffer = owner->buffer();
753 // The name of the file created by the conversion process
756 // Output to filename
757 if (format->name() == "lyx") {
758 string const latexname =
759 buffer->getLatexName(false);
760 filename = ChangeExtension(latexname,
761 format->extension());
762 filename = AddName(buffer->temppath(), filename);
764 if (!buffer->writeFile(filename))
768 Exporter::Export(buffer, format_name, true,
772 // Substitute $$FName for filename
773 if (!contains(command, "$$FName"))
774 command = "( " + command + " ) < $$FName";
775 command = subst(command, "$$FName", filename);
777 // Execute the command in the background
779 call.startscript(Systemcall::DontWait, command);
786 string command = split(split(argument, target, ' '),
790 || target_name.empty()
791 || command.empty()) {
792 lyxerr << "Unable to parse \""
793 << argument << '"' << std::endl;
796 if (target != "printer" && target != "file") {
797 lyxerr << "Unrecognized target \""
798 << target << '"' << std::endl;
802 Buffer * buffer = owner->buffer();
804 if (!Exporter::Export(buffer, "dvi", true)) {
805 showPrintError(buffer->fileName());
809 // Push directory path.
810 string const path = buffer->temppath();
813 // there are three cases here:
814 // 1. we print to a file
815 // 2. we print directly to a printer
816 // 3. we print using a spool command (print to file first)
819 string const dviname =
820 ChangeExtension(buffer->getLatexName(true),
823 if (target == "printer") {
824 if (!lyxrc.print_spool_command.empty()) {
825 // case 3: print using a spool
826 string const psname =
827 ChangeExtension(dviname,".ps");
828 command += lyxrc.print_to_file
831 + QuoteName(dviname);
834 lyxrc.print_spool_command +' ';
835 if (target_name != "default") {
836 command2 += lyxrc.print_spool_printerprefix
840 command2 += QuoteName(psname);
842 // If successful, then spool command
843 res = one.startscript(
848 res = one.startscript(
849 Systemcall::DontWait,
852 // case 2: print directly to a printer
853 res = one.startscript(
854 Systemcall::DontWait,
855 command + QuoteName(dviname));
859 // case 1: print to a file
860 command += lyxrc.print_to_file
861 + QuoteName(MakeAbsPath(target_name,
864 + QuoteName(dviname);
865 res = one.startscript(Systemcall::DontWait,
870 showPrintError(buffer->fileName());
883 InsetCommandParams p("tableofcontents");
884 string const data = InsetCommandMailer::params2string("toc", p);
885 owner->getDialogs().show("toc", data, 0);
893 case LFUN_RECONFIGURE:
897 case LFUN_HELP_OPEN: {
898 string const arg = argument;
900 setErrorMessage(N_("Missing argument"));
903 string const fname = i18nLibFileSearch("doc", arg, "lyx");
905 lyxerr << "LyX: unable to find documentation file `"
906 << arg << "'. Bad installation?" << endl;
909 owner->message(bformat(_("Opening help file %1$s..."),
910 MakeDisplayPath(fname)));
911 view()->loadLyXFile(fname, false);
915 // --- version control -------------------------------
916 case LFUN_VC_REGISTER:
917 if (!ensureBufferClean(view()))
919 if (!owner->buffer()->lyxvc().inUse()) {
920 owner->buffer()->lyxvc().registrer();
925 case LFUN_VC_CHECKIN:
926 if (!ensureBufferClean(view()))
928 if (owner->buffer()->lyxvc().inUse()
929 && !owner->buffer()->isReadonly()) {
930 owner->buffer()->lyxvc().checkIn();
935 case LFUN_VC_CHECKOUT:
936 if (!ensureBufferClean(view()))
938 if (owner->buffer()->lyxvc().inUse()
939 && owner->buffer()->isReadonly()) {
940 owner->buffer()->lyxvc().checkOut();
946 owner->buffer()->lyxvc().revert();
951 owner->buffer()->lyxvc().undoLast();
955 // --- buffers ----------------------------------------
956 case LFUN_SWITCHBUFFER:
957 view()->setBuffer(bufferlist.getBuffer(argument));
961 NewFile(view(), argument);
968 case LFUN_DROP_LAYOUTS_CHOICE:
969 owner->getToolbar().openLayoutList();
972 case LFUN_MENU_OPEN_BY_NAME:
973 owner->getMenubar().openByName(argument);
976 // --- lyxserver commands ----------------------------
978 setMessage(owner->buffer()->fileName());
979 lyxerr[Debug::INFO] << "FNAME["
980 << owner->buffer()->fileName()
985 dispatch_buffer = keyseq.print();
986 lyxserver->notifyClient(dispatch_buffer);
989 case LFUN_GOTOFILEROW: {
992 istringstream is(argument);
993 is >> file_name >> row;
994 if (prefixIs(file_name, getTmpDir())) {
995 // Needed by inverse dvi search. If it is a file
996 // in tmpdir, call the apropriated function
997 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
999 // Must replace extension of the file to be .lyx
1000 // and get full path
1001 string const s = ChangeExtension(file_name, ".lyx");
1002 // Either change buffer or load the file
1003 if (bufferlist.exists(s)) {
1004 view()->setBuffer(bufferlist.getBuffer(s));
1006 view()->loadLyXFile(s);
1010 view()->setCursorFromRow(row);
1013 // see BufferView_pimpl::center()
1014 view()->updateScrollbar();
1018 case LFUN_GOTO_PARAGRAPH: {
1019 istringstream is(argument);
1022 ParIterator par = owner->buffer()->getParFromID(id);
1023 if (par == owner->buffer()->par_iterator_end()) {
1024 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1025 << id << ']' << endl;
1028 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1029 << " found." << endl;
1033 view()->setCursor(par, 0);
1035 view()->switchKeyMap();
1036 owner->view_state_changed();
1039 // see BufferView_pimpl::center()
1040 view()->updateScrollbar();
1044 case LFUN_DIALOG_SHOW: {
1045 string const name = cmd.getArg(0);
1046 string data = trim(cmd.argument.substr(name.size()));
1048 if (name == "character") {
1049 data = freefont2string();
1051 owner->getDialogs().show("character", data);
1054 else if (name == "latexlog") {
1055 pair<Buffer::LogType, string> const logfile =
1056 owner->buffer()->getLogName();
1057 switch (logfile.first) {
1058 case Buffer::latexlog:
1061 case Buffer::buildlog:
1065 data += logfile.second;
1066 owner->getDialogs().show("log", data);
1068 else if (name == "vclog") {
1069 string const data = "vc " +
1070 owner->buffer()->lyxvc().getLogFile();
1071 owner->getDialogs().show("log", data);
1074 owner->getDialogs().show(name, data);
1078 case LFUN_DIALOG_SHOW_NEW_INSET: {
1079 string const name = cmd.getArg(0);
1080 string data = trim(cmd.argument.substr(name.size()));
1081 if (name == "bibitem" ||
1083 name == "include" ||
1089 InsetCommandParams p(name);
1090 data = InsetCommandMailer::params2string(name, p);
1091 } else if (name == "box") {
1092 // \c data == "Boxed" || "Frameless" etc
1093 InsetBoxParams p(data);
1094 data = InsetBoxMailer::params2string(p);
1095 } else if (name == "branch") {
1096 InsetBranchParams p;
1097 data = InsetBranchMailer::params2string(p);
1098 } else if (name == "citation") {
1099 InsetCommandParams p("cite");
1100 data = InsetCommandMailer::params2string(name, p);
1101 } else if (name == "ert") {
1102 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1103 } else if (name == "external") {
1104 InsetExternalParams p;
1105 Buffer const & buffer = *owner->buffer();
1106 data = InsetExternalMailer::params2string(p, buffer);
1107 } else if (name == "float") {
1109 data = InsetFloatMailer::params2string(p);
1110 } else if (name == "graphics") {
1111 InsetGraphicsParams p;
1112 Buffer const & buffer = *owner->buffer();
1113 data = InsetGraphicsMailer::params2string(p, buffer);
1114 } else if (name == "note") {
1116 data = InsetNoteMailer::params2string(p);
1117 } else if (name == "vspace") {
1119 data = InsetVSpaceMailer::params2string(space);
1120 } else if (name == "wrap") {
1122 data = InsetWrapMailer::params2string(p);
1124 owner->getDialogs().show(name, data, 0);
1128 case LFUN_DIALOG_SHOW_NEXT_INSET:
1131 case LFUN_DIALOG_UPDATE: {
1132 string const & name = argument;
1133 // Can only update a dialog connected to an existing inset
1134 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1136 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1137 inset->dispatch(view()->cursor(), fr);
1138 } else if (name == "paragraph") {
1139 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1144 case LFUN_DIALOG_HIDE:
1145 Dialogs::hide(argument, 0);
1148 case LFUN_DIALOG_DISCONNECT_INSET:
1149 owner->getDialogs().disconnect(argument);
1152 case LFUN_CHILDOPEN: {
1153 string const filename =
1154 MakeAbsPath(argument, owner->buffer()->filePath());
1155 setMessage(N_("Opening child document ") +
1156 MakeDisplayPath(filename) + "...");
1157 view()->savePosition(0);
1158 string const parentfilename = owner->buffer()->fileName();
1159 if (bufferlist.exists(filename))
1160 view()->setBuffer(bufferlist.getBuffer(filename));
1162 view()->loadLyXFile(filename);
1163 // Set the parent name of the child document.
1164 // This makes insertion of citations and references in the child work,
1165 // when the target is in the parent or another child document.
1166 owner->buffer()->setParentName(parentfilename);
1170 case LFUN_TOGGLECURSORFOLLOW:
1171 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1175 owner->getIntl().KeyMapOn(false);
1178 case LFUN_KMAP_PRIM:
1179 owner->getIntl().KeyMapPrim();
1183 owner->getIntl().KeyMapSec();
1186 case LFUN_KMAP_TOGGLE:
1187 owner->getIntl().ToggleKeyMap();
1193 string rest = split(argument, countstr, ' ');
1194 istringstream is(countstr);
1197 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1198 for (int i = 0; i < count; ++i)
1199 dispatch(lyxaction.lookupFunc(rest));
1204 // argument contains ';'-terminated commands
1205 while (!argument.empty()) {
1207 string rest = split(argument, first, ';');
1208 dispatch(lyxaction.lookupFunc(rest));
1212 case LFUN_SAVEPREFERENCES: {
1213 Path p(user_lyxdir());
1214 lyxrc.write("preferences");
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_BREAKLINE: {
1275 #warning swallow 'Return' if the minibuffer is focused. But how?
1279 case LFUN_ALL_INSETS_TOGGLE: {
1281 string const name = split(argument, action, ' ');
1282 InsetBase::Code const inset_code =
1283 InsetBase::translate(name);
1285 LCursor & cur = view()->cursor();
1286 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1288 InsetBase & inset = owner->buffer()->inset();
1289 InsetIterator it = inset_iterator_begin(inset);
1290 InsetIterator const end = inset_iterator_end(inset);
1291 for (; it != end; ++it) {
1292 if (inset_code == InsetBase::NO_CODE
1293 || inset_code == it->lyxCode())
1294 it->dispatch(cur, fr);
1299 case LFUN_LANGUAGE_BUFFER: {
1300 Buffer & buffer = *owner->buffer();
1301 Language const * oldL = buffer.params().language;
1302 Language const * newL = languages.getLanguage(argument);
1303 if (!newL || oldL == newL)
1306 if (oldL->RightToLeft() == newL->RightToLeft()
1307 && !buffer.isMultiLingual())
1308 buffer.changeLanguage(oldL, newL);
1310 buffer.updateDocLang(newL);
1314 case LFUN_BUFFERPARAMS_APPLY: {
1315 istringstream ss(argument);
1318 int const unknown_tokens =
1319 owner->buffer()->readHeader(lex);
1321 if (unknown_tokens != 0) {
1322 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1323 << unknown_tokens << " unknown token"
1324 << (unknown_tokens == 1 ? "" : "s")
1330 case LFUN_TEXTCLASS_APPLY: {
1331 Buffer * buffer = owner->buffer();
1333 lyx::textclass_type const old_class =
1334 buffer->params().textclass;
1336 loadTextclass(argument);
1338 std::pair<bool, lyx::textclass_type> const tc_pair =
1339 textclasslist.NumberOfClass(argument);
1344 lyx::textclass_type const new_class = tc_pair.second;
1345 if (old_class == new_class)
1349 owner->message(_("Converting document to new document class..."));
1351 lyx::cap::SwitchLayoutsBetweenClasses(
1352 old_class, new_class,
1353 buffer->paragraphs(), el);
1355 bufferErrors(*buffer, el);
1356 view()->showErrorList(_("Class switch"));
1360 case LFUN_TEXTCLASS_LOAD:
1361 loadTextclass(argument);
1364 case LFUN_LYXRC_APPLY: {
1365 istringstream ss(argument);
1366 bool const success = lyxrc.read(ss) == 0;
1369 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1370 << "Unable to read lyxrc data"
1377 DispatchResult res = view()->cursor().dispatch(cmd);
1378 if (!res.dispatched());
1379 view()->dispatch(cmd);
1384 if (view()->available()) {
1385 view()->fitCursor();
1387 view()->cursor().updatePos();
1388 // if we executed a mutating lfun, mark the buffer as dirty
1389 if (getStatus(cmd).enabled()
1390 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1391 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1392 view()->buffer()->markDirty();
1395 if (view()->cursor().inTexted()) {
1396 view()->owner()->updateLayoutChoice();
1397 sendDispatchMessage(getMessage(), cmd, verbose);
1403 void LyXFunc::sendDispatchMessage(string const & msg,
1404 FuncRequest const & cmd, bool verbose)
1406 owner->updateMenubar();
1407 owner->updateToolbar();
1409 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1410 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1412 owner->message(msg);
1416 string dispatch_msg = msg;
1417 if (!dispatch_msg.empty())
1418 dispatch_msg += ' ';
1420 string comname = lyxaction.getActionName(cmd.action);
1422 bool argsadded = false;
1424 if (!cmd.argument.empty()) {
1425 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1426 comname += ' ' + cmd.argument;
1431 string const shortcuts = toplevel_keymap->findbinding(cmd);
1433 if (!shortcuts.empty()) {
1434 comname += ": " + shortcuts;
1435 } else if (!argsadded && !cmd.argument.empty()) {
1436 comname += ' ' + cmd.argument;
1439 if (!comname.empty()) {
1440 comname = rtrim(comname);
1441 dispatch_msg += '(' + comname + ')';
1444 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1445 if (!dispatch_msg.empty())
1446 owner->message(dispatch_msg);
1450 void LyXFunc::setupLocalKeymap()
1452 keyseq.stdmap = toplevel_keymap.get();
1453 keyseq.curmap = toplevel_keymap.get();
1454 cancel_meta_seq.stdmap = toplevel_keymap.get();
1455 cancel_meta_seq.curmap = toplevel_keymap.get();
1459 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1461 string initpath = lyxrc.document_path;
1462 string filename(name);
1464 if (view()->available()) {
1465 string const trypath = owner->buffer()->filePath();
1466 // If directory is writeable, use this as default.
1467 if (IsDirWriteable(trypath))
1471 static int newfile_number;
1473 if (filename.empty()) {
1474 filename = AddName(lyxrc.document_path,
1475 "newfile" + tostr(++newfile_number) + ".lyx");
1476 FileInfo fi(filename);
1477 while (bufferlist.exists(filename) || fi.readable()) {
1479 filename = AddName(lyxrc.document_path,
1480 "newfile" + tostr(newfile_number) +
1482 fi.newFile(filename);
1486 // The template stuff
1489 FileDialog fileDlg(_("Select template file"),
1490 LFUN_SELECT_FILE_SYNC,
1491 make_pair(string(_("Documents|#o#O")),
1492 string(lyxrc.document_path)),
1493 make_pair(string(_("Templates|#T#t")),
1494 string(lyxrc.template_path)));
1496 FileDialog::Result result =
1497 fileDlg.open(lyxrc.template_path,
1498 FileFilterList(_("LyX Documents (*.lyx)")),
1501 if (result.first == FileDialog::Later)
1503 if (result.second.empty())
1505 templname = result.second;
1508 view()->newFile(filename, templname, !name.empty());
1512 void LyXFunc::open(string const & fname)
1514 string initpath = lyxrc.document_path;
1516 if (view()->available()) {
1517 string const trypath = owner->buffer()->filePath();
1518 // If directory is writeable, use this as default.
1519 if (IsDirWriteable(trypath))
1525 if (fname.empty()) {
1526 FileDialog fileDlg(_("Select document to open"),
1528 make_pair(string(_("Documents|#o#O")),
1529 string(lyxrc.document_path)),
1530 make_pair(string(_("Examples|#E#e")),
1531 string(AddPath(system_lyxdir(), "examples"))));
1533 FileDialog::Result result =
1534 fileDlg.open(initpath,
1535 FileFilterList(_("LyX Documents (*.lyx)")),
1538 if (result.first == FileDialog::Later)
1541 filename = result.second;
1543 // check selected filename
1544 if (filename.empty()) {
1545 owner->message(_("Canceled."));
1551 // get absolute path of file and add ".lyx" to the filename if
1553 string const fullpath = FileSearch(string(), filename, "lyx");
1554 if (!fullpath.empty()) {
1555 filename = fullpath;
1558 string const disp_fn(MakeDisplayPath(filename));
1560 // if the file doesn't exist, let the user create one
1561 FileInfo const f(filename, true);
1563 // the user specifically chose this name. Believe them.
1564 view()->newFile(filename, "", true);
1568 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1571 if (view()->loadLyXFile(filename)) {
1572 str2 = bformat(_("Document %1$s opened."), disp_fn);
1574 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1576 owner->message(str2);
1580 void LyXFunc::doImport(string const & argument)
1583 string filename = split(argument, format, ' ');
1585 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1586 << " file: " << filename << endl;
1588 // need user interaction
1589 if (filename.empty()) {
1590 string initpath = lyxrc.document_path;
1592 if (view()->available()) {
1593 string const trypath = owner->buffer()->filePath();
1594 // If directory is writeable, use this as default.
1595 if (IsDirWriteable(trypath))
1599 string const text = bformat(_("Select %1$s file to import"),
1600 formats.prettyName(format));
1602 FileDialog fileDlg(text,
1604 make_pair(string(_("Documents|#o#O")),
1605 string(lyxrc.document_path)),
1606 make_pair(string(_("Examples|#E#e")),
1607 string(AddPath(system_lyxdir(), "examples"))));
1609 string const filter = formats.prettyName(format)
1610 + " (*." + formats.extension(format) + ')';
1612 FileDialog::Result result =
1613 fileDlg.open(initpath,
1614 FileFilterList(filter),
1617 if (result.first == FileDialog::Later)
1620 filename = result.second;
1622 // check selected filename
1623 if (filename.empty())
1624 owner->message(_("Canceled."));
1627 if (filename.empty())
1630 // get absolute path of file
1631 filename = MakeAbsPath(filename);
1633 string const lyxfile = ChangeExtension(filename, ".lyx");
1635 // Check if the document already is open
1636 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1637 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1638 owner->message(_("Canceled."));
1643 // if the file exists already, and we didn't do
1644 // -i lyx thefile.lyx, warn
1645 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1646 string const file = MakeDisplayPath(lyxfile, 30);
1648 string text = bformat(_("The document %1$s already exists.\n\n"
1649 "Do you want to over-write that document?"), file);
1650 int const ret = Alert::prompt(_("Over-write document?"),
1651 text, 0, 1, _("&Over-write"), _("&Cancel"));
1654 owner->message(_("Canceled."));
1659 Importer::Import(owner, filename, format);
1663 void LyXFunc::closeBuffer()
1665 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1666 if (bufferlist.empty()) {
1667 // need this otherwise SEGV may occur while
1668 // trying to set variables that don't exist
1669 // since there's no current buffer
1670 owner->getDialogs().hideBufferDependent();
1672 view()->setBuffer(bufferlist.first());
1678 // Each "owner" should have it's own message method. lyxview and
1679 // the minibuffer would use the minibuffer, but lyxserver would
1680 // send an ERROR signal to its client. Alejandro 970603
1681 // This function is bit problematic when it comes to NLS, to make the
1682 // lyx servers client be language indepenent we must not translate
1683 // strings sent to this func.
1684 void LyXFunc::setErrorMessage(string const & m) const
1686 dispatch_buffer = m;
1691 void LyXFunc::setMessage(string const & m) const
1693 dispatch_buffer = m;
1697 void LyXFunc::setStatusMessage(string const & m) const
1703 string const LyXFunc::viewStatusMessage()
1705 // When meta-fake key is pressed, show the key sequence so far + "M-".
1707 return keyseq.print() + "M-";
1709 // Else, when a non-complete key sequence is pressed,
1710 // show the available options.
1711 if (keyseq.length() > 0 && !keyseq.deleted())
1712 return keyseq.printOptions();
1714 if (!view()->available())
1715 return _("Welcome to LyX!");
1717 return view()->cursor().currentState();
1721 BufferView * LyXFunc::view() const
1723 BOOST_ASSERT(owner);
1724 return owner->view().get();
1728 bool LyXFunc::wasMetaKey() const
1730 return (meta_fake_bit != key_modifier::none);