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 "LayoutFile.h"
25 #include "BranchList.h"
26 #include "buffer_funcs.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
33 #include "Converter.h"
35 #include "CutAndPaste.h"
36 #include "DispatchResult.h"
38 #include "ErrorList.h"
40 #include "FuncRequest.h"
41 #include "FuncStatus.h"
42 #include "InsetIterator.h"
47 #include "LyXAction.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
59 #include "insets/InsetBox.h"
60 #include "insets/InsetBranch.h"
61 #include "insets/InsetCommand.h"
62 #include "insets/InsetERT.h"
63 #include "insets/InsetExternal.h"
64 #include "insets/InsetFloat.h"
65 #include "insets/InsetGraphics.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetListings.h"
68 #include "insets/InsetNote.h"
69 #include "insets/InsetPhantom.h"
70 #include "insets/InsetSpace.h"
71 #include "insets/InsetTabular.h"
72 #include "insets/InsetVSpace.h"
73 #include "insets/InsetWrap.h"
75 #include "frontends/alert.h"
76 #include "frontends/Application.h"
77 #include "frontends/KeySymbol.h"
78 #include "frontends/LyXView.h"
79 #include "frontends/Selection.h"
81 #include "support/debug.h"
82 #include "support/environment.h"
83 #include "support/FileName.h"
84 #include "support/filetools.h"
85 #include "support/gettext.h"
86 #include "support/lstrings.h"
87 #include "support/Path.h"
88 #include "support/Package.h"
89 #include "support/Systemcall.h"
90 #include "support/convert.h"
91 #include "support/os.h"
97 using namespace lyx::support;
101 using frontend::LyXView;
103 namespace Alert = frontend::Alert;
108 // This function runs "configure" and then rereads lyx.defaults to
109 // reconfigure the automatic settings.
110 void reconfigure(LyXView * lv, string const & option)
112 // emit message signal.
114 lv->message(_("Running configure..."));
116 // Run configure in user lyx directory
117 PathChanger p(package().user_support());
118 string configure_command = package().configure_command();
119 configure_command += option;
121 int ret = one.startscript(Systemcall::Wait, configure_command);
123 // emit message signal.
125 lv->message(_("Reloading configuration..."));
126 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
127 // Re-read packages.lst
128 LaTeXFeatures::getAvailable();
131 Alert::information(_("System reconfiguration failed"),
132 _("The system reconfiguration has failed.\n"
133 "Default textclass is used but LyX may "
134 "not be able to work properly.\n"
135 "Please reconfigure again if needed."));
138 Alert::information(_("System reconfigured"),
139 _("The system has been reconfigured.\n"
140 "You need to restart LyX to make use of any\n"
141 "updated document class specifications."));
145 bool getLocalStatus(Cursor cursor, FuncRequest const & cmd, FuncStatus & status)
147 // Try to fix cursor in case it is broken.
148 cursor.fixIfBroken();
150 // This is, of course, a mess. Better create a new doc iterator and use
151 // this in Inset::getStatus. This might require an additional
152 // BufferView * arg, though (which should be avoided)
153 //Cursor safe = *this;
155 for ( ; cursor.depth(); cursor.pop()) {
156 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
157 LASSERT(cursor.idx() <= cursor.lastidx(), /**/);
158 LASSERT(cursor.pit() <= cursor.lastpit(), /**/);
159 LASSERT(cursor.pos() <= cursor.lastpos(), /**/);
161 // The inset's getStatus() will return 'true' if it made
162 // a definitive decision on whether it want to handle the
163 // request or not. The result of this decision is put into
164 // the 'status' parameter.
165 if (cursor.inset().getStatus(cursor, cmd, status)) {
174 /** Return the change status at cursor position, taking in account the
175 * status at each level of the document iterator (a table in a deleted
176 * footnote is deleted).
177 * When \param outer is true, the top slice is not looked at.
179 Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
181 size_t const depth = dit.depth() - (outer ? 1 : 0);
183 for (size_t i = 0 ; i < depth ; ++i) {
184 CursorSlice const & slice = dit[i];
185 if (!slice.inset().inMathed()
186 && slice.pos() < slice.paragraph().size()) {
187 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
188 if (ch != Change::UNCHANGED)
192 return Change::UNCHANGED;
199 : lyx_view_(0), encoded_last_key(0), meta_fake_bit(NoModifier)
204 void LyXFunc::initKeySequences(KeyMap * kb)
206 keyseq = KeySequence(kb, kb);
207 cancel_meta_seq = KeySequence(kb, kb);
211 void LyXFunc::setLyXView(LyXView * lv)
213 if (lyx_view_ && lyx_view_->view() && lyx_view_ != lv)
214 // save current selection to the selection buffer to allow
215 // middle-button paste in another window
216 cap::saveSelection(lyx_view_->view()->cursor());
221 void LyXFunc::handleKeyFunc(FuncCode action)
223 char_type c = encoded_last_key;
228 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
229 lyx_view_->view()->getIntl().getTransManager().deadkey(
230 c, get_accent(action).accent, view()->cursor().innerText(), view()->cursor());
231 // Need to clear, in case the minibuffer calls these
234 // copied verbatim from do_accent_char
235 view()->cursor().resetAnchor();
236 view()->processUpdateFlags(Update::FitCursor);
239 //FIXME: bookmark handling is a frontend issue. This code should be transferred
240 // to GuiView and be GuiView and be window dependent.
241 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
243 LASSERT(lyx_view_, /**/);
244 if (!theSession().bookmarks().isValid(idx))
246 BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
247 LASSERT(!bm.filename.empty(), /**/);
248 string const file = bm.filename.absFilename();
249 // if the file is not opened, open it.
250 if (!theBufferList().exists(bm.filename)) {
252 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
256 // open may fail, so we need to test it again
257 if (!theBufferList().exists(bm.filename))
260 // bm can be changed when saving
261 BookmarksSection::Bookmark tmp = bm;
263 // Special case idx == 0 used for back-from-back jump navigation
265 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
267 // if the current buffer is not that one, switch to it.
268 if (lyx_view_->buffer()->fileName() != tmp.filename) {
271 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
274 // moveToPosition try paragraph id first and then paragraph (pit, pos).
275 if (!view()->moveToPosition(tmp.bottom_pit, tmp.bottom_pos,
276 tmp.top_id, tmp.top_pos))
283 // Cursor jump succeeded!
284 Cursor const & cur = view()->cursor();
285 pit_type new_pit = cur.pit();
286 pos_type new_pos = cur.pos();
287 int new_id = cur.paragraph().id();
289 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
290 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
291 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
292 || bm.top_id != new_id) {
293 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
294 new_pit, new_pos, new_id);
299 void LyXFunc::processKeySym(KeySymbol const & keysym, KeyModifier state)
301 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
303 // Do nothing if we have nothing (JMarc)
304 if (!keysym.isOK()) {
305 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
306 lyx_view_->restartCursor();
310 if (keysym.isModifier()) {
311 LYXERR(Debug::KEY, "isModifier true");
313 lyx_view_->restartCursor();
317 //Encoding const * encoding = view()->cursor().getEncoding();
318 //encoded_last_key = keysym.getISOEncoded(encoding ? encoding->name() : "");
319 // FIXME: encoded_last_key shadows the member variable of the same
320 // name. Is that intended?
321 char_type encoded_last_key = keysym.getUCSEncoded();
323 // Do a one-deep top-level lookup for
324 // cancel and meta-fake keys. RVDK_PATCH_5
325 cancel_meta_seq.reset();
327 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
328 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
330 // When not cancel or meta-fake, do the normal lookup.
331 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
332 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
333 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
334 // remove Caps Lock and Mod2 as a modifiers
335 func = keyseq.addkey(keysym, (state | meta_fake_bit));
336 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
339 // Dont remove this unless you know what you are doing.
340 meta_fake_bit = NoModifier;
342 // Can this happen now ?
343 if (func.action == LFUN_NOACTION)
344 func = FuncRequest(LFUN_COMMAND_PREFIX);
346 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
347 << keyseq.print(KeySequence::Portable) << ']');
349 // already here we know if it any point in going further
350 // why not return already here if action == -1 and
351 // num_bytes == 0? (Lgb)
353 if (keyseq.length() > 1)
354 lyx_view_->message(keyseq.print(KeySequence::ForGui));
357 // Maybe user can only reach the key via holding down shift.
358 // Let's see. But only if shift is the only modifier
359 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
360 LYXERR(Debug::KEY, "Trying without shift");
361 func = keyseq.addkey(keysym, NoModifier);
362 LYXERR(Debug::KEY, "Action now " << func.action);
365 if (func.action == LFUN_UNKNOWN_ACTION) {
366 // Hmm, we didn't match any of the keysequences. See
367 // if it's normal insertable text not already covered
369 if (keysym.isText() && keyseq.length() == 1) {
370 LYXERR(Debug::KEY, "isText() is true, inserting.");
371 func = FuncRequest(LFUN_SELF_INSERT,
372 FuncRequest::KEYBOARD);
374 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
375 lyx_view_->message(_("Unknown function."));
376 lyx_view_->restartCursor();
381 if (func.action == LFUN_SELF_INSERT) {
382 if (encoded_last_key != 0) {
383 docstring const arg(1, encoded_last_key);
384 dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
385 FuncRequest::KEYBOARD));
386 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
396 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
398 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
401 Buffer * buf = lyx_view_ ? lyx_view_->buffer() : 0;
403 if (cmd.action == LFUN_NOACTION) {
404 flag.message(from_utf8(N_("Nothing to do")));
405 flag.setEnabled(false);
409 switch (cmd.action) {
410 case LFUN_UNKNOWN_ACTION:
411 #if !defined(HAVE_LIBMYTHES) && !defined(HAVE_LIBAIKSAURUS)
412 case LFUN_THESAURUS_ENTRY:
415 flag.setEnabled(false);
422 if (flag.unknown()) {
423 flag.message(from_utf8(N_("Unknown action")));
427 if (!flag.enabled()) {
428 if (flag.message().empty())
429 flag.message(from_utf8(N_("Command disabled")));
433 // Check whether we need a buffer
434 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
436 flag.message(from_utf8(N_("Command not allowed with"
437 "out any document open")));
438 flag.setEnabled(false);
442 // I would really like to avoid having this switch and rather try to
443 // encode this in the function itself.
444 // -- And I'd rather let an inset decide which LFUNs it is willing
445 // to handle (Andre')
447 switch (cmd.action) {
449 case LFUN_BUFFER_TOGGLE_READ_ONLY:
450 flag.setOnOff(buf->isReadonly());
453 case LFUN_BUFFER_SWITCH:
454 // toggle on the current buffer, but do not toggle off
455 // the other ones (is that a good idea?)
456 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
460 case LFUN_BUFFER_EXPORT:
461 enable = cmd.argument() == "custom"
462 || buf->isExportable(to_utf8(cmd.argument()));
465 case LFUN_BUFFER_CHKTEX:
466 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
469 case LFUN_BUILD_PROGRAM:
470 enable = buf->isExportable("program");
473 case LFUN_VC_REGISTER:
474 enable = !buf->lyxvc().inUse();
476 case LFUN_VC_CHECK_IN:
477 enable = buf->lyxvc().checkInEnabled();
479 case LFUN_VC_CHECK_OUT:
480 enable = buf->lyxvc().checkOutEnabled();
483 enable = buf->lyxvc().inUse();
485 case LFUN_VC_UNDO_LAST:
486 enable = buf->lyxvc().undoLastEnabled();
488 case LFUN_BUFFER_RELOAD:
489 enable = !buf->isUnnamed() && buf->fileName().exists()
490 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
493 case LFUN_CITATION_INSERT: {
494 FuncRequest fr(LFUN_INSET_INSERT, "citation");
495 enable = getStatus(fr).enabled();
499 // This could be used for the no-GUI version. The GUI version is handled in
500 // LyXView::getStatus(). See above.
502 case LFUN_BUFFER_WRITE:
503 case LFUN_BUFFER_WRITE_AS: {
504 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
505 enable = b && (b->isUnnamed() || !b->isClean());
510 case LFUN_BUFFER_WRITE_ALL: {
511 // We enable the command only if there are some modified buffers
512 Buffer * first = theBufferList().first();
517 // We cannot use a for loop as the buffer list is a cycle.
523 b = theBufferList().next(b);
524 } while (b != first);
528 case LFUN_BOOKMARK_GOTO: {
529 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
530 enable = theSession().bookmarks().isValid(num);
534 case LFUN_BOOKMARK_CLEAR:
535 enable = theSession().bookmarks().hasValid();
538 // this one is difficult to get right. As a half-baked
539 // solution, we consider only the first action of the sequence
540 case LFUN_COMMAND_SEQUENCE: {
541 // argument contains ';'-terminated commands
542 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
543 FuncRequest func(lyxaction.lookupFunc(firstcmd));
544 func.origin = cmd.origin;
545 flag = getStatus(func);
549 // we want to check if at least one of these is enabled
550 case LFUN_COMMAND_ALTERNATIVES: {
551 // argument contains ';'-terminated commands
552 string arg = to_utf8(cmd.argument());
553 while (!arg.empty()) {
555 arg = split(arg, first, ';');
556 FuncRequest func(lyxaction.lookupFunc(first));
557 func.origin = cmd.origin;
558 flag = getStatus(func);
559 // if this one is enabled, the whole thing is
568 string name = to_utf8(cmd.argument());
569 if (theTopLevelCmdDef().lock(name, func)) {
570 func.origin = cmd.origin;
571 flag = getStatus(func);
572 theTopLevelCmdDef().release(name);
574 // catch recursion or unknown command definiton
575 // all operations until the recursion or unknown command
576 // definiton occures are performed, so set the state to enabled
582 case LFUN_VC_COMMAND: {
583 if (cmd.argument().empty())
586 if (!buf && contains(cmd.getArg(0), 'D'))
591 case LFUN_WORD_FIND_FORWARD:
592 case LFUN_WORD_FIND_BACKWARD:
593 case LFUN_WORD_FINDADV:
594 case LFUN_COMMAND_PREFIX:
595 case LFUN_COMMAND_EXECUTE:
597 case LFUN_META_PREFIX:
598 case LFUN_BUFFER_CLOSE:
599 case LFUN_BUFFER_UPDATE:
600 case LFUN_BUFFER_VIEW:
601 case LFUN_MASTER_BUFFER_UPDATE:
602 case LFUN_MASTER_BUFFER_VIEW:
603 case LFUN_BUFFER_IMPORT:
604 case LFUN_BUFFER_AUTO_SAVE:
605 case LFUN_RECONFIGURE:
607 case LFUN_DROP_LAYOUTS_CHOICE:
609 case LFUN_SERVER_GET_FILENAME:
610 case LFUN_SERVER_NOTIFY:
611 case LFUN_SERVER_GOTO_FILE_ROW:
612 case LFUN_DIALOG_HIDE:
613 case LFUN_DIALOG_DISCONNECT_INSET:
614 case LFUN_BUFFER_CHILD_OPEN:
615 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
616 case LFUN_KEYMAP_OFF:
617 case LFUN_KEYMAP_PRIMARY:
618 case LFUN_KEYMAP_SECONDARY:
619 case LFUN_KEYMAP_TOGGLE:
621 case LFUN_BUFFER_EXPORT_CUSTOM:
622 case LFUN_BUFFER_PRINT:
623 case LFUN_PREFERENCES_SAVE:
625 case LFUN_INSET_EDIT:
626 case LFUN_BUFFER_LANGUAGE:
627 case LFUN_TEXTCLASS_APPLY:
628 case LFUN_TEXTCLASS_LOAD:
629 case LFUN_BUFFER_SAVE_AS_DEFAULT:
630 case LFUN_BUFFER_PARAMS_APPLY:
631 case LFUN_LAYOUT_MODULES_CLEAR:
632 case LFUN_LAYOUT_MODULE_ADD:
633 case LFUN_LAYOUT_RELOAD:
634 case LFUN_LYXRC_APPLY:
635 case LFUN_BUFFER_NEXT:
636 case LFUN_BUFFER_PREVIOUS:
637 // these are handled in our dispatch()
645 if (theApp()->getStatus(cmd, flag))
648 // Does the view know something?
653 if (lyx_view_->getStatus(cmd, flag))
656 // If we have a BufferView, try cursor position and
657 // then the BufferView.
662 if (!getLocalStatus(view()->cursor(), cmd, flag))
663 flag = view()->getStatus(cmd);
667 flag.setEnabled(false);
669 // Can we use a readonly buffer?
670 if (buf && buf->isReadonly()
671 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
672 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
673 flag.message(from_utf8(N_("Document is read-only")));
674 flag.setEnabled(false);
677 // Are we in a DELETED change-tracking region?
679 && lookupChangeType(view()->cursor(), true) == Change::DELETED
680 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
681 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
682 flag.message(from_utf8(N_("This portion of the document is deleted.")));
683 flag.setEnabled(false);
686 // the default error message if we disable the command
687 if (!flag.enabled() && flag.message().empty())
688 flag.message(from_utf8(N_("Command disabled")));
694 bool LyXFunc::ensureBufferClean(BufferView * bv)
696 Buffer & buf = bv->buffer();
697 if (buf.isClean() && !buf.isUnnamed())
700 docstring const file = buf.fileName().displayName(30);
703 if (!buf.isUnnamed()) {
704 text = bformat(_("The document %1$s has unsaved "
705 "changes.\n\nDo you want to save "
706 "the document?"), file);
707 title = _("Save changed document?");
710 text = bformat(_("The document %1$s has not been "
711 "saved yet.\n\nDo you want to save "
712 "the document?"), file);
713 title = _("Save new document?");
715 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
718 lyx_view_->dispatch(FuncRequest(LFUN_BUFFER_WRITE));
720 return buf.isClean() && !buf.isUnnamed();
726 void showPrintError(string const & name)
728 docstring str = bformat(_("Could not print the document %1$s.\n"
729 "Check that your printer is set up correctly."),
730 makeDisplayPath(name, 50));
731 Alert::error(_("Print document failed"), str);
735 bool loadLayoutFile(string const & name, string const & buf_path)
737 if (!LayoutFileList::get().haveClass(name)) {
738 lyxerr << "Document class \"" << name
739 << "\" does not exist."
744 LayoutFile & tc = LayoutFileList::get()[name];
745 if (!tc.load(buf_path)) {
746 docstring s = bformat(_("The document class %1$s "
747 "could not be loaded."), from_utf8(name));
748 Alert::error(_("Could not load class"), s);
755 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
760 void LyXFunc::dispatch(FuncRequest const & cmd)
762 string const argument = to_utf8(cmd.argument());
763 FuncCode const action = cmd.action;
765 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
766 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
768 // we have not done anything wrong yet.
770 dispatch_buffer.erase();
772 // redraw the screen at the end (first of the two drawing steps).
773 //This is done unless explicitely requested otherwise
774 Update::flags updateFlags = Update::FitCursor;
776 FuncStatus const flag = getStatus(cmd);
777 if (!flag.enabled()) {
778 // We cannot use this function here
779 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
780 << lyxaction.getActionName(action)
781 << " [" << action << "] is disabled at this location");
782 setErrorMessage(flag.message());
784 lyx_view_->restartCursor();
786 Buffer * buffer = lyx_view_ ? lyx_view_->buffer() : 0;
789 case LFUN_WORD_FIND_FORWARD:
790 case LFUN_WORD_FIND_BACKWARD: {
791 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
792 static docstring last_search;
793 docstring searched_string;
795 if (!cmd.argument().empty()) {
796 last_search = cmd.argument();
797 searched_string = cmd.argument();
799 searched_string = last_search;
802 if (searched_string.empty())
805 bool const fw = action == LFUN_WORD_FIND_FORWARD;
806 docstring const data =
807 find2string(searched_string, true, false, fw);
808 find(view(), FuncRequest(LFUN_WORD_FIND, data));
812 case LFUN_COMMAND_PREFIX:
813 LASSERT(lyx_view_, /**/);
814 lyx_view_->message(keyseq.printOptions(true));
818 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
820 meta_fake_bit = NoModifier;
822 // cancel any selection
823 dispatch(FuncRequest(LFUN_MARK_OFF));
824 setMessage(from_ascii(N_("Cancel")));
827 case LFUN_META_PREFIX:
828 meta_fake_bit = AltModifier;
829 setMessage(keyseq.print(KeySequence::ForGui));
832 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
833 LASSERT(lyx_view_ && lyx_view_->view() && buffer, /**/);
834 if (buffer->lyxvc().inUse())
835 buffer->lyxvc().toggleReadOnly();
837 buffer->setReadonly(!buffer->isReadonly());
841 // --- Menus -----------------------------------------------
842 case LFUN_BUFFER_CLOSE:
843 lyx_view_->closeBuffer();
845 updateFlags = Update::None;
848 case LFUN_BUFFER_RELOAD: {
849 LASSERT(lyx_view_ && buffer, /**/);
850 docstring const file = makeDisplayPath(buffer->absFileName(), 20);
851 docstring text = bformat(_("Any changes will be lost. Are you sure "
852 "you want to revert to the saved version of the document %1$s?"), file);
853 int const ret = Alert::prompt(_("Revert to saved document?"),
854 text, 1, 1, _("&Revert"), _("&Cancel"));
861 case LFUN_BUFFER_UPDATE:
862 LASSERT(lyx_view_ && buffer, /**/);
863 buffer->doExport(argument, true);
866 case LFUN_BUFFER_VIEW:
867 LASSERT(lyx_view_ && buffer, /**/);
868 buffer->preview(argument);
871 case LFUN_MASTER_BUFFER_UPDATE:
872 LASSERT(lyx_view_ && buffer && buffer->masterBuffer(), /**/);
873 buffer->masterBuffer()->doExport(argument, true);
876 case LFUN_MASTER_BUFFER_VIEW:
877 LASSERT(lyx_view_ && buffer && buffer->masterBuffer(), /**/);
878 buffer->masterBuffer()->preview(argument);
881 case LFUN_BUILD_PROGRAM:
882 LASSERT(lyx_view_ && buffer, /**/);
883 buffer->doExport("program", true);
886 case LFUN_BUFFER_CHKTEX:
887 LASSERT(lyx_view_ && buffer, /**/);
891 case LFUN_BUFFER_EXPORT:
892 LASSERT(lyx_view_ && buffer, /**/);
893 if (argument == "custom")
894 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
896 buffer->doExport(argument, false);
899 case LFUN_BUFFER_EXPORT_CUSTOM: {
900 LASSERT(lyx_view_ && buffer, /**/);
902 string command = split(argument, format_name, ' ');
903 Format const * format = formats.getFormat(format_name);
905 lyxerr << "Format \"" << format_name
906 << "\" not recognized!"
911 // The name of the file created by the conversion process
914 // Output to filename
915 if (format->name() == "lyx") {
916 string const latexname = buffer->latexName(false);
917 filename = changeExtension(latexname,
918 format->extension());
919 filename = addName(buffer->temppath(), filename);
921 if (!buffer->writeFile(FileName(filename)))
925 buffer->doExport(format_name, true, filename);
928 // Substitute $$FName for filename
929 if (!contains(command, "$$FName"))
930 command = "( " + command + " ) < $$FName";
931 command = subst(command, "$$FName", filename);
933 // Execute the command in the background
935 call.startscript(Systemcall::DontWait, command);
939 case LFUN_BUFFER_PRINT: {
940 LASSERT(lyx_view_ && buffer, /**/);
941 // FIXME: cmd.getArg() might fail if one of the arguments
942 // contains double quotes
943 string target = cmd.getArg(0);
944 string target_name = cmd.getArg(1);
945 string command = cmd.getArg(2);
948 || target_name.empty()
949 || command.empty()) {
950 lyxerr << "Unable to parse \""
951 << argument << '"' << endl;
954 if (target != "printer" && target != "file") {
955 lyxerr << "Unrecognized target \""
956 << target << '"' << endl;
960 if (!buffer->doExport("dvi", true)) {
961 showPrintError(buffer->absFileName());
965 // Push directory path.
966 string const path = buffer->temppath();
967 // Prevent the compiler from optimizing away p
971 // there are three cases here:
972 // 1. we print to a file
973 // 2. we print directly to a printer
974 // 3. we print using a spool command (print to file first)
977 string const dviname =
978 changeExtension(buffer->latexName(true), "dvi");
980 if (target == "printer") {
981 if (!lyxrc.print_spool_command.empty()) {
982 // case 3: print using a spool
983 string const psname =
984 changeExtension(dviname,".ps");
985 command += ' ' + lyxrc.print_to_file
988 + quoteName(dviname);
991 lyxrc.print_spool_command + ' ';
992 if (target_name != "default") {
993 command2 += lyxrc.print_spool_printerprefix
997 command2 += quoteName(psname);
999 // If successful, then spool command
1000 res = one.startscript(
1005 res = one.startscript(
1006 Systemcall::DontWait,
1009 // case 2: print directly to a printer
1010 if (target_name != "default")
1011 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1012 res = one.startscript(
1013 Systemcall::DontWait,
1014 command + quoteName(dviname));
1018 // case 1: print to a file
1019 FileName const filename(makeAbsPath(target_name,
1020 buffer->filePath()));
1021 FileName const dvifile(makeAbsPath(dviname, path));
1022 if (filename.exists()) {
1023 docstring text = bformat(
1024 _("The file %1$s already exists.\n\n"
1025 "Do you want to overwrite that file?"),
1026 makeDisplayPath(filename.absFilename()));
1027 if (Alert::prompt(_("Overwrite file?"),
1028 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1031 command += ' ' + lyxrc.print_to_file
1032 + quoteName(filename.toFilesystemEncoding())
1034 + quoteName(dvifile.toFilesystemEncoding());
1035 res = one.startscript(Systemcall::DontWait,
1040 showPrintError(buffer->absFileName());
1044 // FIXME: There is need for a command-line import.
1046 case LFUN_BUFFER_IMPORT:
1051 case LFUN_BUFFER_AUTO_SAVE:
1055 case LFUN_RECONFIGURE:
1056 // argument is any additional parameter to the configure.py command
1057 reconfigure(lyx_view_, argument);
1060 case LFUN_HELP_OPEN: {
1062 theApp()->dispatch(FuncRequest(LFUN_WINDOW_NEW));
1063 string const arg = argument;
1065 setErrorMessage(from_utf8(N_("Missing argument")));
1068 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1070 fname = i18nLibFileSearch("examples", arg, "lyx");
1072 if (fname.empty()) {
1073 lyxerr << "LyX: unable to find documentation file `"
1074 << arg << "'. Bad installation?" << endl;
1077 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1078 makeDisplayPath(fname.absFilename())));
1079 Buffer * buf = lyx_view_->loadDocument(fname, false);
1081 buf->updateLabels();
1082 lyx_view_->setBuffer(buf);
1083 buf->errors("Parse");
1085 updateFlags = Update::None;
1089 // --- version control -------------------------------
1090 case LFUN_VC_REGISTER:
1091 LASSERT(lyx_view_ && buffer, /**/);
1092 if (!ensureBufferClean(view()))
1094 if (!buffer->lyxvc().inUse()) {
1095 if (buffer->lyxvc().registrer())
1098 updateFlags = Update::Force;
1101 case LFUN_VC_CHECK_IN:
1102 LASSERT(lyx_view_ && buffer, /**/);
1103 if (!ensureBufferClean(view()))
1105 if (buffer->lyxvc().inUse()
1106 && !buffer->isReadonly()) {
1107 setMessage(from_utf8(buffer->lyxvc().checkIn()));
1112 case LFUN_VC_CHECK_OUT:
1113 LASSERT(lyx_view_ && buffer, /**/);
1114 if (!ensureBufferClean(view()))
1116 if (buffer->lyxvc().inUse()) {
1117 setMessage(from_utf8(buffer->lyxvc().checkOut()));
1122 case LFUN_VC_REVERT:
1123 LASSERT(lyx_view_ && buffer, /**/);
1124 buffer->lyxvc().revert();
1128 case LFUN_VC_UNDO_LAST:
1129 LASSERT(lyx_view_ && buffer, /**/);
1130 buffer->lyxvc().undoLast();
1134 // --- lyxserver commands ----------------------------
1135 case LFUN_SERVER_GET_FILENAME:
1136 LASSERT(lyx_view_ && buffer, /**/);
1137 setMessage(from_utf8(buffer->absFileName()));
1138 LYXERR(Debug::INFO, "FNAME["
1139 << buffer->absFileName() << ']');
1142 case LFUN_SERVER_NOTIFY:
1143 dispatch_buffer = keyseq.print(KeySequence::Portable);
1144 theServer().notifyClient(to_utf8(dispatch_buffer));
1147 case LFUN_SERVER_GOTO_FILE_ROW: {
1148 LASSERT(lyx_view_, /**/);
1151 istringstream is(argument);
1152 is >> file_name >> row;
1154 bool loaded = false;
1155 if (prefixIs(file_name, package().temp_dir().absFilename()))
1156 // Needed by inverse dvi search. If it is a file
1157 // in tmpdir, call the apropriated function
1158 buf = theBufferList().getBufferFromTmp(file_name);
1160 // Must replace extension of the file to be .lyx
1161 // and get full path
1162 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1163 // Either change buffer or load the file
1164 if (theBufferList().exists(s))
1165 buf = theBufferList().getBuffer(s);
1167 buf = lyx_view_->loadDocument(s);
1173 updateFlags = Update::None;
1177 buf->updateLabels();
1178 lyx_view_->setBuffer(buf);
1179 view()->setCursorFromRow(row);
1181 buf->errors("Parse");
1182 updateFlags = Update::FitCursor;
1187 case LFUN_DIALOG_SHOW_NEW_INSET: {
1188 LASSERT(lyx_view_, /**/);
1189 string const name = cmd.getArg(0);
1190 InsetCode code = insetCode(name);
1191 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1192 bool insetCodeOK = true;
1201 case HYPERLINK_CODE: {
1202 InsetCommandParams p(code);
1203 data = InsetCommand::params2string(name, p);
1206 case INCLUDE_CODE: {
1207 // data is the include type: one of "include",
1208 // "input", "verbatiminput" or "verbatiminput*"
1210 // default type is requested
1212 InsetCommandParams p(INCLUDE_CODE, data);
1213 data = InsetCommand::params2string("include", p);
1217 // \c data == "Boxed" || "Frameless" etc
1218 InsetBoxParams p(data);
1219 data = InsetBox::params2string(p);
1223 InsetBranchParams p;
1224 data = InsetBranch::params2string(p);
1228 InsetCommandParams p(CITE_CODE);
1229 data = InsetCommand::params2string(name, p);
1233 data = InsetERT::params2string(InsetCollapsable::Open);
1236 case EXTERNAL_CODE: {
1237 InsetExternalParams p;
1238 data = InsetExternal::params2string(p, *buffer);
1243 data = InsetFloat::params2string(p);
1246 case LISTINGS_CODE: {
1247 InsetListingsParams p;
1248 data = InsetListings::params2string(p);
1251 case GRAPHICS_CODE: {
1252 InsetGraphicsParams p;
1253 data = InsetGraphics::params2string(p, *buffer);
1258 data = InsetNote::params2string(p);
1261 case PHANTOM_CODE: {
1262 InsetPhantomParams p;
1263 data = InsetPhantom::params2string(p);
1268 data = InsetSpace::params2string(p);
1273 data = InsetVSpace::params2string(space);
1278 data = InsetWrap::params2string(p);
1282 lyxerr << "Inset type '" << name <<
1283 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1284 insetCodeOK = false;
1286 } // end switch(code)
1288 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1292 case LFUN_CITATION_INSERT: {
1293 LASSERT(lyx_view_, /**/);
1294 if (!argument.empty()) {
1295 // we can have one optional argument, delimited by '|'
1296 // citation-insert <key>|<text_before>
1297 // this should be enhanced to also support text_after
1298 // and citation style
1299 string arg = argument;
1301 if (contains(argument, "|")) {
1302 arg = token(argument, '|', 0);
1303 opt1 = token(argument, '|', 1);
1305 InsetCommandParams icp(CITE_CODE);
1306 icp["key"] = from_utf8(arg);
1308 icp["before"] = from_utf8(opt1);
1309 string icstr = InsetCommand::params2string("citation", icp);
1310 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1313 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1317 case LFUN_BUFFER_CHILD_OPEN: {
1318 LASSERT(lyx_view_ && buffer, /**/);
1319 FileName filename = makeAbsPath(argument, buffer->filePath());
1320 view()->saveBookmark(false);
1322 bool parsed = false;
1323 if (theBufferList().exists(filename)) {
1324 child = theBufferList().getBuffer(filename);
1326 setMessage(bformat(_("Opening child document %1$s..."),
1327 makeDisplayPath(filename.absFilename())));
1328 child = lyx_view_->loadDocument(filename, false);
1332 // Set the parent name of the child document.
1333 // This makes insertion of citations and references in the child work,
1334 // when the target is in the parent or another child document.
1335 child->setParent(buffer);
1336 child->masterBuffer()->updateLabels();
1337 lyx_view_->setBuffer(child);
1339 child->errors("Parse");
1342 // If a screen update is required (in case where auto_open is false),
1343 // setBuffer() would have taken care of it already. Otherwise we shall
1344 // reset the update flag because it can cause a circular problem.
1346 updateFlags = Update::None;
1350 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1351 LASSERT(lyx_view_, /**/);
1352 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1355 case LFUN_KEYMAP_OFF:
1356 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
1357 lyx_view_->view()->getIntl().keyMapOn(false);
1360 case LFUN_KEYMAP_PRIMARY:
1361 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
1362 lyx_view_->view()->getIntl().keyMapPrim();
1365 case LFUN_KEYMAP_SECONDARY:
1366 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
1367 lyx_view_->view()->getIntl().keyMapSec();
1370 case LFUN_KEYMAP_TOGGLE:
1371 LASSERT(lyx_view_ && lyx_view_->view(), /**/);
1372 lyx_view_->view()->getIntl().toggleKeyMap();
1378 string rest = split(argument, countstr, ' ');
1379 istringstream is(countstr);
1382 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1383 for (int i = 0; i < count; ++i)
1384 dispatch(lyxaction.lookupFunc(rest));
1388 case LFUN_COMMAND_SEQUENCE: {
1389 // argument contains ';'-terminated commands
1390 string arg = argument;
1391 if (theBufferList().isLoaded(buffer))
1392 buffer->undo().beginUndoGroup();
1393 while (!arg.empty()) {
1395 arg = split(arg, first, ';');
1396 FuncRequest func(lyxaction.lookupFunc(first));
1397 func.origin = cmd.origin;
1400 if (theBufferList().isLoaded(buffer))
1401 buffer->undo().endUndoGroup();
1405 case LFUN_COMMAND_ALTERNATIVES: {
1406 // argument contains ';'-terminated commands
1407 string arg = argument;
1408 while (!arg.empty()) {
1410 arg = split(arg, first, ';');
1411 FuncRequest func(lyxaction.lookupFunc(first));
1412 func.origin = cmd.origin;
1413 FuncStatus stat = getStatus(func);
1414 if (stat.enabled()) {
1424 if (theTopLevelCmdDef().lock(argument, func)) {
1425 func.origin = cmd.origin;
1427 theTopLevelCmdDef().release(argument);
1429 if (func.action == LFUN_UNKNOWN_ACTION) {
1430 // unknown command definition
1431 lyxerr << "Warning: unknown command definition `"
1435 // recursion detected
1436 lyxerr << "Warning: Recursion in the command definition `"
1437 << argument << "' detected"
1444 case LFUN_PREFERENCES_SAVE: {
1445 lyxrc.write(makeAbsPath("preferences",
1446 package().user_support().absFilename()),
1452 LASSERT(lyx_view_, /**/);
1453 lyx_view_->message(from_utf8(argument));
1456 case LFUN_BUFFER_LANGUAGE: {
1457 LASSERT(lyx_view_, /**/);
1458 Language const * oldL = buffer->params().language;
1459 Language const * newL = languages.getLanguage(argument);
1460 if (!newL || oldL == newL)
1463 if (oldL->rightToLeft() == newL->rightToLeft()
1464 && !buffer->isMultiLingual())
1465 buffer->changeLanguage(oldL, newL);
1469 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1470 string const fname =
1471 addName(addPath(package().user_support().absFilename(), "templates/"),
1473 Buffer defaults(fname);
1475 istringstream ss(argument);
1478 int const unknown_tokens = defaults.readHeader(lex);
1480 if (unknown_tokens != 0) {
1481 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1482 << unknown_tokens << " unknown token"
1483 << (unknown_tokens == 1 ? "" : "s")
1487 if (defaults.writeFile(FileName(defaults.absFileName())))
1488 setMessage(bformat(_("Document defaults saved in %1$s"),
1489 makeDisplayPath(fname)));
1491 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1495 case LFUN_BUFFER_PARAMS_APPLY: {
1496 LASSERT(lyx_view_, /**/);
1498 DocumentClass const * const oldClass = buffer->params().documentClassPtr();
1499 Cursor & cur = view()->cursor();
1500 cur.recordUndoFullDocument();
1502 istringstream ss(argument);
1505 int const unknown_tokens = buffer->readHeader(lex);
1507 if (unknown_tokens != 0) {
1508 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1509 << unknown_tokens << " unknown token"
1510 << (unknown_tokens == 1 ? "" : "s")
1514 updateLayout(oldClass, buffer);
1516 updateFlags = Update::Force | Update::FitCursor;
1517 // We are most certainly here because of a change in the document
1518 // It is then better to make sure that all dialogs are in sync with
1519 // current document settings. LyXView::restartCursor() achieve this.
1520 lyx_view_->restartCursor();
1524 case LFUN_LAYOUT_MODULES_CLEAR: {
1525 LASSERT(lyx_view_, /**/);
1526 DocumentClass const * const oldClass = buffer->params().documentClassPtr();
1527 view()->cursor().recordUndoFullDocument();
1528 buffer->params().clearLayoutModules();
1529 buffer->params().makeDocumentClass();
1530 updateLayout(oldClass, buffer);
1531 updateFlags = Update::Force | Update::FitCursor;
1535 case LFUN_LAYOUT_MODULE_ADD: {
1536 LASSERT(lyx_view_, /**/);
1537 BufferParams const & params = buffer->params();
1538 if (!params.moduleCanBeAdded(argument)) {
1539 LYXERR0("Module `" << argument <<
1540 "' cannot be added due to failed requirements or "
1541 "conflicts with installed modules.");
1544 DocumentClass const * const oldClass = params.documentClassPtr();
1545 view()->cursor().recordUndoFullDocument();
1546 buffer->params().addLayoutModule(argument);
1547 buffer->params().makeDocumentClass();
1548 updateLayout(oldClass, buffer);
1549 updateFlags = Update::Force | Update::FitCursor;
1553 case LFUN_TEXTCLASS_APPLY: {
1554 LASSERT(lyx_view_, /**/);
1556 if (!loadLayoutFile(argument, buffer->temppath()) &&
1557 !loadLayoutFile(argument, buffer->filePath()))
1560 LayoutFile const * old_layout = buffer->params().baseClass();
1561 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1563 if (old_layout == new_layout)
1567 //Save the old, possibly modular, layout for use in conversion.
1568 DocumentClass const * const oldDocClass = buffer->params().documentClassPtr();
1569 view()->cursor().recordUndoFullDocument();
1570 buffer->params().setBaseClass(argument);
1571 buffer->params().makeDocumentClass();
1572 updateLayout(oldDocClass, buffer);
1573 updateFlags = Update::Force | Update::FitCursor;
1577 case LFUN_LAYOUT_RELOAD: {
1578 LASSERT(lyx_view_, /**/);
1579 DocumentClass const * const oldClass = buffer->params().documentClassPtr();
1580 LayoutFileIndex bc = buffer->params().baseClassID();
1581 LayoutFileList::get().reset(bc);
1582 buffer->params().setBaseClass(bc);
1583 buffer->params().makeDocumentClass();
1584 updateLayout(oldClass, buffer);
1585 updateFlags = Update::Force | Update::FitCursor;
1589 case LFUN_TEXTCLASS_LOAD:
1590 loadLayoutFile(argument, buffer->temppath()) ||
1591 loadLayoutFile(argument, buffer->filePath());
1594 case LFUN_LYXRC_APPLY: {
1595 LyXRC const lyxrc_orig = lyxrc;
1597 istringstream ss(argument);
1598 bool const success = lyxrc.read(ss) == 0;
1601 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1602 << "Unable to read lyxrc data"
1607 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1609 theApp()->resetGui();
1611 /// We force the redraw in any case because there might be
1612 /// some screen font changes.
1613 /// FIXME: only the current view will be updated. the Gui
1614 /// class is able to furnish the list of views.
1615 updateFlags = Update::Force;
1619 case LFUN_BOOKMARK_GOTO:
1620 // go to bookmark, open unopened file and switch to buffer if necessary
1621 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1622 updateFlags = Update::FitCursor;
1625 case LFUN_BOOKMARK_CLEAR:
1626 theSession().bookmarks().clear();
1629 case LFUN_VC_COMMAND: {
1630 string flag = cmd.getArg(0);
1631 if (buffer && contains(flag, 'R') && !ensureBufferClean(view()))
1634 if (contains(flag, 'M'))
1635 if (!Alert::askForText(message, _("LyX VC: Log Message")))
1638 string path = cmd.getArg(1);
1639 if (contains(path, "$$p") && buffer)
1640 path = subst(path, "$$p", buffer->filePath());
1641 LYXERR(Debug::LYXVC, "Directory: " << path);
1643 if (!pp.isReadableDirectory()) {
1644 lyxerr << _("Directory is not accessible.") << endl;
1647 support::PathChanger p(pp);
1649 string command = cmd.getArg(2);
1650 if (command.empty())
1653 command = subst(command, "$$i", buffer->absFileName());
1654 command = subst(command, "$$p", buffer->filePath());
1656 command = subst(command, "$$m", to_utf8(message));
1657 LYXERR(Debug::LYXVC, "Command: " << command);
1659 one.startscript(Systemcall::Wait, command);
1663 if (contains(flag, 'I'))
1664 buffer->markDirty();
1665 if (contains(flag, 'R'))
1672 LASSERT(theApp(), /**/);
1673 // Let the frontend dispatch its own actions.
1674 if (theApp()->dispatch(cmd))
1675 // Nothing more to do.
1678 // Everything below is only for active lyx_view_
1682 // Start an undo group. This may be needed for
1683 // some stuff like inset-apply on labels.
1684 if (theBufferList().isLoaded(buffer))
1685 buffer->undo().beginUndoGroup();
1687 // Let the current LyXView dispatch its own actions.
1688 if (lyx_view_->dispatch(cmd)) {
1689 if (lyx_view_->view()) {
1690 updateFlags = lyx_view_->view()->cursor().result().update();
1691 if (theBufferList().isLoaded(buffer))
1692 buffer->undo().endUndoGroup();
1697 LASSERT(lyx_view_->view(), /**/);
1699 // Let the current BufferView dispatch its own actions.
1700 if (view()->dispatch(cmd)) {
1701 // The BufferView took care of its own updates if needed.
1702 updateFlags = Update::None;
1703 if (theBufferList().isLoaded(buffer))
1704 buffer->undo().endUndoGroup();
1708 // Let the current Cursor dispatch its own actions.
1709 Cursor old = view()->cursor();
1710 view()->cursor().getPos(cursorPosBeforeDispatchX_,
1711 cursorPosBeforeDispatchY_);
1712 view()->cursor().dispatch(cmd);
1714 // notify insets we just left
1715 if (view()->cursor() != old) {
1717 bool badcursor = notifyCursorLeavesOrEnters(old, view()->cursor());
1719 view()->cursor().fixIfBroken();
1722 if (theBufferList().isLoaded(buffer))
1723 buffer->undo().endUndoGroup();
1725 // update completion. We do it here and not in
1726 // processKeySym to avoid another redraw just for a
1727 // changed inline completion
1728 if (cmd.origin == FuncRequest::KEYBOARD) {
1729 if (cmd.action == LFUN_SELF_INSERT)
1730 lyx_view_->updateCompletion(view()->cursor(), true, true);
1731 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
1732 lyx_view_->updateCompletion(view()->cursor(), false, true);
1734 lyx_view_->updateCompletion(view()->cursor(), false, false);
1737 updateFlags = view()->cursor().result().update();
1740 // if we executed a mutating lfun, mark the buffer as dirty
1741 if (theBufferList().isLoaded(buffer) && flag.enabled()
1742 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1743 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1744 buffer->markDirty();
1746 if (lyx_view_ && lyx_view_->buffer()) {
1747 // BufferView::update() updates the ViewMetricsInfo and
1748 // also initializes the position cache for all insets in
1749 // (at least partially) visible top-level paragraphs.
1750 // We will redraw the screen only if needed.
1751 view()->processUpdateFlags(updateFlags);
1753 // Do we have a selection?
1754 theSelection().haveSelection(view()->cursor().selection());
1757 lyx_view_->restartCursor();
1761 // Some messages may already be translated, so we cannot use _()
1762 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1767 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1769 const bool verbose = (cmd.origin == FuncRequest::MENU
1770 || cmd.origin == FuncRequest::TOOLBAR
1771 || cmd.origin == FuncRequest::COMMANDBUFFER);
1773 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1774 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1776 lyx_view_->message(msg);
1780 docstring dispatch_msg = msg;
1781 if (!dispatch_msg.empty())
1782 dispatch_msg += ' ';
1784 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1786 bool argsadded = false;
1788 if (!cmd.argument().empty()) {
1789 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1790 comname += ' ' + cmd.argument();
1795 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd, KeySequence::ForGui);
1797 if (!shortcuts.empty())
1798 comname += ": " + shortcuts;
1799 else if (!argsadded && !cmd.argument().empty())
1800 comname += ' ' + cmd.argument();
1802 if (!comname.empty()) {
1803 comname = rtrim(comname);
1804 dispatch_msg += '(' + rtrim(comname) + ')';
1807 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1808 if (!dispatch_msg.empty())
1809 lyx_view_->message(dispatch_msg);
1813 void LyXFunc::reloadBuffer()
1815 FileName filename = lyx_view_->buffer()->fileName();
1816 // The user has already confirmed that the changes, if any, should
1817 // be discarded. So we just release the Buffer and don't call closeBuffer();
1818 theBufferList().release(lyx_view_->buffer());
1819 // if the lyx_view_ has been destroyed, create a new one
1821 theApp()->dispatch(FuncRequest(LFUN_WINDOW_NEW));
1822 Buffer * buf = lyx_view_->loadDocument(filename);
1823 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1826 buf->updateLabels();
1827 lyx_view_->setBuffer(buf);
1828 buf->errors("Parse");
1829 str = bformat(_("Document %1$s reloaded."), disp_fn);
1831 str = bformat(_("Could not reload document %1$s"), disp_fn);
1833 lyx_view_->message(str);
1836 // Each "lyx_view_" should have it's own message method. lyxview and
1837 // the minibuffer would use the minibuffer, but lyxserver would
1838 // send an ERROR signal to its client. Alejandro 970603
1839 // This function is bit problematic when it comes to NLS, to make the
1840 // lyx servers client be language indepenent we must not translate
1841 // strings sent to this func.
1842 void LyXFunc::setErrorMessage(docstring const & m) const
1844 dispatch_buffer = m;
1849 void LyXFunc::setMessage(docstring const & m) const
1851 dispatch_buffer = m;
1855 docstring LyXFunc::viewStatusMessage()
1857 // When meta-fake key is pressed, show the key sequence so far + "M-".
1859 return keyseq.print(KeySequence::ForGui) + "M-";
1861 // Else, when a non-complete key sequence is pressed,
1862 // show the available options.
1863 if (keyseq.length() > 0 && !keyseq.deleted())
1864 return keyseq.printOptions(true);
1866 LASSERT(lyx_view_, /**/);
1867 if (!lyx_view_->buffer())
1868 return _("Welcome to LyX!");
1870 return view()->cursor().currentState();
1874 BufferView * LyXFunc::view() const
1876 LASSERT(lyx_view_, /**/);
1877 return lyx_view_->view();
1881 bool LyXFunc::wasMetaKey() const
1883 return (meta_fake_bit != NoModifier);
1887 void LyXFunc::updateLayout(DocumentClass const * const oldlayout, Buffer * buf)
1889 lyx_view_->message(_("Converting document to new document class..."));
1891 StableDocIterator backcur(view()->cursor());
1892 ErrorList & el = buf->errorList("Class Switch");
1893 cap::switchBetweenClasses(
1894 oldlayout, buf->params().documentClassPtr(),
1895 static_cast<InsetText &>(buf->inset()), el);
1897 view()->setCursor(backcur.asDocIterator(buf));
1899 buf->errors("Class Switch");
1900 buf->updateLabels();
1906 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
1908 // Why the switch you might ask. It is a trick to ensure that all
1909 // the elements in the LyXRCTags enum is handled. As you can see
1910 // there are no breaks at all. So it is just a huge fall-through.
1911 // The nice thing is that we will get a warning from the compiler
1912 // if we forget an element.
1913 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
1915 case LyXRC::RC_ACCEPT_COMPOUND:
1916 case LyXRC::RC_ALT_LANG:
1917 case LyXRC::RC_PLAINTEXT_LINELEN:
1918 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
1919 case LyXRC::RC_AUTOCORRECTION_MATH:
1920 case LyXRC::RC_AUTOREGIONDELETE:
1921 case LyXRC::RC_AUTORESET_OPTIONS:
1922 case LyXRC::RC_AUTOSAVE:
1923 case LyXRC::RC_AUTO_NUMBER:
1924 case LyXRC::RC_BACKUPDIR_PATH:
1925 case LyXRC::RC_BIBTEX_COMMAND:
1926 case LyXRC::RC_BINDFILE:
1927 case LyXRC::RC_CHECKLASTFILES:
1928 case LyXRC::RC_COMPLETION_CURSOR_TEXT:
1929 case LyXRC::RC_COMPLETION_INLINE_DELAY:
1930 case LyXRC::RC_COMPLETION_INLINE_DOTS:
1931 case LyXRC::RC_COMPLETION_INLINE_MATH:
1932 case LyXRC::RC_COMPLETION_INLINE_TEXT:
1933 case LyXRC::RC_COMPLETION_POPUP_AFTER_COMPLETE:
1934 case LyXRC::RC_COMPLETION_POPUP_DELAY:
1935 case LyXRC::RC_COMPLETION_POPUP_MATH:
1936 case LyXRC::RC_COMPLETION_POPUP_TEXT:
1937 case LyXRC::RC_USELASTFILEPOS:
1938 case LyXRC::RC_LOADSESSION:
1939 case LyXRC::RC_CHKTEX_COMMAND:
1940 case LyXRC::RC_CONVERTER:
1941 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
1942 case LyXRC::RC_COPIER:
1943 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
1944 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
1945 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
1946 case LyXRC::RC_DATE_INSERT_FORMAT:
1947 case LyXRC::RC_DEFAULT_LANGUAGE:
1948 case LyXRC::RC_GUI_LANGUAGE:
1949 case LyXRC::RC_DEFAULT_PAPERSIZE:
1950 case LyXRC::RC_DEFFILE:
1951 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
1952 case LyXRC::RC_DISPLAY_GRAPHICS:
1953 case LyXRC::RC_DOCUMENTPATH:
1954 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
1955 FileName path(lyxrc_new.document_path);
1956 if (path.exists() && path.isDirectory())
1957 package().document_dir() = FileName(lyxrc.document_path);
1959 case LyXRC::RC_ESC_CHARS:
1960 case LyXRC::RC_EXAMPLEPATH:
1961 case LyXRC::RC_FONT_ENCODING:
1962 case LyXRC::RC_FORMAT:
1963 case LyXRC::RC_GROUP_LAYOUTS:
1964 case LyXRC::RC_INDEX_COMMAND:
1965 case LyXRC::RC_NOMENCL_COMMAND:
1966 case LyXRC::RC_INPUT:
1967 case LyXRC::RC_KBMAP:
1968 case LyXRC::RC_KBMAP_PRIMARY:
1969 case LyXRC::RC_KBMAP_SECONDARY:
1970 case LyXRC::RC_LABEL_INIT_LENGTH:
1971 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
1972 case LyXRC::RC_LANGUAGE_AUTO_END:
1973 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
1974 case LyXRC::RC_LANGUAGE_COMMAND_END:
1975 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
1976 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
1977 case LyXRC::RC_LANGUAGE_PACKAGE:
1978 case LyXRC::RC_LANGUAGE_USE_BABEL:
1979 case LyXRC::RC_MAC_LIKE_WORD_MOVEMENT:
1980 case LyXRC::RC_MACRO_EDIT_STYLE:
1981 case LyXRC::RC_MAKE_BACKUP:
1982 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
1983 case LyXRC::RC_MOUSE_WHEEL_SPEED:
1984 case LyXRC::RC_NUMLASTFILES:
1985 case LyXRC::RC_PATH_PREFIX:
1986 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
1987 prependEnvPath("PATH", lyxrc.path_prefix);
1989 case LyXRC::RC_PERS_DICT:
1990 case LyXRC::RC_PREVIEW:
1991 case LyXRC::RC_PREVIEW_HASHED_LABELS:
1992 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
1993 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
1994 case LyXRC::RC_PRINTCOPIESFLAG:
1995 case LyXRC::RC_PRINTER:
1996 case LyXRC::RC_PRINTEVENPAGEFLAG:
1997 case LyXRC::RC_PRINTEXSTRAOPTIONS:
1998 case LyXRC::RC_PRINTFILEEXTENSION:
1999 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2000 case LyXRC::RC_PRINTODDPAGEFLAG:
2001 case LyXRC::RC_PRINTPAGERANGEFLAG:
2002 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2003 case LyXRC::RC_PRINTPAPERFLAG:
2004 case LyXRC::RC_PRINTREVERSEFLAG:
2005 case LyXRC::RC_PRINTSPOOL_COMMAND:
2006 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2007 case LyXRC::RC_PRINTTOFILE:
2008 case LyXRC::RC_PRINTTOPRINTER:
2009 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2010 case LyXRC::RC_PRINT_COMMAND:
2011 case LyXRC::RC_RTL_SUPPORT:
2012 case LyXRC::RC_SCREEN_DPI:
2013 case LyXRC::RC_SCREEN_FONT_ROMAN:
2014 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2015 case LyXRC::RC_SCREEN_FONT_SANS:
2016 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2017 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2018 case LyXRC::RC_SCREEN_FONT_SIZES:
2019 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2020 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2021 case LyXRC::RC_GEOMETRY_SESSION:
2022 case LyXRC::RC_SCREEN_ZOOM:
2023 case LyXRC::RC_SERVERPIPE:
2024 case LyXRC::RC_SET_COLOR:
2025 case LyXRC::RC_SHOW_BANNER:
2026 case LyXRC::RC_OPEN_BUFFERS_IN_TABS:
2027 case LyXRC::RC_SPELL_COMMAND:
2028 case LyXRC::RC_TEMPDIRPATH:
2029 case LyXRC::RC_TEMPLATEPATH:
2030 case LyXRC::RC_TEX_ALLOWS_SPACES:
2031 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2032 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2033 os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2035 case LyXRC::RC_THESAURUSDIRPATH:
2036 case LyXRC::RC_UIFILE:
2037 case LyXRC::RC_USER_EMAIL:
2038 case LyXRC::RC_USER_NAME:
2039 case LyXRC::RC_USETEMPDIR:
2040 case LyXRC::RC_USE_ALT_LANG:
2041 case LyXRC::RC_USE_CONVERTER_CACHE:
2042 case LyXRC::RC_USE_ESC_CHARS:
2043 case LyXRC::RC_USE_INP_ENC:
2044 case LyXRC::RC_USE_PERS_DICT:
2045 case LyXRC::RC_USE_TOOLTIP:
2046 case LyXRC::RC_USE_PIXMAP_CACHE:
2047 case LyXRC::RC_USE_SPELL_LIB:
2048 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2049 case LyXRC::RC_SORT_LAYOUTS:
2050 case LyXRC::RC_FULL_SCREEN_LIMIT:
2051 case LyXRC::RC_FULL_SCREEN_SCROLLBAR:
2052 case LyXRC::RC_FULL_SCREEN_TABBAR:
2053 case LyXRC::RC_FULL_SCREEN_TOOLBARS:
2054 case LyXRC::RC_FULL_SCREEN_WIDTH:
2055 case LyXRC::RC_VISUAL_CURSOR:
2056 case LyXRC::RC_VIEWER:
2057 case LyXRC::RC_LAST: