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.
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 "support/debug.h"
37 #include "DispatchResult.h"
39 #include "ErrorList.h"
41 #include "FuncRequest.h"
42 #include "FuncStatus.h"
43 #include "support/gettext.h"
44 #include "InsetIterator.h"
49 #include "LyXAction.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
60 #include "TextClassList.h"
61 #include "ToolbarBackend.h"
63 #include "insets/InsetBox.h"
64 #include "insets/InsetBranch.h"
65 #include "insets/InsetCommand.h"
66 #include "insets/InsetERT.h"
67 #include "insets/InsetExternal.h"
68 #include "insets/InsetFloat.h"
69 #include "insets/InsetListings.h"
70 #include "insets/InsetGraphics.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetNote.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetVSpace.h"
75 #include "insets/InsetWrap.h"
77 #include "frontends/alert.h"
78 #include "frontends/Application.h"
79 #include "frontends/FileDialog.h"
80 #include "frontends/KeySymbol.h"
81 #include "frontends/LyXView.h"
82 #include "frontends/Selection.h"
84 #include "support/environment.h"
85 #include "support/FileFilterList.h"
86 #include "support/FileName.h"
87 #include "support/filetools.h"
88 #include "support/lstrings.h"
89 #include "support/Path.h"
90 #include "support/Package.h"
91 #include "support/Systemcall.h"
92 #include "support/convert.h"
93 #include "support/os.h"
98 using namespace lyx::support;
102 using frontend::LyXView;
104 namespace Alert = frontend::Alert;
106 extern bool quitting;
112 bool import(LyXView * lv, FileName const & filename,
113 string const & format, ErrorList & errorList)
115 docstring const displaypath = makeDisplayPath(filename.absFilename());
116 lv->message(bformat(_("Importing %1$s..."), displaypath));
118 FileName const lyxfile(changeExtension(filename.absFilename(), ".lyx"));
120 string loader_format;
121 vector<string> loaders = theConverters().loaders();
122 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
123 for (vector<string>::const_iterator it = loaders.begin();
124 it != loaders.end(); ++it) {
125 if (theConverters().isReachable(format, *it)) {
126 string const tofile =
127 changeExtension(filename.absFilename(),
128 formats.extension(*it));
129 if (!theConverters().convert(0, filename, FileName(tofile),
130 filename, format, *it, errorList))
136 if (loader_format.empty()) {
137 frontend::Alert::error(_("Couldn't import file"),
138 bformat(_("No information for importing the format %1$s."),
139 formats.prettyName(format)));
143 loader_format = format;
147 if (loader_format == "lyx") {
148 Buffer * buf = lv->loadDocument(lyxfile);
151 lv->message(_("file not imported!"));
156 buf->errors("Parse");
158 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
163 bool as_paragraphs = loader_format == "textparagraph";
164 string filename2 = (loader_format == format) ? filename.absFilename()
165 : changeExtension(filename.absFilename(),
166 formats.extension(loader_format));
167 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
168 theLyXFunc().setLyXView(lv);
169 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
173 lv->message(_("imported."));
179 // This function runs "configure" and then rereads lyx.defaults to
180 // reconfigure the automatic settings.
181 void reconfigure(LyXView & lv, string const & option)
183 // emit message signal.
184 lv.message(_("Running configure..."));
186 // Run configure in user lyx directory
187 PathChanger p(package().user_support());
188 string configure_command = package().configure_command();
189 configure_command += option;
191 int ret = one.startscript(Systemcall::Wait, configure_command);
193 // emit message signal.
194 lv.message(_("Reloading configuration..."));
195 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
196 // Re-read packages.lst
197 LaTeXFeatures::getAvailable();
200 Alert::information(_("System reconfiguration failed"),
201 _("The system reconfiguration has failed.\n"
202 "Default textclass is used but LyX may "
203 "not be able to work properly.\n"
204 "Please reconfigure again if needed."));
207 Alert::information(_("System reconfigured"),
208 _("The system has been reconfigured.\n"
209 "You need to restart LyX to make use of any\n"
210 "updated document class specifications."));
214 bool getLocalStatus(Cursor cursor, FuncRequest const & cmd, FuncStatus & status)
216 // Try to fix cursor in case it is broken.
217 cursor.fixIfBroken();
219 // This is, of course, a mess. Better create a new doc iterator and use
220 // this in Inset::getStatus. This might require an additional
221 // BufferView * arg, though (which should be avoided)
222 //Cursor safe = *this;
224 for ( ; cursor.depth(); cursor.pop()) {
225 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
226 BOOST_ASSERT(cursor.idx() <= cursor.lastidx());
227 BOOST_ASSERT(cursor.pit() <= cursor.lastpit());
228 BOOST_ASSERT(cursor.pos() <= cursor.lastpos());
230 // The inset's getStatus() will return 'true' if it made
231 // a definitive decision on whether it want to handle the
232 // request or not. The result of this decision is put into
233 // the 'status' parameter.
234 if (cursor.inset().getStatus(cursor, cmd, status)) {
243 /** Return the change status at cursor position, taking in account the
244 * status at each level of the document iterator (a table in a deleted
245 * footnote is deleted).
246 * When \param outer is true, the top slice is not looked at.
248 Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
250 size_t const depth = dit.depth() - (outer ? 1 : 0);
252 for (size_t i = 0 ; i < depth ; ++i) {
253 CursorSlice const & slice = dit[i];
254 if (!slice.inset().inMathed()
255 && slice.pos() < slice.paragraph().size()) {
256 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
257 if (ch != Change::UNCHANGED)
261 return Change::UNCHANGED;
268 : lyx_view_(0), encoded_last_key(0), meta_fake_bit(NoModifier)
273 void LyXFunc::initKeySequences(KeyMap * kb)
275 keyseq = KeySequence(kb, kb);
276 cancel_meta_seq = KeySequence(kb, kb);
280 void LyXFunc::setLyXView(LyXView * lv)
282 if (!quitting && lyx_view_ && lyx_view_->view() && lyx_view_ != lv)
283 // save current selection to the selection buffer to allow
284 // middle-button paste in another window
285 cap::saveSelection(lyx_view_->view()->cursor());
290 void LyXFunc::handleKeyFunc(kb_action action)
292 char_type c = encoded_last_key;
297 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
298 lyx_view_->view()->getIntl().getTransManager().deadkey(
299 c, get_accent(action).accent, view()->cursor().innerText(), view()->cursor());
300 // Need to clear, in case the minibuffer calls these
303 // copied verbatim from do_accent_char
304 view()->cursor().resetAnchor();
305 view()->processUpdateFlags(Update::FitCursor);
309 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
311 BOOST_ASSERT(lyx_view_);
312 if (!LyX::ref().session().bookmarks().isValid(idx))
314 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(idx);
315 BOOST_ASSERT(!bm.filename.empty());
316 string const file = bm.filename.absFilename();
317 // if the file is not opened, open it.
318 if (!theBufferList().exists(file)) {
320 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
324 // open may fail, so we need to test it again
325 if (!theBufferList().exists(file))
328 // if the current buffer is not that one, switch to it.
329 if (lyx_view_->buffer()->absFileName() != file) {
332 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
334 // moveToPosition try paragraph id first and then paragraph (pit, pos).
335 if (!view()->moveToPosition(bm.bottom_pit, bm.bottom_pos,
336 bm.top_id, bm.top_pos))
339 // Cursor jump succeeded!
340 Cursor const & cur = view()->cursor();
341 pit_type new_pit = cur.pit();
342 pos_type new_pos = cur.pos();
343 int new_id = cur.paragraph().id();
345 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
346 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
347 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
348 || bm.top_id != new_id) {
349 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
350 new_pit, new_pos, new_id);
355 void LyXFunc::processKeySym(KeySymbol const & keysym, KeyModifier state)
357 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
359 // Do nothing if we have nothing (JMarc)
360 if (!keysym.isOK()) {
361 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
362 lyx_view_->restartCursor();
366 if (keysym.isModifier()) {
367 LYXERR(Debug::KEY, "isModifier true");
368 lyx_view_->restartCursor();
372 //Encoding const * encoding = view()->cursor().getEncoding();
373 //encoded_last_key = keysym.getISOEncoded(encoding ? encoding->name() : "");
374 // FIXME: encoded_last_key shadows the member variable of the same
375 // name. Is that intended?
376 char_type encoded_last_key = keysym.getUCSEncoded();
378 // Do a one-deep top-level lookup for
379 // cancel and meta-fake keys. RVDK_PATCH_5
380 cancel_meta_seq.reset();
382 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
383 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
385 // When not cancel or meta-fake, do the normal lookup.
386 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
387 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
388 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
389 // remove Caps Lock and Mod2 as a modifiers
390 func = keyseq.addkey(keysym, (state | meta_fake_bit));
391 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
394 // Dont remove this unless you know what you are doing.
395 meta_fake_bit = NoModifier;
397 // Can this happen now ?
398 if (func.action == LFUN_NOACTION)
399 func = FuncRequest(LFUN_COMMAND_PREFIX);
401 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
402 << keyseq.print(KeySequence::Portable) << ']');
404 // already here we know if it any point in going further
405 // why not return already here if action == -1 and
406 // num_bytes == 0? (Lgb)
408 if (keyseq.length() > 1)
409 lyx_view_->message(keyseq.print(KeySequence::ForGui));
412 // Maybe user can only reach the key via holding down shift.
413 // Let's see. But only if shift is the only modifier
414 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
415 LYXERR(Debug::KEY, "Trying without shift");
416 func = keyseq.addkey(keysym, NoModifier);
417 LYXERR(Debug::KEY, "Action now " << func.action);
420 if (func.action == LFUN_UNKNOWN_ACTION) {
421 // Hmm, we didn't match any of the keysequences. See
422 // if it's normal insertable text not already covered
424 if (keysym.isText() && keyseq.length() == 1) {
425 LYXERR(Debug::KEY, "isText() is true, inserting.");
426 func = FuncRequest(LFUN_SELF_INSERT,
427 FuncRequest::KEYBOARD);
429 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
430 lyx_view_->message(_("Unknown function."));
431 lyx_view_->restartCursor();
436 if (func.action == LFUN_SELF_INSERT) {
437 if (encoded_last_key != 0) {
438 docstring const arg(1, encoded_last_key);
439 dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
440 FuncRequest::KEYBOARD));
441 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
447 lyx_view_->restartCursor();
451 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
453 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
456 Buffer * buf = lyx_view_? lyx_view_->buffer() : 0;
458 if (cmd.action == LFUN_NOACTION) {
459 flag.message(from_utf8(N_("Nothing to do")));
464 switch (cmd.action) {
465 case LFUN_UNKNOWN_ACTION:
466 #ifndef HAVE_LIBAIKSAURUS
467 case LFUN_THESAURUS_ENTRY:
477 if (flag.unknown()) {
478 flag.message(from_utf8(N_("Unknown action")));
482 if (!flag.enabled()) {
483 if (flag.message().empty())
484 flag.message(from_utf8(N_("Command disabled")));
488 // Check whether we need a buffer
489 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
491 flag.message(from_utf8(N_("Command not allowed with"
492 "out any document open")));
497 // I would really like to avoid having this switch and rather try to
498 // encode this in the function itself.
499 // -- And I'd rather let an inset decide which LFUNs it is willing
500 // to handle (Andre')
502 switch (cmd.action) {
504 // FIXME: these cases should be hidden in GuiApplication::getStatus().
505 case LFUN_WINDOW_CLOSE:
507 return theApp()->getStatus(cmd);
511 // FIXME: these cases should be hidden in GuiView::getStatus().
512 case LFUN_DIALOG_TOGGLE:
513 case LFUN_DIALOG_SHOW:
514 case LFUN_DIALOG_UPDATE:
515 if (cmd.argument() == "prefs"
516 || cmd.argument() == "aboutlyx")
519 return lyx_view_->getStatus(cmd);
524 case LFUN_TOOLBAR_TOGGLE:
525 case LFUN_MENUBAR_TOGGLE:
526 case LFUN_STATUSBAR_TOGGLE:
527 case LFUN_INSET_APPLY:
528 case LFUN_BUFFER_WRITE:
529 case LFUN_BUFFER_WRITE_AS:
531 return lyx_view_->getStatus(cmd);
535 case LFUN_BUFFER_TOGGLE_READ_ONLY:
536 flag.setOnOff(buf->isReadonly());
539 case LFUN_BUFFER_SWITCH:
540 // toggle on the current buffer, but do not toggle off
541 // the other ones (is that a good idea?)
542 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
546 case LFUN_BUFFER_EXPORT:
547 enable = cmd.argument() == "custom"
548 || buf->isExportable(to_utf8(cmd.argument()));
551 case LFUN_BUFFER_CHKTEX:
552 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
555 case LFUN_BUILD_PROGRAM:
556 enable = buf->isExportable("program");
559 case LFUN_VC_REGISTER:
560 enable = !buf->lyxvc().inUse();
562 case LFUN_VC_CHECK_IN:
563 enable = buf->lyxvc().inUse() && !buf->isReadonly();
565 case LFUN_VC_CHECK_OUT:
566 enable = buf->lyxvc().inUse() && buf->isReadonly();
569 case LFUN_VC_UNDO_LAST:
570 enable = buf->lyxvc().inUse();
572 case LFUN_BUFFER_RELOAD:
573 enable = !buf->isUnnamed() && buf->fileName().exists()
574 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
577 case LFUN_CITATION_INSERT: {
578 FuncRequest fr(LFUN_INSET_INSERT, "citation");
579 enable = getStatus(fr).enabled();
583 // This could be used for the no-GUI version. The GUI version is handled in
584 // LyXView::getStatus(). See above.
586 case LFUN_BUFFER_WRITE:
587 case LFUN_BUFFER_WRITE_AS: {
588 Buffer * b = theBufferList().getBuffer(cmd.getArg(0));
589 enable = b && (b->isUnnamed() || !b->isClean());
594 case LFUN_BUFFER_WRITE_ALL: {
595 // We enable the command only if there are some modified buffers
596 Buffer * first = theBufferList().first();
601 // We cannot use a for loop as the buffer list is a cycle.
607 b = theBufferList().next(b);
608 } while (b != first);
612 case LFUN_BOOKMARK_GOTO: {
613 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
614 enable = LyX::ref().session().bookmarks().isValid(num);
618 case LFUN_BOOKMARK_CLEAR:
619 enable = LyX::ref().session().bookmarks().size() > 0;
622 // this one is difficult to get right. As a half-baked
623 // solution, we consider only the first action of the sequence
624 case LFUN_COMMAND_SEQUENCE: {
625 // argument contains ';'-terminated commands
626 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
627 FuncRequest func(lyxaction.lookupFunc(firstcmd));
628 func.origin = cmd.origin;
629 flag = getStatus(func);
635 string name = to_utf8(cmd.argument());
636 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
637 func.origin = cmd.origin;
638 flag = getStatus(func);
639 LyX::ref().topLevelCmdDef().release(name);
641 // catch recursion or unknown command definiton
642 // all operations until the recursion or unknown command
643 // definiton occures are performed, so set the state to enabled
649 case LFUN_BUFFER_NEW:
650 case LFUN_BUFFER_NEW_TEMPLATE:
651 case LFUN_WORD_FIND_FORWARD:
652 case LFUN_WORD_FIND_BACKWARD:
653 case LFUN_COMMAND_PREFIX:
654 case LFUN_COMMAND_EXECUTE:
656 case LFUN_META_PREFIX:
657 case LFUN_BUFFER_CLOSE:
658 case LFUN_BUFFER_UPDATE:
659 case LFUN_BUFFER_VIEW:
660 case LFUN_MASTER_BUFFER_UPDATE:
661 case LFUN_MASTER_BUFFER_VIEW:
662 case LFUN_BUFFER_IMPORT:
663 case LFUN_BUFFER_AUTO_SAVE:
664 case LFUN_RECONFIGURE:
668 case LFUN_DROP_LAYOUTS_CHOICE:
670 case LFUN_SERVER_GET_NAME:
671 case LFUN_SERVER_NOTIFY:
672 case LFUN_SERVER_GOTO_FILE_ROW:
673 case LFUN_DIALOG_HIDE:
674 case LFUN_DIALOG_DISCONNECT_INSET:
675 case LFUN_BUFFER_CHILD_OPEN:
676 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
677 case LFUN_KEYMAP_OFF:
678 case LFUN_KEYMAP_PRIMARY:
679 case LFUN_KEYMAP_SECONDARY:
680 case LFUN_KEYMAP_TOGGLE:
682 case LFUN_BUFFER_EXPORT_CUSTOM:
683 case LFUN_BUFFER_PRINT:
684 case LFUN_PREFERENCES_SAVE:
685 case LFUN_SCREEN_FONT_UPDATE:
688 case LFUN_EXTERNAL_EDIT:
689 case LFUN_GRAPHICS_EDIT:
690 case LFUN_ALL_INSETS_TOGGLE:
691 case LFUN_BUFFER_LANGUAGE:
692 case LFUN_TEXTCLASS_APPLY:
693 case LFUN_TEXTCLASS_LOAD:
694 case LFUN_BUFFER_SAVE_AS_DEFAULT:
695 case LFUN_BUFFER_PARAMS_APPLY:
696 case LFUN_LAYOUT_MODULES_CLEAR:
697 case LFUN_LAYOUT_MODULE_ADD:
698 case LFUN_LAYOUT_RELOAD:
699 case LFUN_LYXRC_APPLY:
700 case LFUN_BUFFER_NEXT:
701 case LFUN_BUFFER_PREVIOUS:
702 case LFUN_WINDOW_NEW:
704 // these are handled in our dispatch()
712 if (!getLocalStatus(view()->cursor(), cmd, flag))
713 flag = view()->getStatus(cmd);
719 // Can we use a readonly buffer?
720 if (buf && buf->isReadonly()
721 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
722 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
723 flag.message(from_utf8(N_("Document is read-only")));
727 // Are we in a DELETED change-tracking region?
729 && lookupChangeType(view()->cursor(), true) == Change::DELETED
730 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
731 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
732 flag.message(from_utf8(N_("This portion of the document is deleted.")));
736 // the default error message if we disable the command
737 if (!flag.enabled() && flag.message().empty())
738 flag.message(from_utf8(N_("Command disabled")));
744 bool LyXFunc::ensureBufferClean(BufferView * bv)
746 Buffer & buf = bv->buffer();
750 docstring const file = buf.fileName().displayName(30);
751 docstring text = bformat(_("The document %1$s has unsaved "
752 "changes.\n\nDo you want to save "
753 "the document?"), file);
754 int const ret = Alert::prompt(_("Save changed document?"),
755 text, 0, 1, _("&Save"),
759 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
761 return buf.isClean();
767 void showPrintError(string const & name)
769 docstring str = bformat(_("Could not print the document %1$s.\n"
770 "Check that your printer is set up correctly."),
771 makeDisplayPath(name, 50));
772 Alert::error(_("Print document failed"), str);
776 void loadTextClass(string const & name)
778 pair<bool, textclass_type> const tc_pair =
779 textclasslist.numberOfClass(name);
781 if (!tc_pair.first) {
782 lyxerr << "Document class \"" << name
783 << "\" does not exist."
788 textclass_type const tc = tc_pair.second;
790 if (!textclasslist[tc].load()) {
791 docstring s = bformat(_("The document class %1$s."
792 "could not be loaded."),
793 from_utf8(textclasslist[tc].name()));
794 Alert::error(_("Could not load class"), s);
799 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
804 void LyXFunc::dispatch(FuncRequest const & cmd)
806 string const argument = to_utf8(cmd.argument());
807 kb_action const action = cmd.action;
809 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
810 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
812 // we have not done anything wrong yet.
814 dispatch_buffer.erase();
816 // redraw the screen at the end (first of the two drawing steps).
817 //This is done unless explicitely requested otherwise
818 Update::flags updateFlags = Update::FitCursor;
820 FuncStatus const flag = getStatus(cmd);
821 if (!flag.enabled()) {
822 // We cannot use this function here
823 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
824 << lyxaction.getActionName(action)
825 << " [" << action << "] is disabled at this location");
826 setErrorMessage(flag.message());
830 case LFUN_WORD_FIND_FORWARD:
831 case LFUN_WORD_FIND_BACKWARD: {
832 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
833 static docstring last_search;
834 docstring searched_string;
836 if (!cmd.argument().empty()) {
837 last_search = cmd.argument();
838 searched_string = cmd.argument();
840 searched_string = last_search;
843 if (searched_string.empty())
846 bool const fw = action == LFUN_WORD_FIND_FORWARD;
847 docstring const data =
848 find2string(searched_string, true, false, fw);
849 find(view(), FuncRequest(LFUN_WORD_FIND, data));
853 case LFUN_COMMAND_PREFIX:
854 BOOST_ASSERT(lyx_view_);
855 lyx_view_->message(keyseq.printOptions(true));
859 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
861 meta_fake_bit = NoModifier;
862 if (lyx_view_->buffer())
863 // cancel any selection
864 dispatch(FuncRequest(LFUN_MARK_OFF));
865 setMessage(from_ascii(N_("Cancel")));
868 case LFUN_META_PREFIX:
869 meta_fake_bit = AltModifier;
870 setMessage(keyseq.print(KeySequence::ForGui));
873 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
874 BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
875 Buffer * buf = lyx_view_->buffer();
876 if (buf->lyxvc().inUse())
877 buf->lyxvc().toggleReadOnly();
879 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
883 // --- Menus -----------------------------------------------
884 case LFUN_BUFFER_NEW:
885 lyx_view_->newDocument(argument, false);
886 updateFlags = Update::None;
889 case LFUN_BUFFER_NEW_TEMPLATE:
890 lyx_view_->newDocument(argument, true);
891 updateFlags = Update::None;
894 case LFUN_BUFFER_CLOSE:
896 updateFlags = Update::None;
899 case LFUN_BUFFER_RELOAD: {
900 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
901 docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
902 docstring text = bformat(_("Any changes will be lost. Are you sure "
903 "you want to revert to the saved version of the document %1$s?"), file);
904 int const ret = Alert::prompt(_("Revert to saved document?"),
905 text, 1, 1, _("&Revert"), _("&Cancel"));
912 case LFUN_BUFFER_UPDATE:
913 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
914 lyx_view_->buffer()->doExport(argument, true);
917 case LFUN_BUFFER_VIEW:
918 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
919 lyx_view_->buffer()->preview(argument);
922 case LFUN_MASTER_BUFFER_UPDATE:
923 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
924 lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
927 case LFUN_MASTER_BUFFER_VIEW:
928 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
929 lyx_view_->buffer()->masterBuffer()->preview(argument);
932 case LFUN_BUILD_PROGRAM:
933 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
934 lyx_view_->buffer()->doExport("program", true);
937 case LFUN_BUFFER_CHKTEX:
938 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
939 lyx_view_->buffer()->runChktex();
942 case LFUN_BUFFER_EXPORT:
943 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
944 if (argument == "custom")
945 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
947 lyx_view_->buffer()->doExport(argument, false);
950 case LFUN_BUFFER_EXPORT_CUSTOM: {
951 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
953 string command = split(argument, format_name, ' ');
954 Format const * format = formats.getFormat(format_name);
956 lyxerr << "Format \"" << format_name
957 << "\" not recognized!"
962 Buffer * buffer = lyx_view_->buffer();
964 // The name of the file created by the conversion process
967 // Output to filename
968 if (format->name() == "lyx") {
969 string const latexname = buffer->latexName(false);
970 filename = changeExtension(latexname,
971 format->extension());
972 filename = addName(buffer->temppath(), filename);
974 if (!buffer->writeFile(FileName(filename)))
978 buffer->doExport(format_name, true, filename);
981 // Substitute $$FName for filename
982 if (!contains(command, "$$FName"))
983 command = "( " + command + " ) < $$FName";
984 command = subst(command, "$$FName", filename);
986 // Execute the command in the background
988 call.startscript(Systemcall::DontWait, command);
992 case LFUN_BUFFER_PRINT: {
993 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
994 // FIXME: cmd.getArg() might fail if one of the arguments
995 // contains double quotes
996 string target = cmd.getArg(0);
997 string target_name = cmd.getArg(1);
998 string command = cmd.getArg(2);
1001 || target_name.empty()
1002 || command.empty()) {
1003 lyxerr << "Unable to parse \""
1004 << argument << '"' << endl;
1007 if (target != "printer" && target != "file") {
1008 lyxerr << "Unrecognized target \""
1009 << target << '"' << endl;
1013 Buffer * buffer = lyx_view_->buffer();
1015 if (!buffer->doExport("dvi", true)) {
1016 showPrintError(buffer->absFileName());
1020 // Push directory path.
1021 string const path = buffer->temppath();
1022 // Prevent the compiler from optimizing away p
1026 // there are three cases here:
1027 // 1. we print to a file
1028 // 2. we print directly to a printer
1029 // 3. we print using a spool command (print to file first)
1032 string const dviname =
1033 changeExtension(buffer->latexName(true), "dvi");
1035 if (target == "printer") {
1036 if (!lyxrc.print_spool_command.empty()) {
1037 // case 3: print using a spool
1038 string const psname =
1039 changeExtension(dviname,".ps");
1040 command += ' ' + lyxrc.print_to_file
1043 + quoteName(dviname);
1046 lyxrc.print_spool_command + ' ';
1047 if (target_name != "default") {
1048 command2 += lyxrc.print_spool_printerprefix
1052 command2 += quoteName(psname);
1054 // If successful, then spool command
1055 res = one.startscript(
1060 res = one.startscript(
1061 Systemcall::DontWait,
1064 // case 2: print directly to a printer
1065 if (target_name != "default")
1066 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1067 res = one.startscript(
1068 Systemcall::DontWait,
1069 command + quoteName(dviname));
1073 // case 1: print to a file
1074 FileName const filename(makeAbsPath(target_name,
1075 lyx_view_->buffer()->filePath()));
1076 FileName const dvifile(makeAbsPath(dviname, path));
1077 if (filename.exists()) {
1078 docstring text = bformat(
1079 _("The file %1$s already exists.\n\n"
1080 "Do you want to overwrite that file?"),
1081 makeDisplayPath(filename.absFilename()));
1082 if (Alert::prompt(_("Overwrite file?"),
1083 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1086 command += ' ' + lyxrc.print_to_file
1087 + quoteName(filename.toFilesystemEncoding())
1089 + quoteName(dvifile.toFilesystemEncoding());
1090 res = one.startscript(Systemcall::DontWait,
1095 showPrintError(buffer->absFileName());
1099 case LFUN_BUFFER_IMPORT:
1103 case LFUN_BUFFER_AUTO_SAVE:
1104 lyx_view_->buffer()->autoSave();
1107 case LFUN_RECONFIGURE:
1108 BOOST_ASSERT(lyx_view_);
1109 // argument is any additional parameter to the configure.py command
1110 reconfigure(*lyx_view_, argument);
1113 case LFUN_HELP_OPEN: {
1114 BOOST_ASSERT(lyx_view_);
1115 string const arg = argument;
1117 setErrorMessage(from_ascii(N_("Missing argument")));
1120 FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1121 if (fname.empty()) {
1122 lyxerr << "LyX: unable to find documentation file `"
1123 << arg << "'. Bad installation?" << endl;
1126 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1127 makeDisplayPath(fname.absFilename())));
1128 Buffer * buf = lyx_view_->loadDocument(fname, false);
1131 lyx_view_->setBuffer(buf);
1132 buf->errors("Parse");
1134 updateFlags = Update::None;
1138 // --- version control -------------------------------
1139 case LFUN_VC_REGISTER:
1140 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1141 if (!ensureBufferClean(view()))
1143 if (!lyx_view_->buffer()->lyxvc().inUse()) {
1144 lyx_view_->buffer()->lyxvc().registrer();
1147 updateFlags = Update::Force;
1150 case LFUN_VC_CHECK_IN:
1151 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1152 if (!ensureBufferClean(view()))
1154 if (lyx_view_->buffer()->lyxvc().inUse()
1155 && !lyx_view_->buffer()->isReadonly()) {
1156 lyx_view_->buffer()->lyxvc().checkIn();
1161 case LFUN_VC_CHECK_OUT:
1162 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1163 if (!ensureBufferClean(view()))
1165 if (lyx_view_->buffer()->lyxvc().inUse()
1166 && lyx_view_->buffer()->isReadonly()) {
1167 lyx_view_->buffer()->lyxvc().checkOut();
1172 case LFUN_VC_REVERT:
1173 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1174 lyx_view_->buffer()->lyxvc().revert();
1178 case LFUN_VC_UNDO_LAST:
1179 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1180 lyx_view_->buffer()->lyxvc().undoLast();
1184 // --- buffers ----------------------------------------
1186 case LFUN_FILE_NEW: {
1187 BOOST_ASSERT(lyx_view_);
1189 string tmpname = split(argument, name, ':'); // Split filename
1190 Buffer * const b = newFile(name, tmpname);
1192 lyx_view_->setBuffer(b);
1193 updateFlags = Update::None;
1197 // --- lyxserver commands ----------------------------
1198 case LFUN_SERVER_GET_NAME:
1199 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1200 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1201 LYXERR(Debug::INFO, "FNAME["
1202 << lyx_view_->buffer()->absFileName() << ']');
1205 case LFUN_SERVER_NOTIFY:
1206 dispatch_buffer = keyseq.print(KeySequence::Portable);
1207 theServer().notifyClient(to_utf8(dispatch_buffer));
1210 case LFUN_SERVER_GOTO_FILE_ROW: {
1211 BOOST_ASSERT(lyx_view_);
1214 istringstream is(argument);
1215 is >> file_name >> row;
1217 bool loaded = false;
1218 if (prefixIs(file_name, package().temp_dir().absFilename()))
1219 // Needed by inverse dvi search. If it is a file
1220 // in tmpdir, call the apropriated function
1221 buf = theBufferList().getBufferFromTmp(file_name);
1223 // Must replace extension of the file to be .lyx
1224 // and get full path
1225 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1226 // Either change buffer or load the file
1227 if (theBufferList().exists(s.absFilename()))
1228 buf = theBufferList().getBuffer(s.absFilename());
1230 buf = lyx_view_->loadDocument(s);
1236 updateFlags = Update::None;
1241 lyx_view_->setBuffer(buf);
1242 view()->setCursorFromRow(row);
1244 buf->errors("Parse");
1245 updateFlags = Update::FitCursor;
1250 case LFUN_DIALOG_SHOW_NEW_INSET: {
1251 BOOST_ASSERT(lyx_view_);
1252 string const name = cmd.getArg(0);
1253 InsetCode code = insetCode(name);
1254 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1255 bool insetCodeOK = true;
1264 case HYPERLINK_CODE: {
1265 InsetCommandParams p(code);
1266 data = InsetCommandMailer::params2string(name, p);
1269 case INCLUDE_CODE: {
1270 // data is the include type: one of "include",
1271 // "input", "verbatiminput" or "verbatiminput*"
1273 // default type is requested
1275 InsetCommandParams p(INCLUDE_CODE, data);
1276 data = InsetCommandMailer::params2string("include", p);
1280 // \c data == "Boxed" || "Frameless" etc
1281 InsetBoxParams p(data);
1282 data = InsetBoxMailer::params2string(p);
1286 InsetBranchParams p;
1287 data = InsetBranchMailer::params2string(p);
1291 InsetCommandParams p(CITE_CODE);
1292 data = InsetCommandMailer::params2string(name, p);
1296 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1299 case EXTERNAL_CODE: {
1300 InsetExternalParams p;
1301 Buffer const & buffer = *lyx_view_->buffer();
1302 data = InsetExternalMailer::params2string(p, buffer);
1307 data = InsetFloatMailer::params2string(p);
1310 case LISTINGS_CODE: {
1311 InsetListingsParams p;
1312 data = InsetListingsMailer::params2string(p);
1315 case GRAPHICS_CODE: {
1316 InsetGraphicsParams p;
1317 Buffer const & buffer = *lyx_view_->buffer();
1318 data = InsetGraphicsMailer::params2string(p, buffer);
1323 data = InsetNoteMailer::params2string(p);
1328 data = InsetVSpaceMailer::params2string(space);
1333 data = InsetWrapMailer::params2string(p);
1337 lyxerr << "Inset type '" << name <<
1338 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1339 insetCodeOK = false;
1341 } // end switch(code)
1343 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1347 case LFUN_CITATION_INSERT: {
1348 BOOST_ASSERT(lyx_view_);
1349 if (!argument.empty()) {
1350 // we can have one optional argument, delimited by '|'
1351 // citation-insert <key>|<text_before>
1352 // this should be enhanced to also support text_after
1353 // and citation style
1354 string arg = argument;
1356 if (contains(argument, "|")) {
1357 arg = token(argument, '|', 0);
1358 opt1 = token(argument, '|', 1);
1360 InsetCommandParams icp(CITE_CODE);
1361 icp["key"] = from_utf8(arg);
1363 icp["before"] = from_utf8(opt1);
1364 string icstr = InsetCommandMailer::params2string("citation", icp);
1365 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1368 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1372 case LFUN_BUFFER_CHILD_OPEN: {
1373 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1374 Buffer * parent = lyx_view_->buffer();
1375 FileName filename = makeAbsPath(argument, parent->filePath());
1376 view()->saveBookmark(false);
1378 bool parsed = false;
1379 if (theBufferList().exists(filename.absFilename())) {
1380 child = theBufferList().getBuffer(filename.absFilename());
1382 setMessage(bformat(_("Opening child document %1$s..."),
1383 makeDisplayPath(filename.absFilename())));
1384 child = lyx_view_->loadDocument(filename, false);
1388 // Set the parent name of the child document.
1389 // This makes insertion of citations and references in the child work,
1390 // when the target is in the parent or another child document.
1391 child->setParent(parent);
1392 updateLabels(*child->masterBuffer());
1393 lyx_view_->setBuffer(child);
1395 child->errors("Parse");
1398 // If a screen update is required (in case where auto_open is false),
1399 // setBuffer() would have taken care of it already. Otherwise we shall
1400 // reset the update flag because it can cause a circular problem.
1402 updateFlags = Update::None;
1406 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1407 BOOST_ASSERT(lyx_view_);
1408 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1411 case LFUN_KEYMAP_OFF:
1412 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1413 lyx_view_->view()->getIntl().keyMapOn(false);
1416 case LFUN_KEYMAP_PRIMARY:
1417 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1418 lyx_view_->view()->getIntl().keyMapPrim();
1421 case LFUN_KEYMAP_SECONDARY:
1422 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1423 lyx_view_->view()->getIntl().keyMapSec();
1426 case LFUN_KEYMAP_TOGGLE:
1427 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1428 lyx_view_->view()->getIntl().toggleKeyMap();
1434 string rest = split(argument, countstr, ' ');
1435 istringstream is(countstr);
1438 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1439 for (int i = 0; i < count; ++i)
1440 dispatch(lyxaction.lookupFunc(rest));
1444 case LFUN_COMMAND_SEQUENCE: {
1445 // argument contains ';'-terminated commands
1446 string arg = argument;
1447 while (!arg.empty()) {
1449 arg = split(arg, first, ';');
1450 FuncRequest func(lyxaction.lookupFunc(first));
1451 func.origin = cmd.origin;
1459 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1460 func.origin = cmd.origin;
1462 LyX::ref().topLevelCmdDef().release(argument);
1464 if (func.action == LFUN_UNKNOWN_ACTION) {
1465 // unknown command definition
1466 lyxerr << "Warning: unknown command definition `"
1470 // recursion detected
1471 lyxerr << "Warning: Recursion in the command definition `"
1472 << argument << "' detected"
1479 case LFUN_PREFERENCES_SAVE: {
1480 lyxrc.write(makeAbsPath("preferences",
1481 package().user_support().absFilename()),
1486 case LFUN_SET_COLOR: {
1488 string const x11_name = split(argument, lyx_name, ' ');
1489 if (lyx_name.empty() || x11_name.empty()) {
1490 setErrorMessage(from_ascii(N_(
1491 "Syntax: set-color <lyx_name>"
1496 bool const graphicsbg_changed =
1497 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1498 x11_name != lcolor.getX11Name(Color_graphicsbg));
1500 if (!lcolor.setColor(lyx_name, x11_name)) {
1502 bformat(_("Set-color \"%1$s\" failed "
1503 "- color is undefined or "
1504 "may not be redefined"),
1505 from_utf8(lyx_name)));
1509 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1511 if (graphicsbg_changed) {
1512 // FIXME: The graphics cache no longer has a changeDisplay method.
1514 graphics::GCache::get().changeDisplay(true);
1521 BOOST_ASSERT(lyx_view_);
1522 lyx_view_->message(from_utf8(argument));
1525 case LFUN_EXTERNAL_EDIT: {
1526 BOOST_ASSERT(lyx_view_);
1527 FuncRequest fr(action, argument);
1528 InsetExternal().dispatch(view()->cursor(), fr);
1532 case LFUN_GRAPHICS_EDIT: {
1533 FuncRequest fr(action, argument);
1534 InsetGraphics().dispatch(view()->cursor(), fr);
1538 case LFUN_ALL_INSETS_TOGGLE: {
1539 BOOST_ASSERT(lyx_view_);
1541 string const name = split(argument, action, ' ');
1542 InsetCode const inset_code = insetCode(name);
1544 Cursor & cur = view()->cursor();
1545 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1547 Inset & inset = lyx_view_->buffer()->inset();
1548 InsetIterator it = inset_iterator_begin(inset);
1549 InsetIterator const end = inset_iterator_end(inset);
1550 for (; it != end; ++it) {
1551 if (!it->asInsetMath()
1552 && (inset_code == NO_CODE
1553 || inset_code == it->lyxCode())) {
1554 Cursor tmpcur = cur;
1555 tmpcur.pushBackward(*it);
1556 it->dispatch(tmpcur, fr);
1559 updateFlags = Update::Force | Update::FitCursor;
1563 case LFUN_BUFFER_LANGUAGE: {
1564 BOOST_ASSERT(lyx_view_);
1565 Buffer & buffer = *lyx_view_->buffer();
1566 Language const * oldL = buffer.params().language;
1567 Language const * newL = languages.getLanguage(argument);
1568 if (!newL || oldL == newL)
1571 if (oldL->rightToLeft() == newL->rightToLeft()
1572 && !buffer.isMultiLingual())
1573 buffer.changeLanguage(oldL, newL);
1577 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1578 string const fname =
1579 addName(addPath(package().user_support().absFilename(), "templates/"),
1581 Buffer defaults(fname);
1583 istringstream ss(argument);
1586 int const unknown_tokens = defaults.readHeader(lex);
1588 if (unknown_tokens != 0) {
1589 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1590 << unknown_tokens << " unknown token"
1591 << (unknown_tokens == 1 ? "" : "s")
1595 if (defaults.writeFile(FileName(defaults.absFileName())))
1596 setMessage(bformat(_("Document defaults saved in %1$s"),
1597 makeDisplayPath(fname)));
1599 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1603 case LFUN_BUFFER_PARAMS_APPLY: {
1604 BOOST_ASSERT(lyx_view_);
1605 biblio::CiteEngine const oldEngine =
1606 lyx_view_->buffer()->params().getEngine();
1608 Buffer * buffer = lyx_view_->buffer();
1610 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1612 Cursor & cur = view()->cursor();
1613 cur.recordUndoFullDocument();
1615 istringstream ss(argument);
1618 int const unknown_tokens = buffer->readHeader(lex);
1620 if (unknown_tokens != 0) {
1621 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1622 << unknown_tokens << " unknown token"
1623 << (unknown_tokens == 1 ? "" : "s")
1627 updateLayout(oldClass, buffer);
1629 biblio::CiteEngine const newEngine =
1630 lyx_view_->buffer()->params().getEngine();
1632 if (oldEngine != newEngine) {
1633 FuncRequest fr(LFUN_INSET_REFRESH);
1635 Inset & inset = lyx_view_->buffer()->inset();
1636 InsetIterator it = inset_iterator_begin(inset);
1637 InsetIterator const end = inset_iterator_end(inset);
1638 for (; it != end; ++it)
1639 if (it->lyxCode() == CITE_CODE)
1640 it->dispatch(cur, fr);
1643 updateFlags = Update::Force | Update::FitCursor;
1644 // We are here most certainaly because of a change in the document
1645 // It is then better to make sure that all dialogs are in sync
1646 // with current document settings. LyXView::restartCursor() achieve this.
1647 lyx_view_->restartCursor();
1651 case LFUN_LAYOUT_MODULES_CLEAR: {
1652 BOOST_ASSERT(lyx_view_);
1653 Buffer * buffer = lyx_view_->buffer();
1654 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1655 view()->cursor().recordUndoFullDocument();
1656 buffer->params().clearLayoutModules();
1657 buffer->params().makeTextClass();
1658 updateLayout(oldClass, buffer);
1659 updateFlags = Update::Force | Update::FitCursor;
1663 case LFUN_LAYOUT_MODULE_ADD: {
1664 BOOST_ASSERT(lyx_view_);
1665 Buffer * buffer = lyx_view_->buffer();
1666 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1667 view()->cursor().recordUndoFullDocument();
1668 buffer->params().addLayoutModule(argument);
1669 buffer->params().makeTextClass();
1670 updateLayout(oldClass, buffer);
1671 updateFlags = Update::Force | Update::FitCursor;
1675 case LFUN_TEXTCLASS_APPLY: {
1676 BOOST_ASSERT(lyx_view_);
1677 Buffer * buffer = lyx_view_->buffer();
1679 loadTextClass(argument);
1681 pair<bool, textclass_type> const tc_pair =
1682 textclasslist.numberOfClass(argument);
1687 textclass_type const old_class = buffer->params().getBaseClass();
1688 textclass_type const new_class = tc_pair.second;
1690 if (old_class == new_class)
1694 //Save the old, possibly modular, layout for use in conversion.
1695 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1696 view()->cursor().recordUndoFullDocument();
1697 buffer->params().setBaseClass(new_class);
1698 buffer->params().makeTextClass();
1699 updateLayout(oldClass, buffer);
1700 updateFlags = Update::Force | Update::FitCursor;
1704 case LFUN_LAYOUT_RELOAD: {
1705 BOOST_ASSERT(lyx_view_);
1706 Buffer * buffer = lyx_view_->buffer();
1707 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1708 textclass_type const tc = buffer->params().getBaseClass();
1709 textclasslist.reset(tc);
1710 buffer->params().setBaseClass(tc);
1711 buffer->params().makeTextClass();
1712 updateLayout(oldClass, buffer);
1713 updateFlags = Update::Force | Update::FitCursor;
1717 case LFUN_TEXTCLASS_LOAD:
1718 loadTextClass(argument);
1721 case LFUN_LYXRC_APPLY: {
1722 LyXRC const lyxrc_orig = lyxrc;
1724 istringstream ss(argument);
1725 bool const success = lyxrc.read(ss) == 0;
1728 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1729 << "Unable to read lyxrc data"
1734 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1736 theApp()->resetGui();
1738 /// We force the redraw in any case because there might be
1739 /// some screen font changes.
1740 /// FIXME: only the current view will be updated. the Gui
1741 /// class is able to furnish the list of views.
1742 updateFlags = Update::Force;
1746 case LFUN_BOOKMARK_GOTO:
1747 // go to bookmark, open unopened file and switch to buffer if necessary
1748 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1749 updateFlags = Update::FitCursor;
1752 case LFUN_BOOKMARK_CLEAR:
1753 LyX::ref().session().bookmarks().clear();
1757 BOOST_ASSERT(theApp());
1758 // Let the frontend dispatch its own actions.
1759 if (theApp()->dispatch(cmd))
1760 // Nothing more to do.
1763 // Let the current LyXView dispatch its own actions.
1764 BOOST_ASSERT(lyx_view_);
1765 if (lyx_view_->dispatch(cmd)) {
1766 if (lyx_view_->view())
1767 updateFlags = lyx_view_->view()->cursor().result().update();
1771 BOOST_ASSERT(lyx_view_->view());
1772 // Let the current BufferView dispatch its own actions.
1773 if (view()->dispatch(cmd)) {
1774 // The BufferView took care of its own updates if needed.
1775 updateFlags = Update::None;
1779 // Let the current Cursor dispatch its own actions.
1780 view()->cursor().getPos(cursorPosBeforeDispatchX_,
1781 cursorPosBeforeDispatchY_);
1782 view()->cursor().dispatch(cmd);
1783 updateFlags = view()->cursor().result().update();
1784 if (!view()->cursor().result().dispatched()) {
1785 // No update needed in this case (e.g. when reaching
1787 updateFlags = Update::None;
1791 if (lyx_view_ && lyx_view_->buffer()) {
1792 // BufferView::update() updates the ViewMetricsInfo and
1793 // also initializes the position cache for all insets in
1794 // (at least partially) visible top-level paragraphs.
1795 // We will redraw the screen only if needed.
1796 view()->processUpdateFlags(updateFlags);
1798 // if we executed a mutating lfun, mark the buffer as dirty
1800 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1801 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1802 lyx_view_->buffer()->markDirty();
1804 //Do we have a selection?
1805 theSelection().haveSelection(view()->cursor().selection());
1808 if (!quitting && lyx_view_) {
1809 // Some messages may already be translated, so we cannot use _()
1810 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1815 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1817 const bool verbose = (cmd.origin == FuncRequest::MENU
1818 || cmd.origin == FuncRequest::TOOLBAR
1819 || cmd.origin == FuncRequest::COMMANDBUFFER);
1821 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1822 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1824 lyx_view_->message(msg);
1828 docstring dispatch_msg = msg;
1829 if (!dispatch_msg.empty())
1830 dispatch_msg += ' ';
1832 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1834 bool argsadded = false;
1836 if (!cmd.argument().empty()) {
1837 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1838 comname += ' ' + cmd.argument();
1843 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1845 if (!shortcuts.empty())
1846 comname += ": " + shortcuts;
1847 else if (!argsadded && !cmd.argument().empty())
1848 comname += ' ' + cmd.argument();
1850 if (!comname.empty()) {
1851 comname = rtrim(comname);
1852 dispatch_msg += '(' + rtrim(comname) + ')';
1855 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1856 if (!dispatch_msg.empty())
1857 lyx_view_->message(dispatch_msg);
1861 void LyXFunc::doImport(string const & argument)
1864 string filename = split(argument, format, ' ');
1866 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
1867 << " file: " << filename);
1869 // need user interaction
1870 if (filename.empty()) {
1871 string initpath = lyxrc.document_path;
1873 if (lyx_view_->buffer()) {
1874 string const trypath = lyx_view_->buffer()->filePath();
1875 // If directory is writeable, use this as default.
1876 if (FileName(trypath).isDirWritable())
1880 docstring const text = bformat(_("Select %1$s file to import"),
1881 formats.prettyName(format));
1883 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
1884 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1885 dlg.setButton2(_("Examples|#E#e"),
1886 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1888 docstring filter = formats.prettyName(format);
1891 filter += from_utf8(formats.extension(format));
1894 FileDialog::Result result =
1895 dlg.open(from_utf8(initpath),
1896 FileFilterList(filter),
1899 if (result.first == FileDialog::Later)
1902 filename = to_utf8(result.second);
1904 // check selected filename
1905 if (filename.empty())
1906 lyx_view_->message(_("Canceled."));
1909 if (filename.empty())
1912 // get absolute path of file
1913 FileName const fullname(makeAbsPath(filename));
1915 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
1917 // Check if the document already is open
1918 Buffer * buf = theBufferList().getBuffer(lyxfile.absFilename());
1919 if (use_gui && buf) {
1920 lyx_view_->setBuffer(buf);
1921 if (!lyx_view_->closeBuffer()) {
1922 lyx_view_->message(_("Canceled."));
1927 // if the file exists already, and we didn't do
1928 // -i lyx thefile.lyx, warn
1929 if (lyxfile.exists() && fullname != lyxfile) {
1930 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
1932 docstring text = bformat(_("The document %1$s already exists.\n\n"
1933 "Do you want to overwrite that document?"), file);
1934 int const ret = Alert::prompt(_("Overwrite document?"),
1935 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1938 lyx_view_->message(_("Canceled."));
1943 ErrorList errorList;
1944 import(lyx_view_, fullname, format, errorList);
1945 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1949 void LyXFunc::closeBuffer()
1951 // goto bookmark to update bookmark pit.
1952 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
1953 gotoBookmark(i+1, false, false);
1955 lyx_view_->closeBuffer();
1959 void LyXFunc::reloadBuffer()
1961 FileName filename = lyx_view_->buffer()->fileName();
1962 // The user has already confirmed that the changes, if any, should
1963 // be discarded. So we just release the Buffer and don't call closeBuffer();
1964 theBufferList().release(lyx_view_->buffer());
1965 Buffer * buf = lyx_view_->loadDocument(filename);
1966 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1970 lyx_view_->setBuffer(buf);
1971 buf->errors("Parse");
1972 str = bformat(_("Document %1$s reloaded."), disp_fn);
1974 str = bformat(_("Could not reload document %1$s"), disp_fn);
1976 lyx_view_->message(str);
1979 // Each "lyx_view_" should have it's own message method. lyxview and
1980 // the minibuffer would use the minibuffer, but lyxserver would
1981 // send an ERROR signal to its client. Alejandro 970603
1982 // This function is bit problematic when it comes to NLS, to make the
1983 // lyx servers client be language indepenent we must not translate
1984 // strings sent to this func.
1985 void LyXFunc::setErrorMessage(docstring const & m) const
1987 dispatch_buffer = m;
1992 void LyXFunc::setMessage(docstring const & m) const
1994 dispatch_buffer = m;
1998 docstring const LyXFunc::viewStatusMessage()
2000 // When meta-fake key is pressed, show the key sequence so far + "M-".
2002 return keyseq.print(KeySequence::ForGui) + "M-";
2004 // Else, when a non-complete key sequence is pressed,
2005 // show the available options.
2006 if (keyseq.length() > 0 && !keyseq.deleted())
2007 return keyseq.printOptions(true);
2009 BOOST_ASSERT(lyx_view_);
2010 if (!lyx_view_->buffer())
2011 return _("Welcome to LyX!");
2013 return view()->cursor().currentState();
2017 BufferView * LyXFunc::view() const
2019 BOOST_ASSERT(lyx_view_);
2020 return lyx_view_->view();
2024 bool LyXFunc::wasMetaKey() const
2026 return (meta_fake_bit != NoModifier);
2030 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2033 lyx_view_->message(_("Converting document to new document class..."));
2035 StableDocIterator backcur(view()->cursor());
2036 ErrorList & el = buffer->errorList("Class Switch");
2037 cap::switchBetweenClasses(
2038 oldlayout, buffer->params().getTextClassPtr(),
2039 static_cast<InsetText &>(buffer->inset()), el);
2041 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2043 buffer->errors("Class Switch");
2044 updateLabels(*buffer);
2050 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2052 // Why the switch you might ask. It is a trick to ensure that all
2053 // the elements in the LyXRCTags enum is handled. As you can see
2054 // there are no breaks at all. So it is just a huge fall-through.
2055 // The nice thing is that we will get a warning from the compiler
2056 // if we forget an element.
2057 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2059 case LyXRC::RC_ACCEPT_COMPOUND:
2060 case LyXRC::RC_ALT_LANG:
2061 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2062 case LyXRC::RC_PLAINTEXT_LINELEN:
2063 case LyXRC::RC_AUTOREGIONDELETE:
2064 case LyXRC::RC_AUTORESET_OPTIONS:
2065 case LyXRC::RC_AUTOSAVE:
2066 case LyXRC::RC_AUTO_NUMBER:
2067 case LyXRC::RC_BACKUPDIR_PATH:
2068 case LyXRC::RC_BIBTEX_COMMAND:
2069 case LyXRC::RC_BINDFILE:
2070 case LyXRC::RC_CHECKLASTFILES:
2071 case LyXRC::RC_USELASTFILEPOS:
2072 case LyXRC::RC_LOADSESSION:
2073 case LyXRC::RC_CHKTEX_COMMAND:
2074 case LyXRC::RC_CONVERTER:
2075 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2076 case LyXRC::RC_COPIER:
2077 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2078 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2079 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2080 case LyXRC::RC_DATE_INSERT_FORMAT:
2081 case LyXRC::RC_DEFAULT_LANGUAGE:
2082 case LyXRC::RC_DEFAULT_PAPERSIZE:
2083 case LyXRC::RC_DEFFILE:
2084 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2085 case LyXRC::RC_DISPLAY_GRAPHICS:
2086 case LyXRC::RC_DOCUMENTPATH:
2087 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2088 FileName path(lyxrc_new.document_path);
2089 if (path.exists() && path.isDirectory())
2090 package().document_dir() = FileName(lyxrc.document_path);
2092 case LyXRC::RC_ESC_CHARS:
2093 case LyXRC::RC_EXAMPLEPATH:
2094 case LyXRC::RC_FONT_ENCODING:
2095 case LyXRC::RC_FORMAT:
2096 case LyXRC::RC_INDEX_COMMAND:
2097 case LyXRC::RC_INPUT:
2098 case LyXRC::RC_KBMAP:
2099 case LyXRC::RC_KBMAP_PRIMARY:
2100 case LyXRC::RC_KBMAP_SECONDARY:
2101 case LyXRC::RC_LABEL_INIT_LENGTH:
2102 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2103 case LyXRC::RC_LANGUAGE_AUTO_END:
2104 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2105 case LyXRC::RC_LANGUAGE_COMMAND_END:
2106 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2107 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2108 case LyXRC::RC_LANGUAGE_PACKAGE:
2109 case LyXRC::RC_LANGUAGE_USE_BABEL:
2110 case LyXRC::RC_MACRO_EDIT_STYLE:
2111 case LyXRC::RC_MAKE_BACKUP:
2112 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2113 case LyXRC::RC_MOUSE_WHEEL_SPEED:
2114 case LyXRC::RC_NUMLASTFILES:
2115 case LyXRC::RC_PATH_PREFIX:
2116 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2117 prependEnvPath("PATH", lyxrc.path_prefix);
2119 case LyXRC::RC_PERS_DICT:
2120 case LyXRC::RC_PREVIEW:
2121 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2122 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2123 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2124 case LyXRC::RC_PRINTCOPIESFLAG:
2125 case LyXRC::RC_PRINTER:
2126 case LyXRC::RC_PRINTEVENPAGEFLAG:
2127 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2128 case LyXRC::RC_PRINTFILEEXTENSION:
2129 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2130 case LyXRC::RC_PRINTODDPAGEFLAG:
2131 case LyXRC::RC_PRINTPAGERANGEFLAG:
2132 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2133 case LyXRC::RC_PRINTPAPERFLAG:
2134 case LyXRC::RC_PRINTREVERSEFLAG:
2135 case LyXRC::RC_PRINTSPOOL_COMMAND:
2136 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2137 case LyXRC::RC_PRINTTOFILE:
2138 case LyXRC::RC_PRINTTOPRINTER:
2139 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2140 case LyXRC::RC_PRINT_COMMAND:
2141 case LyXRC::RC_RTL_SUPPORT:
2142 case LyXRC::RC_SCREEN_DPI:
2143 case LyXRC::RC_SCREEN_FONT_ROMAN:
2144 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2145 case LyXRC::RC_SCREEN_FONT_SANS:
2146 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2147 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2148 case LyXRC::RC_SCREEN_FONT_SIZES:
2149 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2150 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2151 case LyXRC::RC_GEOMETRY_SESSION:
2152 case LyXRC::RC_SCREEN_ZOOM:
2153 case LyXRC::RC_SERVERPIPE:
2154 case LyXRC::RC_SET_COLOR:
2155 case LyXRC::RC_SHOW_BANNER:
2156 case LyXRC::RC_SPELL_COMMAND:
2157 case LyXRC::RC_TEMPDIRPATH:
2158 case LyXRC::RC_TEMPLATEPATH:
2159 case LyXRC::RC_TEX_ALLOWS_SPACES:
2160 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2161 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2162 os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2164 case LyXRC::RC_UIFILE:
2165 case LyXRC::RC_USER_EMAIL:
2166 case LyXRC::RC_USER_NAME:
2167 case LyXRC::RC_USETEMPDIR:
2168 case LyXRC::RC_USE_ALT_LANG:
2169 case LyXRC::RC_USE_CONVERTER_CACHE:
2170 case LyXRC::RC_USE_ESC_CHARS:
2171 case LyXRC::RC_USE_INP_ENC:
2172 case LyXRC::RC_USE_PERS_DICT:
2173 case LyXRC::RC_USE_TOOLTIP:
2174 case LyXRC::RC_USE_PIXMAP_CACHE:
2175 case LyXRC::RC_USE_SPELL_LIB:
2176 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2177 case LyXRC::RC_SORT_LAYOUTS:
2178 case LyXRC::RC_VIEWER:
2179 case LyXRC::RC_LAST: