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 = theLyXFunc().loadAndViewFile(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_INSET_APPLY:
526 case LFUN_BUFFER_WRITE:
527 case LFUN_BUFFER_WRITE_AS:
529 return lyx_view_->getStatus(cmd);
533 case LFUN_BUFFER_TOGGLE_READ_ONLY:
534 flag.setOnOff(buf->isReadonly());
537 case LFUN_BUFFER_SWITCH:
538 // toggle on the current buffer, but do not toggle off
539 // the other ones (is that a good idea?)
540 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
544 case LFUN_BUFFER_EXPORT:
545 enable = cmd.argument() == "custom"
546 || buf->isExportable(to_utf8(cmd.argument()));
549 case LFUN_BUFFER_CHKTEX:
550 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
553 case LFUN_BUILD_PROGRAM:
554 enable = buf->isExportable("program");
557 case LFUN_VC_REGISTER:
558 enable = !buf->lyxvc().inUse();
560 case LFUN_VC_CHECK_IN:
561 enable = buf->lyxvc().inUse() && !buf->isReadonly();
563 case LFUN_VC_CHECK_OUT:
564 enable = buf->lyxvc().inUse() && buf->isReadonly();
567 case LFUN_VC_UNDO_LAST:
568 enable = buf->lyxvc().inUse();
570 case LFUN_BUFFER_RELOAD:
571 enable = !buf->isUnnamed() && buf->fileName().exists()
572 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
575 case LFUN_CITATION_INSERT: {
576 FuncRequest fr(LFUN_INSET_INSERT, "citation");
577 enable = getStatus(fr).enabled();
581 // This could be used for the no-GUI version. The GUI version is handled in
582 // LyXView::getStatus(). See above.
584 case LFUN_BUFFER_WRITE:
585 case LFUN_BUFFER_WRITE_AS: {
586 Buffer * b = theBufferList().getBuffer(cmd.getArg(0));
587 enable = b && (b->isUnnamed() || !b->isClean());
592 case LFUN_BUFFER_WRITE_ALL: {
593 // We enable the command only if there are some modified buffers
594 Buffer * first = theBufferList().first();
599 // We cannot use a for loop as the buffer list is a cycle.
605 b = theBufferList().next(b);
606 } while (b != first);
610 case LFUN_BOOKMARK_GOTO: {
611 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
612 enable = LyX::ref().session().bookmarks().isValid(num);
616 case LFUN_BOOKMARK_CLEAR:
617 enable = LyX::ref().session().bookmarks().size() > 0;
620 // this one is difficult to get right. As a half-baked
621 // solution, we consider only the first action of the sequence
622 case LFUN_COMMAND_SEQUENCE: {
623 // argument contains ';'-terminated commands
624 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
625 FuncRequest func(lyxaction.lookupFunc(firstcmd));
626 func.origin = cmd.origin;
627 flag = getStatus(func);
633 string name = to_utf8(cmd.argument());
634 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
635 func.origin = cmd.origin;
636 flag = getStatus(func);
637 LyX::ref().topLevelCmdDef().release(name);
639 // catch recursion or unknown command definiton
640 // all operations until the recursion or unknown command
641 // definiton occures are performed, so set the state to enabled
647 case LFUN_BUFFER_NEW:
648 case LFUN_BUFFER_NEW_TEMPLATE:
649 case LFUN_WORD_FIND_FORWARD:
650 case LFUN_WORD_FIND_BACKWARD:
651 case LFUN_COMMAND_PREFIX:
652 case LFUN_COMMAND_EXECUTE:
654 case LFUN_META_PREFIX:
655 case LFUN_BUFFER_CLOSE:
656 case LFUN_BUFFER_UPDATE:
657 case LFUN_BUFFER_VIEW:
658 case LFUN_MASTER_BUFFER_UPDATE:
659 case LFUN_MASTER_BUFFER_VIEW:
660 case LFUN_BUFFER_IMPORT:
661 case LFUN_BUFFER_AUTO_SAVE:
662 case LFUN_RECONFIGURE:
666 case LFUN_DROP_LAYOUTS_CHOICE:
668 case LFUN_SERVER_GET_NAME:
669 case LFUN_SERVER_NOTIFY:
670 case LFUN_SERVER_GOTO_FILE_ROW:
671 case LFUN_DIALOG_HIDE:
672 case LFUN_DIALOG_DISCONNECT_INSET:
673 case LFUN_BUFFER_CHILD_OPEN:
674 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
675 case LFUN_KEYMAP_OFF:
676 case LFUN_KEYMAP_PRIMARY:
677 case LFUN_KEYMAP_SECONDARY:
678 case LFUN_KEYMAP_TOGGLE:
680 case LFUN_BUFFER_EXPORT_CUSTOM:
681 case LFUN_BUFFER_PRINT:
682 case LFUN_PREFERENCES_SAVE:
683 case LFUN_SCREEN_FONT_UPDATE:
686 case LFUN_EXTERNAL_EDIT:
687 case LFUN_GRAPHICS_EDIT:
688 case LFUN_ALL_INSETS_TOGGLE:
689 case LFUN_BUFFER_LANGUAGE:
690 case LFUN_TEXTCLASS_APPLY:
691 case LFUN_TEXTCLASS_LOAD:
692 case LFUN_BUFFER_SAVE_AS_DEFAULT:
693 case LFUN_BUFFER_PARAMS_APPLY:
694 case LFUN_LAYOUT_MODULES_CLEAR:
695 case LFUN_LAYOUT_MODULE_ADD:
696 case LFUN_LAYOUT_RELOAD:
697 case LFUN_LYXRC_APPLY:
698 case LFUN_BUFFER_NEXT:
699 case LFUN_BUFFER_PREVIOUS:
700 case LFUN_WINDOW_NEW:
702 // these are handled in our dispatch()
710 if (!getLocalStatus(view()->cursor(), cmd, flag))
711 flag = view()->getStatus(cmd);
717 // Can we use a readonly buffer?
718 if (buf && buf->isReadonly()
719 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
720 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
721 flag.message(from_utf8(N_("Document is read-only")));
725 // Are we in a DELETED change-tracking region?
727 && lookupChangeType(view()->cursor(), true) == Change::DELETED
728 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
729 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
730 flag.message(from_utf8(N_("This portion of the document is deleted.")));
734 // the default error message if we disable the command
735 if (!flag.enabled() && flag.message().empty())
736 flag.message(from_utf8(N_("Command disabled")));
742 bool LyXFunc::ensureBufferClean(BufferView * bv)
744 Buffer & buf = bv->buffer();
748 docstring const file = buf.fileName().displayName(30);
749 docstring text = bformat(_("The document %1$s has unsaved "
750 "changes.\n\nDo you want to save "
751 "the document?"), file);
752 int const ret = Alert::prompt(_("Save changed document?"),
753 text, 0, 1, _("&Save"),
757 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
759 return buf.isClean();
765 void showPrintError(string const & name)
767 docstring str = bformat(_("Could not print the document %1$s.\n"
768 "Check that your printer is set up correctly."),
769 makeDisplayPath(name, 50));
770 Alert::error(_("Print document failed"), str);
774 void loadTextClass(string const & name)
776 pair<bool, textclass_type> const tc_pair =
777 textclasslist.numberOfClass(name);
779 if (!tc_pair.first) {
780 lyxerr << "Document class \"" << name
781 << "\" does not exist."
786 textclass_type const tc = tc_pair.second;
788 if (!textclasslist[tc].load()) {
789 docstring s = bformat(_("The document class %1$s."
790 "could not be loaded."),
791 from_utf8(textclasslist[tc].name()));
792 Alert::error(_("Could not load class"), s);
797 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
802 void LyXFunc::dispatch(FuncRequest const & cmd)
804 string const argument = to_utf8(cmd.argument());
805 kb_action const action = cmd.action;
807 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
808 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
810 // we have not done anything wrong yet.
812 dispatch_buffer.erase();
814 // redraw the screen at the end (first of the two drawing steps).
815 //This is done unless explicitely requested otherwise
816 Update::flags updateFlags = Update::FitCursor;
818 FuncStatus const flag = getStatus(cmd);
819 if (!flag.enabled()) {
820 // We cannot use this function here
821 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
822 << lyxaction.getActionName(action)
823 << " [" << action << "] is disabled at this location");
824 setErrorMessage(flag.message());
828 case LFUN_WORD_FIND_FORWARD:
829 case LFUN_WORD_FIND_BACKWARD: {
830 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
831 static docstring last_search;
832 docstring searched_string;
834 if (!cmd.argument().empty()) {
835 last_search = cmd.argument();
836 searched_string = cmd.argument();
838 searched_string = last_search;
841 if (searched_string.empty())
844 bool const fw = action == LFUN_WORD_FIND_FORWARD;
845 docstring const data =
846 find2string(searched_string, true, false, fw);
847 find(view(), FuncRequest(LFUN_WORD_FIND, data));
851 case LFUN_COMMAND_PREFIX:
852 BOOST_ASSERT(lyx_view_);
853 lyx_view_->message(keyseq.printOptions(true));
857 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
859 meta_fake_bit = NoModifier;
860 if (lyx_view_->buffer())
861 // cancel any selection
862 dispatch(FuncRequest(LFUN_MARK_OFF));
863 setMessage(from_ascii(N_("Cancel")));
866 case LFUN_META_PREFIX:
867 meta_fake_bit = AltModifier;
868 setMessage(keyseq.print(KeySequence::ForGui));
871 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
872 BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
873 Buffer * buf = lyx_view_->buffer();
874 if (buf->lyxvc().inUse())
875 buf->lyxvc().toggleReadOnly();
877 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
881 // --- Menus -----------------------------------------------
882 case LFUN_BUFFER_NEW:
883 lyx_view_->newDocument(argument, false);
884 updateFlags = Update::None;
887 case LFUN_BUFFER_NEW_TEMPLATE:
888 lyx_view_->newDocument(argument, true);
889 updateFlags = Update::None;
892 case LFUN_BUFFER_CLOSE:
894 updateFlags = Update::None;
897 case LFUN_BUFFER_RELOAD: {
898 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
899 docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
900 docstring text = bformat(_("Any changes will be lost. Are you sure "
901 "you want to revert to the saved version of the document %1$s?"), file);
902 int const ret = Alert::prompt(_("Revert to saved document?"),
903 text, 1, 1, _("&Revert"), _("&Cancel"));
910 case LFUN_BUFFER_UPDATE:
911 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
912 lyx_view_->buffer()->doExport(argument, true);
915 case LFUN_BUFFER_VIEW:
916 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
917 lyx_view_->buffer()->preview(argument);
920 case LFUN_MASTER_BUFFER_UPDATE:
921 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
922 lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
925 case LFUN_MASTER_BUFFER_VIEW:
926 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
927 lyx_view_->buffer()->masterBuffer()->preview(argument);
930 case LFUN_BUILD_PROGRAM:
931 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
932 lyx_view_->buffer()->doExport("program", true);
935 case LFUN_BUFFER_CHKTEX:
936 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
937 lyx_view_->buffer()->runChktex();
940 case LFUN_BUFFER_EXPORT:
941 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
942 if (argument == "custom")
943 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
945 lyx_view_->buffer()->doExport(argument, false);
948 case LFUN_BUFFER_EXPORT_CUSTOM: {
949 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
951 string command = split(argument, format_name, ' ');
952 Format const * format = formats.getFormat(format_name);
954 lyxerr << "Format \"" << format_name
955 << "\" not recognized!"
960 Buffer * buffer = lyx_view_->buffer();
962 // The name of the file created by the conversion process
965 // Output to filename
966 if (format->name() == "lyx") {
967 string const latexname = buffer->latexName(false);
968 filename = changeExtension(latexname,
969 format->extension());
970 filename = addName(buffer->temppath(), filename);
972 if (!buffer->writeFile(FileName(filename)))
976 buffer->doExport(format_name, true, filename);
979 // Substitute $$FName for filename
980 if (!contains(command, "$$FName"))
981 command = "( " + command + " ) < $$FName";
982 command = subst(command, "$$FName", filename);
984 // Execute the command in the background
986 call.startscript(Systemcall::DontWait, command);
990 case LFUN_BUFFER_PRINT: {
991 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
992 // FIXME: cmd.getArg() might fail if one of the arguments
993 // contains double quotes
994 string target = cmd.getArg(0);
995 string target_name = cmd.getArg(1);
996 string command = cmd.getArg(2);
999 || target_name.empty()
1000 || command.empty()) {
1001 lyxerr << "Unable to parse \""
1002 << argument << '"' << endl;
1005 if (target != "printer" && target != "file") {
1006 lyxerr << "Unrecognized target \""
1007 << target << '"' << endl;
1011 Buffer * buffer = lyx_view_->buffer();
1013 if (!buffer->doExport("dvi", true)) {
1014 showPrintError(buffer->absFileName());
1018 // Push directory path.
1019 string const path = buffer->temppath();
1020 // Prevent the compiler from optimizing away p
1024 // there are three cases here:
1025 // 1. we print to a file
1026 // 2. we print directly to a printer
1027 // 3. we print using a spool command (print to file first)
1030 string const dviname =
1031 changeExtension(buffer->latexName(true), "dvi");
1033 if (target == "printer") {
1034 if (!lyxrc.print_spool_command.empty()) {
1035 // case 3: print using a spool
1036 string const psname =
1037 changeExtension(dviname,".ps");
1038 command += ' ' + lyxrc.print_to_file
1041 + quoteName(dviname);
1044 lyxrc.print_spool_command + ' ';
1045 if (target_name != "default") {
1046 command2 += lyxrc.print_spool_printerprefix
1050 command2 += quoteName(psname);
1052 // If successful, then spool command
1053 res = one.startscript(
1058 res = one.startscript(
1059 Systemcall::DontWait,
1062 // case 2: print directly to a printer
1063 if (target_name != "default")
1064 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1065 res = one.startscript(
1066 Systemcall::DontWait,
1067 command + quoteName(dviname));
1071 // case 1: print to a file
1072 FileName const filename(makeAbsPath(target_name,
1073 lyx_view_->buffer()->filePath()));
1074 FileName const dvifile(makeAbsPath(dviname, path));
1075 if (filename.exists()) {
1076 docstring text = bformat(
1077 _("The file %1$s already exists.\n\n"
1078 "Do you want to overwrite that file?"),
1079 makeDisplayPath(filename.absFilename()));
1080 if (Alert::prompt(_("Overwrite file?"),
1081 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1084 command += ' ' + lyxrc.print_to_file
1085 + quoteName(filename.toFilesystemEncoding())
1087 + quoteName(dvifile.toFilesystemEncoding());
1088 res = one.startscript(Systemcall::DontWait,
1093 showPrintError(buffer->absFileName());
1097 case LFUN_BUFFER_IMPORT:
1101 case LFUN_BUFFER_AUTO_SAVE:
1102 lyx_view_->buffer()->autoSave();
1105 case LFUN_RECONFIGURE:
1106 BOOST_ASSERT(lyx_view_);
1107 // argument is any additional parameter to the configure.py command
1108 reconfigure(*lyx_view_, argument);
1111 case LFUN_HELP_OPEN: {
1112 BOOST_ASSERT(lyx_view_);
1113 string const arg = argument;
1115 setErrorMessage(from_ascii(N_("Missing argument")));
1118 FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1119 if (fname.empty()) {
1120 lyxerr << "LyX: unable to find documentation file `"
1121 << arg << "'. Bad installation?" << endl;
1124 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1125 makeDisplayPath(fname.absFilename())));
1126 Buffer * buf = loadAndViewFile(fname, false);
1129 lyx_view_->setBuffer(buf);
1130 buf->errors("Parse");
1132 updateFlags = Update::None;
1136 // --- version control -------------------------------
1137 case LFUN_VC_REGISTER:
1138 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1139 if (!ensureBufferClean(view()))
1141 if (!lyx_view_->buffer()->lyxvc().inUse()) {
1142 lyx_view_->buffer()->lyxvc().registrer();
1145 updateFlags = Update::Force;
1148 case LFUN_VC_CHECK_IN:
1149 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1150 if (!ensureBufferClean(view()))
1152 if (lyx_view_->buffer()->lyxvc().inUse()
1153 && !lyx_view_->buffer()->isReadonly()) {
1154 lyx_view_->buffer()->lyxvc().checkIn();
1159 case LFUN_VC_CHECK_OUT:
1160 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1161 if (!ensureBufferClean(view()))
1163 if (lyx_view_->buffer()->lyxvc().inUse()
1164 && lyx_view_->buffer()->isReadonly()) {
1165 lyx_view_->buffer()->lyxvc().checkOut();
1170 case LFUN_VC_REVERT:
1171 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1172 lyx_view_->buffer()->lyxvc().revert();
1176 case LFUN_VC_UNDO_LAST:
1177 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1178 lyx_view_->buffer()->lyxvc().undoLast();
1182 // --- buffers ----------------------------------------
1184 case LFUN_FILE_NEW: {
1185 BOOST_ASSERT(lyx_view_);
1187 string tmpname = split(argument, name, ':'); // Split filename
1188 Buffer * const b = newFile(name, tmpname);
1190 lyx_view_->setBuffer(b);
1191 updateFlags = Update::None;
1195 case LFUN_FILE_OPEN:
1196 BOOST_ASSERT(lyx_view_);
1198 updateFlags = Update::None;
1201 // --- lyxserver commands ----------------------------
1202 case LFUN_SERVER_GET_NAME:
1203 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1204 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1205 LYXERR(Debug::INFO, "FNAME["
1206 << lyx_view_->buffer()->absFileName() << ']');
1209 case LFUN_SERVER_NOTIFY:
1210 dispatch_buffer = keyseq.print(KeySequence::Portable);
1211 theServer().notifyClient(to_utf8(dispatch_buffer));
1214 case LFUN_SERVER_GOTO_FILE_ROW: {
1215 BOOST_ASSERT(lyx_view_);
1218 istringstream is(argument);
1219 is >> file_name >> row;
1221 bool loaded = false;
1222 if (prefixIs(file_name, package().temp_dir().absFilename()))
1223 // Needed by inverse dvi search. If it is a file
1224 // in tmpdir, call the apropriated function
1225 buf = theBufferList().getBufferFromTmp(file_name);
1227 // Must replace extension of the file to be .lyx
1228 // and get full path
1229 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1230 // Either change buffer or load the file
1231 if (theBufferList().exists(s.absFilename()))
1232 buf = theBufferList().getBuffer(s.absFilename());
1234 buf = loadAndViewFile(s);
1240 updateFlags = Update::None;
1245 lyx_view_->setBuffer(buf);
1246 view()->setCursorFromRow(row);
1248 buf->errors("Parse");
1249 updateFlags = Update::FitCursor;
1254 case LFUN_DIALOG_SHOW_NEW_INSET: {
1255 BOOST_ASSERT(lyx_view_);
1256 string const name = cmd.getArg(0);
1257 InsetCode code = insetCode(name);
1258 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1259 bool insetCodeOK = true;
1268 case HYPERLINK_CODE: {
1269 InsetCommandParams p(code);
1270 data = InsetCommandMailer::params2string(name, p);
1273 case INCLUDE_CODE: {
1274 // data is the include type: one of "include",
1275 // "input", "verbatiminput" or "verbatiminput*"
1277 // default type is requested
1279 InsetCommandParams p(INCLUDE_CODE, data);
1280 data = InsetCommandMailer::params2string("include", p);
1284 // \c data == "Boxed" || "Frameless" etc
1285 InsetBoxParams p(data);
1286 data = InsetBoxMailer::params2string(p);
1290 InsetBranchParams p;
1291 data = InsetBranchMailer::params2string(p);
1295 InsetCommandParams p(CITE_CODE);
1296 data = InsetCommandMailer::params2string(name, p);
1300 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1303 case EXTERNAL_CODE: {
1304 InsetExternalParams p;
1305 Buffer const & buffer = *lyx_view_->buffer();
1306 data = InsetExternalMailer::params2string(p, buffer);
1311 data = InsetFloatMailer::params2string(p);
1314 case LISTINGS_CODE: {
1315 InsetListingsParams p;
1316 data = InsetListingsMailer::params2string(p);
1319 case GRAPHICS_CODE: {
1320 InsetGraphicsParams p;
1321 Buffer const & buffer = *lyx_view_->buffer();
1322 data = InsetGraphicsMailer::params2string(p, buffer);
1327 data = InsetNoteMailer::params2string(p);
1332 data = InsetVSpaceMailer::params2string(space);
1337 data = InsetWrapMailer::params2string(p);
1341 lyxerr << "Inset type '" << name <<
1342 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1343 insetCodeOK = false;
1345 } // end switch(code)
1347 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1351 case LFUN_CITATION_INSERT: {
1352 BOOST_ASSERT(lyx_view_);
1353 if (!argument.empty()) {
1354 // we can have one optional argument, delimited by '|'
1355 // citation-insert <key>|<text_before>
1356 // this should be enhanced to also support text_after
1357 // and citation style
1358 string arg = argument;
1360 if (contains(argument, "|")) {
1361 arg = token(argument, '|', 0);
1362 opt1 = token(argument, '|', 1);
1364 InsetCommandParams icp(CITE_CODE);
1365 icp["key"] = from_utf8(arg);
1367 icp["before"] = from_utf8(opt1);
1368 string icstr = InsetCommandMailer::params2string("citation", icp);
1369 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1372 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1376 case LFUN_BUFFER_CHILD_OPEN: {
1377 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1378 Buffer * parent = lyx_view_->buffer();
1379 FileName filename = makeAbsPath(argument, parent->filePath());
1380 view()->saveBookmark(false);
1382 bool parsed = false;
1383 if (theBufferList().exists(filename.absFilename())) {
1384 child = theBufferList().getBuffer(filename.absFilename());
1386 setMessage(bformat(_("Opening child document %1$s..."),
1387 makeDisplayPath(filename.absFilename())));
1388 child = loadAndViewFile(filename, true);
1392 // Set the parent name of the child document.
1393 // This makes insertion of citations and references in the child work,
1394 // when the target is in the parent or another child document.
1395 child->setParent(parent);
1396 updateLabels(*child->masterBuffer());
1397 lyx_view_->setBuffer(child);
1399 child->errors("Parse");
1402 // If a screen update is required (in case where auto_open is false),
1403 // setBuffer() would have taken care of it already. Otherwise we shall
1404 // reset the update flag because it can cause a circular problem.
1406 updateFlags = Update::None;
1410 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1411 BOOST_ASSERT(lyx_view_);
1412 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1415 case LFUN_KEYMAP_OFF:
1416 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1417 lyx_view_->view()->getIntl().keyMapOn(false);
1420 case LFUN_KEYMAP_PRIMARY:
1421 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1422 lyx_view_->view()->getIntl().keyMapPrim();
1425 case LFUN_KEYMAP_SECONDARY:
1426 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1427 lyx_view_->view()->getIntl().keyMapSec();
1430 case LFUN_KEYMAP_TOGGLE:
1431 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1432 lyx_view_->view()->getIntl().toggleKeyMap();
1438 string rest = split(argument, countstr, ' ');
1439 istringstream is(countstr);
1442 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1443 for (int i = 0; i < count; ++i)
1444 dispatch(lyxaction.lookupFunc(rest));
1448 case LFUN_COMMAND_SEQUENCE: {
1449 // argument contains ';'-terminated commands
1450 string arg = argument;
1451 while (!arg.empty()) {
1453 arg = split(arg, first, ';');
1454 FuncRequest func(lyxaction.lookupFunc(first));
1455 func.origin = cmd.origin;
1463 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1464 func.origin = cmd.origin;
1466 LyX::ref().topLevelCmdDef().release(argument);
1468 if (func.action == LFUN_UNKNOWN_ACTION) {
1469 // unknown command definition
1470 lyxerr << "Warning: unknown command definition `"
1474 // recursion detected
1475 lyxerr << "Warning: Recursion in the command definition `"
1476 << argument << "' detected"
1483 case LFUN_PREFERENCES_SAVE: {
1484 lyxrc.write(makeAbsPath("preferences",
1485 package().user_support().absFilename()),
1490 case LFUN_SET_COLOR: {
1492 string const x11_name = split(argument, lyx_name, ' ');
1493 if (lyx_name.empty() || x11_name.empty()) {
1494 setErrorMessage(from_ascii(N_(
1495 "Syntax: set-color <lyx_name>"
1500 bool const graphicsbg_changed =
1501 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1502 x11_name != lcolor.getX11Name(Color_graphicsbg));
1504 if (!lcolor.setColor(lyx_name, x11_name)) {
1506 bformat(_("Set-color \"%1$s\" failed "
1507 "- color is undefined or "
1508 "may not be redefined"),
1509 from_utf8(lyx_name)));
1513 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1515 if (graphicsbg_changed) {
1516 // FIXME: The graphics cache no longer has a changeDisplay method.
1518 graphics::GCache::get().changeDisplay(true);
1525 BOOST_ASSERT(lyx_view_);
1526 lyx_view_->message(from_utf8(argument));
1529 case LFUN_EXTERNAL_EDIT: {
1530 BOOST_ASSERT(lyx_view_);
1531 FuncRequest fr(action, argument);
1532 InsetExternal().dispatch(view()->cursor(), fr);
1536 case LFUN_GRAPHICS_EDIT: {
1537 FuncRequest fr(action, argument);
1538 InsetGraphics().dispatch(view()->cursor(), fr);
1542 case LFUN_ALL_INSETS_TOGGLE: {
1543 BOOST_ASSERT(lyx_view_);
1545 string const name = split(argument, action, ' ');
1546 InsetCode const inset_code = insetCode(name);
1548 Cursor & cur = view()->cursor();
1549 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1551 Inset & inset = lyx_view_->buffer()->inset();
1552 InsetIterator it = inset_iterator_begin(inset);
1553 InsetIterator const end = inset_iterator_end(inset);
1554 for (; it != end; ++it) {
1555 if (!it->asInsetMath()
1556 && (inset_code == NO_CODE
1557 || inset_code == it->lyxCode())) {
1558 Cursor tmpcur = cur;
1559 tmpcur.pushBackward(*it);
1560 it->dispatch(tmpcur, fr);
1563 updateFlags = Update::Force | Update::FitCursor;
1567 case LFUN_BUFFER_LANGUAGE: {
1568 BOOST_ASSERT(lyx_view_);
1569 Buffer & buffer = *lyx_view_->buffer();
1570 Language const * oldL = buffer.params().language;
1571 Language const * newL = languages.getLanguage(argument);
1572 if (!newL || oldL == newL)
1575 if (oldL->rightToLeft() == newL->rightToLeft()
1576 && !buffer.isMultiLingual())
1577 buffer.changeLanguage(oldL, newL);
1581 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1582 string const fname =
1583 addName(addPath(package().user_support().absFilename(), "templates/"),
1585 Buffer defaults(fname);
1587 istringstream ss(argument);
1590 int const unknown_tokens = defaults.readHeader(lex);
1592 if (unknown_tokens != 0) {
1593 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1594 << unknown_tokens << " unknown token"
1595 << (unknown_tokens == 1 ? "" : "s")
1599 if (defaults.writeFile(FileName(defaults.absFileName())))
1600 setMessage(bformat(_("Document defaults saved in %1$s"),
1601 makeDisplayPath(fname)));
1603 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1607 case LFUN_BUFFER_PARAMS_APPLY: {
1608 BOOST_ASSERT(lyx_view_);
1609 biblio::CiteEngine const oldEngine =
1610 lyx_view_->buffer()->params().getEngine();
1612 Buffer * buffer = lyx_view_->buffer();
1614 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1616 Cursor & cur = view()->cursor();
1617 cur.recordUndoFullDocument();
1619 istringstream ss(argument);
1622 int const unknown_tokens = buffer->readHeader(lex);
1624 if (unknown_tokens != 0) {
1625 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1626 << unknown_tokens << " unknown token"
1627 << (unknown_tokens == 1 ? "" : "s")
1631 updateLayout(oldClass, buffer);
1633 biblio::CiteEngine const newEngine =
1634 lyx_view_->buffer()->params().getEngine();
1636 if (oldEngine != newEngine) {
1637 FuncRequest fr(LFUN_INSET_REFRESH);
1639 Inset & inset = lyx_view_->buffer()->inset();
1640 InsetIterator it = inset_iterator_begin(inset);
1641 InsetIterator const end = inset_iterator_end(inset);
1642 for (; it != end; ++it)
1643 if (it->lyxCode() == CITE_CODE)
1644 it->dispatch(cur, fr);
1647 updateFlags = Update::Force | Update::FitCursor;
1648 // We are here most certainaly because of a change in the document
1649 // It is then better to make sure that all dialogs are in sync
1650 // with current document settings. LyXView::restartCursor() achieve this.
1651 lyx_view_->restartCursor();
1655 case LFUN_LAYOUT_MODULES_CLEAR: {
1656 BOOST_ASSERT(lyx_view_);
1657 Buffer * buffer = lyx_view_->buffer();
1658 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1659 view()->cursor().recordUndoFullDocument();
1660 buffer->params().clearLayoutModules();
1661 buffer->params().makeTextClass();
1662 updateLayout(oldClass, buffer);
1663 updateFlags = Update::Force | Update::FitCursor;
1667 case LFUN_LAYOUT_MODULE_ADD: {
1668 BOOST_ASSERT(lyx_view_);
1669 Buffer * buffer = lyx_view_->buffer();
1670 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1671 view()->cursor().recordUndoFullDocument();
1672 buffer->params().addLayoutModule(argument);
1673 buffer->params().makeTextClass();
1674 updateLayout(oldClass, buffer);
1675 updateFlags = Update::Force | Update::FitCursor;
1679 case LFUN_TEXTCLASS_APPLY: {
1680 BOOST_ASSERT(lyx_view_);
1681 Buffer * buffer = lyx_view_->buffer();
1683 loadTextClass(argument);
1685 pair<bool, textclass_type> const tc_pair =
1686 textclasslist.numberOfClass(argument);
1691 textclass_type const old_class = buffer->params().getBaseClass();
1692 textclass_type const new_class = tc_pair.second;
1694 if (old_class == new_class)
1698 //Save the old, possibly modular, layout for use in conversion.
1699 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1700 view()->cursor().recordUndoFullDocument();
1701 buffer->params().setBaseClass(new_class);
1702 buffer->params().makeTextClass();
1703 updateLayout(oldClass, buffer);
1704 updateFlags = Update::Force | Update::FitCursor;
1708 case LFUN_LAYOUT_RELOAD: {
1709 BOOST_ASSERT(lyx_view_);
1710 Buffer * buffer = lyx_view_->buffer();
1711 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1712 textclass_type const tc = buffer->params().getBaseClass();
1713 textclasslist.reset(tc);
1714 buffer->params().setBaseClass(tc);
1715 buffer->params().makeTextClass();
1716 updateLayout(oldClass, buffer);
1717 updateFlags = Update::Force | Update::FitCursor;
1721 case LFUN_TEXTCLASS_LOAD:
1722 loadTextClass(argument);
1725 case LFUN_LYXRC_APPLY: {
1726 LyXRC const lyxrc_orig = lyxrc;
1728 istringstream ss(argument);
1729 bool const success = lyxrc.read(ss) == 0;
1732 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1733 << "Unable to read lyxrc data"
1738 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1740 theApp()->resetGui();
1742 /// We force the redraw in any case because there might be
1743 /// some screen font changes.
1744 /// FIXME: only the current view will be updated. the Gui
1745 /// class is able to furnish the list of views.
1746 updateFlags = Update::Force;
1750 case LFUN_BOOKMARK_GOTO:
1751 // go to bookmark, open unopened file and switch to buffer if necessary
1752 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1753 updateFlags = Update::FitCursor;
1756 case LFUN_BOOKMARK_CLEAR:
1757 LyX::ref().session().bookmarks().clear();
1761 BOOST_ASSERT(theApp());
1762 // Let the frontend dispatch its own actions.
1763 if (theApp()->dispatch(cmd))
1764 // Nothing more to do.
1767 // Let the current LyXView dispatch its own actions.
1768 BOOST_ASSERT(lyx_view_);
1769 if (lyx_view_->dispatch(cmd)) {
1770 if (lyx_view_->view())
1771 updateFlags = lyx_view_->view()->cursor().result().update();
1775 BOOST_ASSERT(lyx_view_->view());
1776 // Let the current BufferView dispatch its own actions.
1777 if (view()->dispatch(cmd)) {
1778 // The BufferView took care of its own updates if needed.
1779 updateFlags = Update::None;
1783 // Let the current Cursor dispatch its own actions.
1784 view()->cursor().getPos(cursorPosBeforeDispatchX_,
1785 cursorPosBeforeDispatchY_);
1786 view()->cursor().dispatch(cmd);
1787 updateFlags = view()->cursor().result().update();
1788 if (!view()->cursor().result().dispatched()) {
1789 // No update needed in this case (e.g. when reaching
1791 updateFlags = Update::None;
1795 if (lyx_view_ && lyx_view_->buffer()) {
1796 // BufferView::update() updates the ViewMetricsInfo and
1797 // also initializes the position cache for all insets in
1798 // (at least partially) visible top-level paragraphs.
1799 // We will redraw the screen only if needed.
1800 view()->processUpdateFlags(updateFlags);
1802 // if we executed a mutating lfun, mark the buffer as dirty
1804 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1805 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1806 lyx_view_->buffer()->markDirty();
1808 //Do we have a selection?
1809 theSelection().haveSelection(view()->cursor().selection());
1812 if (!quitting && lyx_view_) {
1813 // Some messages may already be translated, so we cannot use _()
1814 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1819 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1821 const bool verbose = (cmd.origin == FuncRequest::MENU
1822 || cmd.origin == FuncRequest::TOOLBAR
1823 || cmd.origin == FuncRequest::COMMANDBUFFER);
1825 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1826 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1828 lyx_view_->message(msg);
1832 docstring dispatch_msg = msg;
1833 if (!dispatch_msg.empty())
1834 dispatch_msg += ' ';
1836 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1838 bool argsadded = false;
1840 if (!cmd.argument().empty()) {
1841 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1842 comname += ' ' + cmd.argument();
1847 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1849 if (!shortcuts.empty())
1850 comname += ": " + shortcuts;
1851 else if (!argsadded && !cmd.argument().empty())
1852 comname += ' ' + cmd.argument();
1854 if (!comname.empty()) {
1855 comname = rtrim(comname);
1856 dispatch_msg += '(' + rtrim(comname) + ')';
1859 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1860 if (!dispatch_msg.empty())
1861 lyx_view_->message(dispatch_msg);
1865 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1867 lyx_view_->setBusy(true);
1869 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1872 lyx_view_->message(_("Document not loaded."));
1873 lyx_view_->setBusy(false);
1877 lyx_view_->setBuffer(newBuffer);
1879 // scroll to the position when the file was last closed
1880 if (lyxrc.use_lastfilepos) {
1881 LastFilePosSection::FilePos filepos =
1882 LyX::ref().session().lastFilePos().load(filename);
1883 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1887 LyX::ref().session().lastFiles().add(filename);
1889 lyx_view_->setBusy(false);
1894 void LyXFunc::open(string const & fname)
1896 string initpath = lyxrc.document_path;
1898 if (lyx_view_->buffer()) {
1899 string const trypath = lyx_view_->buffer()->filePath();
1900 // If directory is writeable, use this as default.
1901 if (FileName(trypath).isDirWritable())
1907 if (fname.empty()) {
1908 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
1909 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1910 dlg.setButton2(_("Examples|#E#e"),
1911 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1913 FileDialog::Result result =
1914 dlg.open(from_utf8(initpath),
1915 FileFilterList(_("LyX Documents (*.lyx)")),
1918 if (result.first == FileDialog::Later)
1921 filename = to_utf8(result.second);
1923 // check selected filename
1924 if (filename.empty()) {
1925 lyx_view_->message(_("Canceled."));
1931 // get absolute path of file and add ".lyx" to the filename if
1933 FileName const fullname =
1934 fileSearch(string(), filename, "lyx", support::may_not_exist);
1935 if (!fullname.empty())
1936 filename = fullname.absFilename();
1938 // if the file doesn't exist, let the user create one
1939 if (!fullname.exists()) {
1940 // the user specifically chose this name. Believe him.
1941 Buffer * const b = newFile(filename, string(), true);
1943 lyx_view_->setBuffer(b);
1947 docstring const disp_fn = makeDisplayPath(filename);
1948 lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
1951 Buffer * buf = loadAndViewFile(fullname);
1954 lyx_view_->setBuffer(buf);
1955 buf->errors("Parse");
1956 str2 = bformat(_("Document %1$s opened."), disp_fn);
1958 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1960 lyx_view_->message(str2);
1964 void LyXFunc::doImport(string const & argument)
1967 string filename = split(argument, format, ' ');
1969 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
1970 << " file: " << filename);
1972 // need user interaction
1973 if (filename.empty()) {
1974 string initpath = lyxrc.document_path;
1976 if (lyx_view_->buffer()) {
1977 string const trypath = lyx_view_->buffer()->filePath();
1978 // If directory is writeable, use this as default.
1979 if (FileName(trypath).isDirWritable())
1983 docstring const text = bformat(_("Select %1$s file to import"),
1984 formats.prettyName(format));
1986 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
1987 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1988 dlg.setButton2(_("Examples|#E#e"),
1989 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1991 docstring filter = formats.prettyName(format);
1994 filter += from_utf8(formats.extension(format));
1997 FileDialog::Result result =
1998 dlg.open(from_utf8(initpath),
1999 FileFilterList(filter),
2002 if (result.first == FileDialog::Later)
2005 filename = to_utf8(result.second);
2007 // check selected filename
2008 if (filename.empty())
2009 lyx_view_->message(_("Canceled."));
2012 if (filename.empty())
2015 // get absolute path of file
2016 FileName const fullname(makeAbsPath(filename));
2018 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2020 // Check if the document already is open
2021 Buffer * buf = theBufferList().getBuffer(lyxfile.absFilename());
2022 if (use_gui && buf) {
2023 lyx_view_->setBuffer(buf);
2024 if (!lyx_view_->closeBuffer()) {
2025 lyx_view_->message(_("Canceled."));
2030 // if the file exists already, and we didn't do
2031 // -i lyx thefile.lyx, warn
2032 if (lyxfile.exists() && fullname != lyxfile) {
2033 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2035 docstring text = bformat(_("The document %1$s already exists.\n\n"
2036 "Do you want to overwrite that document?"), file);
2037 int const ret = Alert::prompt(_("Overwrite document?"),
2038 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2041 lyx_view_->message(_("Canceled."));
2046 ErrorList errorList;
2047 import(lyx_view_, fullname, format, errorList);
2048 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2052 void LyXFunc::closeBuffer()
2054 // goto bookmark to update bookmark pit.
2055 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2056 gotoBookmark(i+1, false, false);
2058 lyx_view_->closeBuffer();
2062 void LyXFunc::reloadBuffer()
2064 FileName filename = lyx_view_->buffer()->fileName();
2065 // The user has already confirmed that the changes, if any, should
2066 // be discarded. So we just release the Buffer and don't call closeBuffer();
2067 theBufferList().release(lyx_view_->buffer());
2068 Buffer * buf = loadAndViewFile(filename);
2069 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2073 lyx_view_->setBuffer(buf);
2074 buf->errors("Parse");
2075 str = bformat(_("Document %1$s reloaded."), disp_fn);
2077 str = bformat(_("Could not reload document %1$s"), disp_fn);
2079 lyx_view_->message(str);
2082 // Each "lyx_view_" should have it's own message method. lyxview and
2083 // the minibuffer would use the minibuffer, but lyxserver would
2084 // send an ERROR signal to its client. Alejandro 970603
2085 // This function is bit problematic when it comes to NLS, to make the
2086 // lyx servers client be language indepenent we must not translate
2087 // strings sent to this func.
2088 void LyXFunc::setErrorMessage(docstring const & m) const
2090 dispatch_buffer = m;
2095 void LyXFunc::setMessage(docstring const & m) const
2097 dispatch_buffer = m;
2101 docstring const LyXFunc::viewStatusMessage()
2103 // When meta-fake key is pressed, show the key sequence so far + "M-".
2105 return keyseq.print(KeySequence::ForGui) + "M-";
2107 // Else, when a non-complete key sequence is pressed,
2108 // show the available options.
2109 if (keyseq.length() > 0 && !keyseq.deleted())
2110 return keyseq.printOptions(true);
2112 BOOST_ASSERT(lyx_view_);
2113 if (!lyx_view_->buffer())
2114 return _("Welcome to LyX!");
2116 return view()->cursor().currentState();
2120 BufferView * LyXFunc::view() const
2122 BOOST_ASSERT(lyx_view_);
2123 return lyx_view_->view();
2127 bool LyXFunc::wasMetaKey() const
2129 return (meta_fake_bit != NoModifier);
2133 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2136 lyx_view_->message(_("Converting document to new document class..."));
2138 StableDocIterator backcur(view()->cursor());
2139 ErrorList & el = buffer->errorList("Class Switch");
2140 cap::switchBetweenClasses(
2141 oldlayout, buffer->params().getTextClassPtr(),
2142 static_cast<InsetText &>(buffer->inset()), el);
2144 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2146 buffer->errors("Class Switch");
2147 updateLabels(*buffer);
2153 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2155 // Why the switch you might ask. It is a trick to ensure that all
2156 // the elements in the LyXRCTags enum is handled. As you can see
2157 // there are no breaks at all. So it is just a huge fall-through.
2158 // The nice thing is that we will get a warning from the compiler
2159 // if we forget an element.
2160 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2162 case LyXRC::RC_ACCEPT_COMPOUND:
2163 case LyXRC::RC_ALT_LANG:
2164 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2165 case LyXRC::RC_PLAINTEXT_LINELEN:
2166 case LyXRC::RC_AUTOREGIONDELETE:
2167 case LyXRC::RC_AUTORESET_OPTIONS:
2168 case LyXRC::RC_AUTOSAVE:
2169 case LyXRC::RC_AUTO_NUMBER:
2170 case LyXRC::RC_BACKUPDIR_PATH:
2171 case LyXRC::RC_BIBTEX_COMMAND:
2172 case LyXRC::RC_BINDFILE:
2173 case LyXRC::RC_CHECKLASTFILES:
2174 case LyXRC::RC_USELASTFILEPOS:
2175 case LyXRC::RC_LOADSESSION:
2176 case LyXRC::RC_CHKTEX_COMMAND:
2177 case LyXRC::RC_CONVERTER:
2178 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2179 case LyXRC::RC_COPIER:
2180 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2181 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2182 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2183 case LyXRC::RC_DATE_INSERT_FORMAT:
2184 case LyXRC::RC_DEFAULT_LANGUAGE:
2185 case LyXRC::RC_DEFAULT_PAPERSIZE:
2186 case LyXRC::RC_DEFFILE:
2187 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2188 case LyXRC::RC_DISPLAY_GRAPHICS:
2189 case LyXRC::RC_DOCUMENTPATH:
2190 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2191 FileName path(lyxrc_new.document_path);
2192 if (path.exists() && path.isDirectory())
2193 package().document_dir() = FileName(lyxrc.document_path);
2195 case LyXRC::RC_ESC_CHARS:
2196 case LyXRC::RC_EXAMPLEPATH:
2197 case LyXRC::RC_FONT_ENCODING:
2198 case LyXRC::RC_FORMAT:
2199 case LyXRC::RC_INDEX_COMMAND:
2200 case LyXRC::RC_INPUT:
2201 case LyXRC::RC_KBMAP:
2202 case LyXRC::RC_KBMAP_PRIMARY:
2203 case LyXRC::RC_KBMAP_SECONDARY:
2204 case LyXRC::RC_LABEL_INIT_LENGTH:
2205 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2206 case LyXRC::RC_LANGUAGE_AUTO_END:
2207 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2208 case LyXRC::RC_LANGUAGE_COMMAND_END:
2209 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2210 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2211 case LyXRC::RC_LANGUAGE_PACKAGE:
2212 case LyXRC::RC_LANGUAGE_USE_BABEL:
2213 case LyXRC::RC_MACRO_EDIT_STYLE:
2214 case LyXRC::RC_MAKE_BACKUP:
2215 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2216 case LyXRC::RC_MOUSE_WHEEL_SPEED:
2217 case LyXRC::RC_NUMLASTFILES:
2218 case LyXRC::RC_PATH_PREFIX:
2219 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2220 prependEnvPath("PATH", lyxrc.path_prefix);
2222 case LyXRC::RC_PERS_DICT:
2223 case LyXRC::RC_PREVIEW:
2224 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2225 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2226 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2227 case LyXRC::RC_PRINTCOPIESFLAG:
2228 case LyXRC::RC_PRINTER:
2229 case LyXRC::RC_PRINTEVENPAGEFLAG:
2230 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2231 case LyXRC::RC_PRINTFILEEXTENSION:
2232 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2233 case LyXRC::RC_PRINTODDPAGEFLAG:
2234 case LyXRC::RC_PRINTPAGERANGEFLAG:
2235 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2236 case LyXRC::RC_PRINTPAPERFLAG:
2237 case LyXRC::RC_PRINTREVERSEFLAG:
2238 case LyXRC::RC_PRINTSPOOL_COMMAND:
2239 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2240 case LyXRC::RC_PRINTTOFILE:
2241 case LyXRC::RC_PRINTTOPRINTER:
2242 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2243 case LyXRC::RC_PRINT_COMMAND:
2244 case LyXRC::RC_RTL_SUPPORT:
2245 case LyXRC::RC_SCREEN_DPI:
2246 case LyXRC::RC_SCREEN_FONT_ROMAN:
2247 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2248 case LyXRC::RC_SCREEN_FONT_SANS:
2249 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2250 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2251 case LyXRC::RC_SCREEN_FONT_SIZES:
2252 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2253 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2254 case LyXRC::RC_GEOMETRY_SESSION:
2255 case LyXRC::RC_SCREEN_ZOOM:
2256 case LyXRC::RC_SERVERPIPE:
2257 case LyXRC::RC_SET_COLOR:
2258 case LyXRC::RC_SHOW_BANNER:
2259 case LyXRC::RC_SPELL_COMMAND:
2260 case LyXRC::RC_TEMPDIRPATH:
2261 case LyXRC::RC_TEMPLATEPATH:
2262 case LyXRC::RC_TEX_ALLOWS_SPACES:
2263 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2264 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2265 os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2267 case LyXRC::RC_UIFILE:
2268 case LyXRC::RC_USER_EMAIL:
2269 case LyXRC::RC_USER_NAME:
2270 case LyXRC::RC_USETEMPDIR:
2271 case LyXRC::RC_USE_ALT_LANG:
2272 case LyXRC::RC_USE_CONVERTER_CACHE:
2273 case LyXRC::RC_USE_ESC_CHARS:
2274 case LyXRC::RC_USE_INP_ENC:
2275 case LyXRC::RC_USE_PERS_DICT:
2276 case LyXRC::RC_USE_TOOLTIP:
2277 case LyXRC::RC_USE_PIXMAP_CACHE:
2278 case LyXRC::RC_USE_SPELL_LIB:
2279 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2280 case LyXRC::RC_SORT_LAYOUTS:
2281 case LyXRC::RC_VIEWER:
2282 case LyXRC::RC_LAST: