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 // these are handled in our dispatch()
515 cur.getStatus(cmd, flag);
521 // Can we use a readonly buffer?
522 if (buf && buf->isReadonly()
523 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
524 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
525 setStatusMessage(N_("Document is read-only"));
535 bool ensureBufferClean(BufferView * bv)
537 Buffer & buf = *bv->buffer();
541 string const file = MakeDisplayPath(buf.fileName(), 30);
542 string text = bformat(_("The document %1$s has unsaved "
543 "changes.\n\nDo you want to save "
544 "the document?"), file);
545 int const ret = Alert::prompt(_("Save changed document?"),
546 text, 0, 1, _("&Save"),
550 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
552 return buf.isClean();
556 void showPrintError(string const & name)
558 string str = bformat(_("Could not print the document %1$s.\n"
559 "Check that your printer is set up correctly."),
560 MakeDisplayPath(name, 50));
561 Alert::error(_("Print document failed"), str);
565 void loadTextclass(string const & name)
567 std::pair<bool, lyx::textclass_type> const tc_pair =
568 textclasslist.NumberOfClass(name);
570 if (!tc_pair.first) {
571 lyxerr << "Document class \"" << name
572 << "\" does not exist."
577 lyx::textclass_type const tc = tc_pair.second;
579 if (!textclasslist[tc].load()) {
580 string s = bformat(_("The document could not be converted\n"
581 "into the document class %1$s."),
582 textclasslist[tc].name());
583 Alert::error(_("Could not change class"), s);
590 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
592 string const argument = cmd.argument;
593 kb_action const action = cmd.action;
595 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
596 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
598 // we have not done anything wrong yet.
600 dispatch_buffer.erase();
601 selection_possible = false;
603 // We cannot use this function here
604 if (!getStatus(cmd).enabled()) {
605 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
606 << lyxaction.getActionName(action)
607 << " [" << action << "] is disabled at this location"
609 setErrorMessage(getStatusMessage());
613 if (view()->available())
614 view()->hideCursor();
618 case LFUN_WORDFINDFORWARD:
619 case LFUN_WORDFINDBACKWARD: {
620 static string last_search;
621 string searched_string;
623 if (!argument.empty()) {
624 last_search = argument;
625 searched_string = argument;
627 searched_string = last_search;
630 if (searched_string.empty())
633 bool const fw = action == LFUN_WORDFINDFORWARD;
635 lyx::find::find2string(searched_string, true, false, fw);
636 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
641 owner->message(keyseq.printOptions());
644 case LFUN_EXEC_COMMAND:
645 owner->focus_command_buffer();
650 meta_fake_bit = key_modifier::none;
651 if (view()->available())
652 // cancel any selection
653 dispatch(FuncRequest(LFUN_MARK_OFF));
654 setMessage(N_("Cancel"));
658 meta_fake_bit = key_modifier::alt;
659 setMessage(keyseq.print());
662 case LFUN_READ_ONLY_TOGGLE:
663 if (owner->buffer()->lyxvc().inUse())
664 owner->buffer()->lyxvc().toggleReadOnly();
666 owner->buffer()->setReadonly(
667 !owner->buffer()->isReadonly());
670 // --- Menus -----------------------------------------------
672 menuNew(argument, false);
675 case LFUN_MENUNEWTMPLT:
676 menuNew(argument, true);
679 case LFUN_CLOSEBUFFER:
684 if (!owner->buffer()->isUnnamed()) {
685 string const str = bformat(_("Saving document %1$s..."),
686 MakeDisplayPath(owner->buffer()->fileName()));
688 MenuWrite(owner->buffer());
689 owner->message(str + _(" done."));
691 WriteAs(owner->buffer());
695 WriteAs(owner->buffer(), argument);
698 case LFUN_MENURELOAD: {
699 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
700 string text = bformat(_("Any changes will be lost. Are you sure "
701 "you want to revert to the saved version of the document %1$s?"), file);
702 int const ret = Alert::prompt(_("Revert to saved document?"),
703 text, 0, 1, _("&Revert"), _("&Cancel"));
711 Exporter::Export(owner->buffer(), argument, true);
712 view()->showErrorList(BufferFormat(*owner->buffer()));
716 Exporter::Preview(owner->buffer(), argument);
717 view()->showErrorList(BufferFormat(*owner->buffer()));
721 Exporter::Export(owner->buffer(), "program", true);
722 view()->showErrorList(_("Build"));
726 owner->buffer()->runChktex();
727 view()->showErrorList(_("ChkTeX"));
731 if (argument == "custom")
732 owner->getDialogs().show("sendto");
734 Exporter::Export(owner->buffer(), argument, false);
735 view()->showErrorList(BufferFormat(*owner->buffer()));
739 case LFUN_EXPORT_CUSTOM: {
741 string command = split(argument, format_name, ' ');
742 Format const * format = formats.getFormat(format_name);
744 lyxerr << "Format \"" << format_name
745 << "\" not recognized!"
750 Buffer * buffer = owner->buffer();
752 // The name of the file created by the conversion process
755 // Output to filename
756 if (format->name() == "lyx") {
757 string const latexname =
758 buffer->getLatexName(false);
759 filename = ChangeExtension(latexname,
760 format->extension());
761 filename = AddName(buffer->temppath(), filename);
763 if (!buffer->writeFile(filename))
767 Exporter::Export(buffer, format_name, true,
771 // Substitute $$FName for filename
772 if (!contains(command, "$$FName"))
773 command = "( " + command + " ) < $$FName";
774 command = subst(command, "$$FName", filename);
776 // Execute the command in the background
778 call.startscript(Systemcall::DontWait, command);
785 string command = split(split(argument, target, ' '),
789 || target_name.empty()
790 || command.empty()) {
791 lyxerr << "Unable to parse \""
792 << argument << '"' << std::endl;
795 if (target != "printer" && target != "file") {
796 lyxerr << "Unrecognized target \""
797 << target << '"' << std::endl;
801 Buffer * buffer = owner->buffer();
803 if (!Exporter::Export(buffer, "dvi", true)) {
804 showPrintError(buffer->fileName());
808 // Push directory path.
809 string const path = buffer->temppath();
812 // there are three cases here:
813 // 1. we print to a file
814 // 2. we print directly to a printer
815 // 3. we print using a spool command (print to file first)
818 string const dviname =
819 ChangeExtension(buffer->getLatexName(true),
822 if (target == "printer") {
823 if (!lyxrc.print_spool_command.empty()) {
824 // case 3: print using a spool
825 string const psname =
826 ChangeExtension(dviname,".ps");
827 command += lyxrc.print_to_file
830 + QuoteName(dviname);
833 lyxrc.print_spool_command +' ';
834 if (target_name != "default") {
835 command2 += lyxrc.print_spool_printerprefix
839 command2 += QuoteName(psname);
841 // If successful, then spool command
842 res = one.startscript(
847 res = one.startscript(
848 Systemcall::DontWait,
851 // case 2: print directly to a printer
852 res = one.startscript(
853 Systemcall::DontWait,
854 command + QuoteName(dviname));
858 // case 1: print to a file
859 command += lyxrc.print_to_file
860 + QuoteName(MakeAbsPath(target_name,
863 + QuoteName(dviname);
864 res = one.startscript(Systemcall::DontWait,
869 showPrintError(buffer->fileName());
882 InsetCommandParams p("tableofcontents");
883 string const data = InsetCommandMailer::params2string("toc", p);
884 owner->getDialogs().show("toc", data, 0);
892 case LFUN_RECONFIGURE:
896 case LFUN_HELP_OPEN: {
897 string const arg = argument;
899 setErrorMessage(N_("Missing argument"));
902 string const fname = i18nLibFileSearch("doc", arg, "lyx");
904 lyxerr << "LyX: unable to find documentation file `"
905 << arg << "'. Bad installation?" << endl;
908 owner->message(bformat(_("Opening help file %1$s..."),
909 MakeDisplayPath(fname)));
910 view()->loadLyXFile(fname, false);
914 // --- version control -------------------------------
915 case LFUN_VC_REGISTER:
916 if (!ensureBufferClean(view()))
918 if (!owner->buffer()->lyxvc().inUse()) {
919 owner->buffer()->lyxvc().registrer();
924 case LFUN_VC_CHECKIN:
925 if (!ensureBufferClean(view()))
927 if (owner->buffer()->lyxvc().inUse()
928 && !owner->buffer()->isReadonly()) {
929 owner->buffer()->lyxvc().checkIn();
934 case LFUN_VC_CHECKOUT:
935 if (!ensureBufferClean(view()))
937 if (owner->buffer()->lyxvc().inUse()
938 && owner->buffer()->isReadonly()) {
939 owner->buffer()->lyxvc().checkOut();
945 owner->buffer()->lyxvc().revert();
950 owner->buffer()->lyxvc().undoLast();
954 // --- buffers ----------------------------------------
955 case LFUN_SWITCHBUFFER:
956 view()->setBuffer(bufferlist.getBuffer(argument));
960 NewFile(view(), argument);
967 case LFUN_DROP_LAYOUTS_CHOICE:
968 owner->getToolbar().openLayoutList();
971 case LFUN_MENU_OPEN_BY_NAME:
972 owner->getMenubar().openByName(argument);
975 // --- lyxserver commands ----------------------------
977 setMessage(owner->buffer()->fileName());
978 lyxerr[Debug::INFO] << "FNAME["
979 << owner->buffer()->fileName()
984 dispatch_buffer = keyseq.print();
985 lyxserver->notifyClient(dispatch_buffer);
988 case LFUN_GOTOFILEROW: {
991 istringstream is(argument);
992 is >> file_name >> row;
993 if (prefixIs(file_name, getTmpDir())) {
994 // Needed by inverse dvi search. If it is a file
995 // in tmpdir, call the apropriated function
996 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
998 // Must replace extension of the file to be .lyx
1000 string const s = ChangeExtension(file_name, ".lyx");
1001 // Either change buffer or load the file
1002 if (bufferlist.exists(s)) {
1003 view()->setBuffer(bufferlist.getBuffer(s));
1005 view()->loadLyXFile(s);
1009 view()->setCursorFromRow(row);
1012 // see BufferView_pimpl::center()
1013 view()->updateScrollbar();
1017 case LFUN_GOTO_PARAGRAPH: {
1018 istringstream is(argument);
1021 ParIterator par = owner->buffer()->getParFromID(id);
1022 if (par == owner->buffer()->par_iterator_end()) {
1023 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1024 << id << ']' << endl;
1027 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1028 << " found." << endl;
1032 view()->setCursor(par, 0);
1034 view()->switchKeyMap();
1035 owner->view_state_changed();
1038 // see BufferView_pimpl::center()
1039 view()->updateScrollbar();
1043 case LFUN_DIALOG_SHOW: {
1044 string const name = cmd.getArg(0);
1045 string data = trim(cmd.argument.substr(name.size()));
1047 if (name == "character") {
1048 data = freefont2string();
1050 owner->getDialogs().show("character", data);
1052 else if (name == "preamble")
1053 owner->getDialogs().showPreamble();
1054 else if (name == "spellchecker")
1055 owner->getDialogs().showSpellchecker();
1057 else if (name == "latexlog") {
1058 pair<Buffer::LogType, string> const logfile =
1059 owner->buffer()->getLogName();
1060 switch (logfile.first) {
1061 case Buffer::latexlog:
1064 case Buffer::buildlog:
1068 data += logfile.second;
1069 owner->getDialogs().show("log", data);
1071 else if (name == "vclog") {
1072 string const data = "vc " +
1073 owner->buffer()->lyxvc().getLogFile();
1074 owner->getDialogs().show("log", data);
1077 owner->getDialogs().show(name, data);
1081 case LFUN_DIALOG_SHOW_NEW_INSET: {
1082 string const name = cmd.getArg(0);
1083 string data = trim(cmd.argument.substr(name.size()));
1084 if (name == "bibitem" ||
1086 name == "include" ||
1092 InsetCommandParams p(name);
1093 data = InsetCommandMailer::params2string(name, p);
1094 } else if (name == "box") {
1095 // \c data == "Boxed" || "Frameless" etc
1096 InsetBoxParams p(data);
1097 data = InsetBoxMailer::params2string(p);
1098 } else if (name == "branch") {
1099 InsetBranchParams p;
1100 data = InsetBranchMailer::params2string(p);
1101 } else if (name == "citation") {
1102 InsetCommandParams p("cite");
1103 data = InsetCommandMailer::params2string(name, p);
1104 } else if (name == "ert") {
1105 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1106 } else if (name == "external") {
1107 InsetExternalParams p;
1108 Buffer const & buffer = *owner->buffer();
1109 data = InsetExternalMailer::params2string(p, buffer);
1110 } else if (name == "float") {
1112 data = InsetFloatMailer::params2string(p);
1113 } else if (name == "graphics") {
1114 InsetGraphicsParams p;
1115 Buffer const & buffer = *owner->buffer();
1116 data = InsetGraphicsMailer::params2string(p, buffer);
1117 } else if (name == "note") {
1119 data = InsetNoteMailer::params2string(p);
1120 } else if (name == "vspace") {
1122 data = InsetVSpaceMailer::params2string(space);
1123 } else if (name == "wrap") {
1125 data = InsetWrapMailer::params2string(p);
1127 owner->getDialogs().show(name, data, 0);
1131 case LFUN_DIALOG_SHOW_NEXT_INSET:
1134 case LFUN_DIALOG_UPDATE: {
1135 string const & name = argument;
1136 // Can only update a dialog connected to an existing inset
1137 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1139 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1140 inset->dispatch(view()->cursor(), fr);
1141 } else if (name == "paragraph") {
1142 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1147 case LFUN_DIALOG_HIDE:
1148 Dialogs::hide(argument, 0);
1151 case LFUN_DIALOG_DISCONNECT_INSET:
1152 owner->getDialogs().disconnect(argument);
1155 case LFUN_CHILDOPEN: {
1156 string const filename =
1157 MakeAbsPath(argument, owner->buffer()->filePath());
1158 setMessage(N_("Opening child document ") +
1159 MakeDisplayPath(filename) + "...");
1160 view()->savePosition(0);
1161 string const parentfilename = owner->buffer()->fileName();
1162 if (bufferlist.exists(filename))
1163 view()->setBuffer(bufferlist.getBuffer(filename));
1165 view()->loadLyXFile(filename);
1166 // Set the parent name of the child document.
1167 // This makes insertion of citations and references in the child work,
1168 // when the target is in the parent or another child document.
1169 owner->buffer()->setParentName(parentfilename);
1173 case LFUN_TOGGLECURSORFOLLOW:
1174 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1178 owner->getIntl().KeyMapOn(false);
1181 case LFUN_KMAP_PRIM:
1182 owner->getIntl().KeyMapPrim();
1186 owner->getIntl().KeyMapSec();
1189 case LFUN_KMAP_TOGGLE:
1190 owner->getIntl().ToggleKeyMap();
1196 string rest = split(argument, countstr, ' ');
1197 istringstream is(countstr);
1200 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1201 for (int i = 0; i < count; ++i)
1202 dispatch(lyxaction.lookupFunc(rest));
1207 // argument contains ';'-terminated commands
1208 while (!argument.empty()) {
1210 string rest = split(argument, first, ';');
1211 dispatch(lyxaction.lookupFunc(rest));
1215 case LFUN_SAVEPREFERENCES: {
1216 Path p(user_lyxdir());
1217 lyxrc.write("preferences");
1221 case LFUN_SCREEN_FONT_UPDATE:
1222 // handle the screen font changes.
1223 lyxrc.set_font_norm_type();
1224 lyx_gui::update_fonts();
1225 // All visible buffers will need resize
1229 case LFUN_SET_COLOR: {
1231 string const x11_name = split(argument, lyx_name, ' ');
1232 if (lyx_name.empty() || x11_name.empty()) {
1233 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1238 bool const graphicsbg_changed =
1239 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1240 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1242 if (!lcolor.setColor(lyx_name, x11_name)) {
1244 bformat(_("Set-color \"%1$s\" failed "
1245 "- color is undefined or "
1246 "may not be redefined"), lyx_name));
1250 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1252 if (graphicsbg_changed) {
1253 #ifdef WITH_WARNINGS
1254 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1257 lyx::graphics::GCache::get().changeDisplay(true);
1264 owner->message(argument);
1267 case LFUN_TOOLTIPS_TOGGLE:
1268 owner->getDialogs().toggleTooltips();
1271 case LFUN_EXTERNAL_EDIT: {
1272 FuncRequest fr(action, argument);
1273 InsetExternal().dispatch(view()->cursor(), fr);
1277 case LFUN_BREAKLINE: {
1278 #warning swallow 'Return' if the minibuffer is focused. But how?
1282 case LFUN_ALL_INSETS_TOGGLE: {
1284 string const name = split(argument, action, ' ');
1285 InsetBase::Code const inset_code =
1286 InsetBase::translate(name);
1288 LCursor & cur = view()->cursor();
1289 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1291 InsetBase & inset = owner->buffer()->inset();
1292 InsetIterator it = inset_iterator_begin(inset);
1293 InsetIterator const end = inset_iterator_end(inset);
1294 for (; it != end; ++it) {
1295 if (inset_code == InsetBase::NO_CODE
1296 || inset_code == it->lyxCode())
1297 it->dispatch(cur, fr);
1302 case LFUN_LANGUAGE_BUFFER: {
1303 Buffer & buffer = *owner->buffer();
1304 Language const * oldL = buffer.params().language;
1305 Language const * newL = languages.getLanguage(argument);
1306 if (!newL || oldL == newL)
1309 if (oldL->RightToLeft() == newL->RightToLeft()
1310 && !buffer.isMultiLingual())
1311 buffer.changeLanguage(oldL, newL);
1313 buffer.updateDocLang(newL);
1317 case LFUN_BUFFERPARAMS_APPLY: {
1318 istringstream ss(argument);
1321 int const unknown_tokens =
1322 owner->buffer()->readHeader(lex);
1324 if (unknown_tokens != 0) {
1325 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1326 << unknown_tokens << " unknown token"
1327 << (unknown_tokens == 1 ? "" : "s")
1333 case LFUN_TEXTCLASS_APPLY: {
1334 Buffer * buffer = owner->buffer();
1336 lyx::textclass_type const old_class =
1337 buffer->params().textclass;
1339 loadTextclass(argument);
1341 std::pair<bool, lyx::textclass_type> const tc_pair =
1342 textclasslist.NumberOfClass(argument);
1347 lyx::textclass_type const new_class = tc_pair.second;
1348 if (old_class == new_class)
1353 _("Converting document to new document class..."));
1356 lyx::cap::SwitchLayoutsBetweenClasses(
1357 old_class, new_class,
1358 buffer->paragraphs(), el);
1360 bufferErrors(*buffer, el);
1361 view()->showErrorList(_("Class switch"));
1365 case LFUN_TEXTCLASS_LOAD:
1366 loadTextclass(argument);
1369 case LFUN_LYXRC_APPLY: {
1370 istringstream ss(argument);
1371 bool const success = lyxrc.read(ss) == 0;
1374 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1375 << "Unable to read lyxrc data"
1382 DispatchResult res = view()->cursor().dispatch(cmd);
1383 if (!res.dispatched());
1384 view()->dispatch(cmd);
1389 if (view()->available()) {
1390 view()->fitCursor();
1392 view()->cursor().updatePos();
1393 // if we executed a mutating lfun, mark the buffer as dirty
1394 if (getStatus(cmd).enabled()
1395 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1396 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1397 view()->buffer()->markDirty();
1400 if (view()->cursor().inTexted()) {
1401 view()->owner()->updateLayoutChoice();
1402 sendDispatchMessage(getMessage(), cmd, verbose);
1408 void LyXFunc::sendDispatchMessage(string const & msg,
1409 FuncRequest const & cmd, bool verbose)
1411 owner->updateMenubar();
1412 owner->updateToolbar();
1414 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1415 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1417 owner->message(msg);
1421 string dispatch_msg = msg;
1422 if (!dispatch_msg.empty())
1423 dispatch_msg += ' ';
1425 string comname = lyxaction.getActionName(cmd.action);
1427 bool argsadded = false;
1429 if (!cmd.argument.empty()) {
1430 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1431 comname += ' ' + cmd.argument;
1436 string const shortcuts = toplevel_keymap->findbinding(cmd);
1438 if (!shortcuts.empty()) {
1439 comname += ": " + shortcuts;
1440 } else if (!argsadded && !cmd.argument.empty()) {
1441 comname += ' ' + cmd.argument;
1444 if (!comname.empty()) {
1445 comname = rtrim(comname);
1446 dispatch_msg += '(' + comname + ')';
1449 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1450 if (!dispatch_msg.empty())
1451 owner->message(dispatch_msg);
1455 void LyXFunc::setupLocalKeymap()
1457 keyseq.stdmap = toplevel_keymap.get();
1458 keyseq.curmap = toplevel_keymap.get();
1459 cancel_meta_seq.stdmap = toplevel_keymap.get();
1460 cancel_meta_seq.curmap = toplevel_keymap.get();
1464 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1466 string initpath = lyxrc.document_path;
1467 string filename(name);
1469 if (view()->available()) {
1470 string const trypath = owner->buffer()->filePath();
1471 // If directory is writeable, use this as default.
1472 if (IsDirWriteable(trypath))
1476 static int newfile_number;
1478 if (filename.empty()) {
1479 filename = AddName(lyxrc.document_path,
1480 "newfile" + tostr(++newfile_number) + ".lyx");
1481 FileInfo fi(filename);
1482 while (bufferlist.exists(filename) || fi.readable()) {
1484 filename = AddName(lyxrc.document_path,
1485 "newfile" + tostr(newfile_number) +
1487 fi.newFile(filename);
1491 // The template stuff
1494 FileDialog fileDlg(_("Select template file"),
1495 LFUN_SELECT_FILE_SYNC,
1496 make_pair(string(_("Documents|#o#O")),
1497 string(lyxrc.document_path)),
1498 make_pair(string(_("Templates|#T#t")),
1499 string(lyxrc.template_path)));
1501 FileDialog::Result result =
1502 fileDlg.open(lyxrc.template_path,
1503 FileFilterList(_("LyX Documents (*.lyx)")),
1506 if (result.first == FileDialog::Later)
1508 if (result.second.empty())
1510 templname = result.second;
1513 view()->newFile(filename, templname, !name.empty());
1517 void LyXFunc::open(string const & fname)
1519 string initpath = lyxrc.document_path;
1521 if (view()->available()) {
1522 string const trypath = owner->buffer()->filePath();
1523 // If directory is writeable, use this as default.
1524 if (IsDirWriteable(trypath))
1530 if (fname.empty()) {
1531 FileDialog fileDlg(_("Select document to open"),
1533 make_pair(string(_("Documents|#o#O")),
1534 string(lyxrc.document_path)),
1535 make_pair(string(_("Examples|#E#e")),
1536 string(AddPath(system_lyxdir(), "examples"))));
1538 FileDialog::Result result =
1539 fileDlg.open(initpath,
1540 FileFilterList(_("LyX Documents (*.lyx)")),
1543 if (result.first == FileDialog::Later)
1546 filename = result.second;
1548 // check selected filename
1549 if (filename.empty()) {
1550 owner->message(_("Canceled."));
1556 // get absolute path of file and add ".lyx" to the filename if
1558 string const fullpath = FileSearch(string(), filename, "lyx");
1559 if (!fullpath.empty()) {
1560 filename = fullpath;
1563 string const disp_fn(MakeDisplayPath(filename));
1565 // if the file doesn't exist, let the user create one
1566 FileInfo const f(filename, true);
1568 // the user specifically chose this name. Believe them.
1569 view()->newFile(filename, "", true);
1573 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1576 if (view()->loadLyXFile(filename)) {
1577 str2 = bformat(_("Document %1$s opened."), disp_fn);
1579 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1581 owner->message(str2);
1585 void LyXFunc::doImport(string const & argument)
1588 string filename = split(argument, format, ' ');
1590 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1591 << " file: " << filename << endl;
1593 // need user interaction
1594 if (filename.empty()) {
1595 string initpath = lyxrc.document_path;
1597 if (view()->available()) {
1598 string const trypath = owner->buffer()->filePath();
1599 // If directory is writeable, use this as default.
1600 if (IsDirWriteable(trypath))
1604 string const text = bformat(_("Select %1$s file to import"),
1605 formats.prettyName(format));
1607 FileDialog fileDlg(text,
1609 make_pair(string(_("Documents|#o#O")),
1610 string(lyxrc.document_path)),
1611 make_pair(string(_("Examples|#E#e")),
1612 string(AddPath(system_lyxdir(), "examples"))));
1614 string const filter = formats.prettyName(format)
1615 + " (*." + formats.extension(format) + ')';
1617 FileDialog::Result result =
1618 fileDlg.open(initpath,
1619 FileFilterList(filter),
1622 if (result.first == FileDialog::Later)
1625 filename = result.second;
1627 // check selected filename
1628 if (filename.empty())
1629 owner->message(_("Canceled."));
1632 if (filename.empty())
1635 // get absolute path of file
1636 filename = MakeAbsPath(filename);
1638 string const lyxfile = ChangeExtension(filename, ".lyx");
1640 // Check if the document already is open
1641 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1642 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1643 owner->message(_("Canceled."));
1648 // if the file exists already, and we didn't do
1649 // -i lyx thefile.lyx, warn
1650 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1651 string const file = MakeDisplayPath(lyxfile, 30);
1653 string text = bformat(_("The document %1$s already exists.\n\n"
1654 "Do you want to over-write that document?"), file);
1655 int const ret = Alert::prompt(_("Over-write document?"),
1656 text, 0, 1, _("&Over-write"), _("&Cancel"));
1659 owner->message(_("Canceled."));
1664 Importer::Import(owner, filename, format);
1668 void LyXFunc::closeBuffer()
1670 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1671 if (bufferlist.empty()) {
1672 // need this otherwise SEGV may occur while
1673 // trying to set variables that don't exist
1674 // since there's no current buffer
1675 owner->getDialogs().hideBufferDependent();
1677 view()->setBuffer(bufferlist.first());
1683 // Each "owner" should have it's own message method. lyxview and
1684 // the minibuffer would use the minibuffer, but lyxserver would
1685 // send an ERROR signal to its client. Alejandro 970603
1686 // This function is bit problematic when it comes to NLS, to make the
1687 // lyx servers client be language indepenent we must not translate
1688 // strings sent to this func.
1689 void LyXFunc::setErrorMessage(string const & m) const
1691 dispatch_buffer = m;
1696 void LyXFunc::setMessage(string const & m) const
1698 dispatch_buffer = m;
1702 void LyXFunc::setStatusMessage(string const & m) const
1708 string const LyXFunc::viewStatusMessage()
1710 // When meta-fake key is pressed, show the key sequence so far + "M-".
1712 return keyseq.print() + "M-";
1714 // Else, when a non-complete key sequence is pressed,
1715 // show the available options.
1716 if (keyseq.length() > 0 && !keyseq.deleted())
1717 return keyseq.printOptions();
1719 if (!view()->available())
1720 return _("Welcome to LyX!");
1722 return view()->cursor().currentState();
1726 BufferView * LyXFunc::view() const
1728 BOOST_ASSERT(owner);
1729 return owner->view().get();
1733 bool LyXFunc::wasMetaKey() const
1735 return (meta_fake_bit != key_modifier::none);