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_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 = loadAndViewFile(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 case LFUN_FILE_OPEN:
1198 BOOST_ASSERT(lyx_view_);
1200 updateFlags = Update::None;
1203 // --- lyxserver commands ----------------------------
1204 case LFUN_SERVER_GET_NAME:
1205 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1206 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1207 LYXERR(Debug::INFO, "FNAME["
1208 << lyx_view_->buffer()->absFileName() << ']');
1211 case LFUN_SERVER_NOTIFY:
1212 dispatch_buffer = keyseq.print(KeySequence::Portable);
1213 theServer().notifyClient(to_utf8(dispatch_buffer));
1216 case LFUN_SERVER_GOTO_FILE_ROW: {
1217 BOOST_ASSERT(lyx_view_);
1220 istringstream is(argument);
1221 is >> file_name >> row;
1223 bool loaded = false;
1224 if (prefixIs(file_name, package().temp_dir().absFilename()))
1225 // Needed by inverse dvi search. If it is a file
1226 // in tmpdir, call the apropriated function
1227 buf = theBufferList().getBufferFromTmp(file_name);
1229 // Must replace extension of the file to be .lyx
1230 // and get full path
1231 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1232 // Either change buffer or load the file
1233 if (theBufferList().exists(s.absFilename()))
1234 buf = theBufferList().getBuffer(s.absFilename());
1236 buf = loadAndViewFile(s);
1242 updateFlags = Update::None;
1247 lyx_view_->setBuffer(buf);
1248 view()->setCursorFromRow(row);
1250 buf->errors("Parse");
1251 updateFlags = Update::FitCursor;
1256 case LFUN_DIALOG_SHOW_NEW_INSET: {
1257 BOOST_ASSERT(lyx_view_);
1258 string const name = cmd.getArg(0);
1259 InsetCode code = insetCode(name);
1260 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1261 bool insetCodeOK = true;
1270 case HYPERLINK_CODE: {
1271 InsetCommandParams p(code);
1272 data = InsetCommandMailer::params2string(name, p);
1275 case INCLUDE_CODE: {
1276 // data is the include type: one of "include",
1277 // "input", "verbatiminput" or "verbatiminput*"
1279 // default type is requested
1281 InsetCommandParams p(INCLUDE_CODE, data);
1282 data = InsetCommandMailer::params2string("include", p);
1286 // \c data == "Boxed" || "Frameless" etc
1287 InsetBoxParams p(data);
1288 data = InsetBoxMailer::params2string(p);
1292 InsetBranchParams p;
1293 data = InsetBranchMailer::params2string(p);
1297 InsetCommandParams p(CITE_CODE);
1298 data = InsetCommandMailer::params2string(name, p);
1302 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1305 case EXTERNAL_CODE: {
1306 InsetExternalParams p;
1307 Buffer const & buffer = *lyx_view_->buffer();
1308 data = InsetExternalMailer::params2string(p, buffer);
1313 data = InsetFloatMailer::params2string(p);
1316 case LISTINGS_CODE: {
1317 InsetListingsParams p;
1318 data = InsetListingsMailer::params2string(p);
1321 case GRAPHICS_CODE: {
1322 InsetGraphicsParams p;
1323 Buffer const & buffer = *lyx_view_->buffer();
1324 data = InsetGraphicsMailer::params2string(p, buffer);
1329 data = InsetNoteMailer::params2string(p);
1334 data = InsetVSpaceMailer::params2string(space);
1339 data = InsetWrapMailer::params2string(p);
1343 lyxerr << "Inset type '" << name <<
1344 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1345 insetCodeOK = false;
1347 } // end switch(code)
1349 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1353 case LFUN_CITATION_INSERT: {
1354 BOOST_ASSERT(lyx_view_);
1355 if (!argument.empty()) {
1356 // we can have one optional argument, delimited by '|'
1357 // citation-insert <key>|<text_before>
1358 // this should be enhanced to also support text_after
1359 // and citation style
1360 string arg = argument;
1362 if (contains(argument, "|")) {
1363 arg = token(argument, '|', 0);
1364 opt1 = token(argument, '|', 1);
1366 InsetCommandParams icp(CITE_CODE);
1367 icp["key"] = from_utf8(arg);
1369 icp["before"] = from_utf8(opt1);
1370 string icstr = InsetCommandMailer::params2string("citation", icp);
1371 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1374 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1378 case LFUN_BUFFER_CHILD_OPEN: {
1379 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1380 Buffer * parent = lyx_view_->buffer();
1381 FileName filename = makeAbsPath(argument, parent->filePath());
1382 view()->saveBookmark(false);
1384 bool parsed = false;
1385 if (theBufferList().exists(filename.absFilename())) {
1386 child = theBufferList().getBuffer(filename.absFilename());
1388 setMessage(bformat(_("Opening child document %1$s..."),
1389 makeDisplayPath(filename.absFilename())));
1390 child = loadAndViewFile(filename, true);
1394 // Set the parent name of the child document.
1395 // This makes insertion of citations and references in the child work,
1396 // when the target is in the parent or another child document.
1397 child->setParent(parent);
1398 updateLabels(*child->masterBuffer());
1399 lyx_view_->setBuffer(child);
1401 child->errors("Parse");
1404 // If a screen update is required (in case where auto_open is false),
1405 // setBuffer() would have taken care of it already. Otherwise we shall
1406 // reset the update flag because it can cause a circular problem.
1408 updateFlags = Update::None;
1412 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1413 BOOST_ASSERT(lyx_view_);
1414 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1417 case LFUN_KEYMAP_OFF:
1418 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1419 lyx_view_->view()->getIntl().keyMapOn(false);
1422 case LFUN_KEYMAP_PRIMARY:
1423 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1424 lyx_view_->view()->getIntl().keyMapPrim();
1427 case LFUN_KEYMAP_SECONDARY:
1428 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1429 lyx_view_->view()->getIntl().keyMapSec();
1432 case LFUN_KEYMAP_TOGGLE:
1433 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1434 lyx_view_->view()->getIntl().toggleKeyMap();
1440 string rest = split(argument, countstr, ' ');
1441 istringstream is(countstr);
1444 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1445 for (int i = 0; i < count; ++i)
1446 dispatch(lyxaction.lookupFunc(rest));
1450 case LFUN_COMMAND_SEQUENCE: {
1451 // argument contains ';'-terminated commands
1452 string arg = argument;
1453 while (!arg.empty()) {
1455 arg = split(arg, first, ';');
1456 FuncRequest func(lyxaction.lookupFunc(first));
1457 func.origin = cmd.origin;
1465 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1466 func.origin = cmd.origin;
1468 LyX::ref().topLevelCmdDef().release(argument);
1470 if (func.action == LFUN_UNKNOWN_ACTION) {
1471 // unknown command definition
1472 lyxerr << "Warning: unknown command definition `"
1476 // recursion detected
1477 lyxerr << "Warning: Recursion in the command definition `"
1478 << argument << "' detected"
1485 case LFUN_PREFERENCES_SAVE: {
1486 lyxrc.write(makeAbsPath("preferences",
1487 package().user_support().absFilename()),
1492 case LFUN_SET_COLOR: {
1494 string const x11_name = split(argument, lyx_name, ' ');
1495 if (lyx_name.empty() || x11_name.empty()) {
1496 setErrorMessage(from_ascii(N_(
1497 "Syntax: set-color <lyx_name>"
1502 bool const graphicsbg_changed =
1503 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1504 x11_name != lcolor.getX11Name(Color_graphicsbg));
1506 if (!lcolor.setColor(lyx_name, x11_name)) {
1508 bformat(_("Set-color \"%1$s\" failed "
1509 "- color is undefined or "
1510 "may not be redefined"),
1511 from_utf8(lyx_name)));
1515 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1517 if (graphicsbg_changed) {
1518 // FIXME: The graphics cache no longer has a changeDisplay method.
1520 graphics::GCache::get().changeDisplay(true);
1527 BOOST_ASSERT(lyx_view_);
1528 lyx_view_->message(from_utf8(argument));
1531 case LFUN_EXTERNAL_EDIT: {
1532 BOOST_ASSERT(lyx_view_);
1533 FuncRequest fr(action, argument);
1534 InsetExternal().dispatch(view()->cursor(), fr);
1538 case LFUN_GRAPHICS_EDIT: {
1539 FuncRequest fr(action, argument);
1540 InsetGraphics().dispatch(view()->cursor(), fr);
1544 case LFUN_ALL_INSETS_TOGGLE: {
1545 BOOST_ASSERT(lyx_view_);
1547 string const name = split(argument, action, ' ');
1548 InsetCode const inset_code = insetCode(name);
1550 Cursor & cur = view()->cursor();
1551 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1553 Inset & inset = lyx_view_->buffer()->inset();
1554 InsetIterator it = inset_iterator_begin(inset);
1555 InsetIterator const end = inset_iterator_end(inset);
1556 for (; it != end; ++it) {
1557 if (!it->asInsetMath()
1558 && (inset_code == NO_CODE
1559 || inset_code == it->lyxCode())) {
1560 Cursor tmpcur = cur;
1561 tmpcur.pushBackward(*it);
1562 it->dispatch(tmpcur, fr);
1565 updateFlags = Update::Force | Update::FitCursor;
1569 case LFUN_BUFFER_LANGUAGE: {
1570 BOOST_ASSERT(lyx_view_);
1571 Buffer & buffer = *lyx_view_->buffer();
1572 Language const * oldL = buffer.params().language;
1573 Language const * newL = languages.getLanguage(argument);
1574 if (!newL || oldL == newL)
1577 if (oldL->rightToLeft() == newL->rightToLeft()
1578 && !buffer.isMultiLingual())
1579 buffer.changeLanguage(oldL, newL);
1583 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1584 string const fname =
1585 addName(addPath(package().user_support().absFilename(), "templates/"),
1587 Buffer defaults(fname);
1589 istringstream ss(argument);
1592 int const unknown_tokens = defaults.readHeader(lex);
1594 if (unknown_tokens != 0) {
1595 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1596 << unknown_tokens << " unknown token"
1597 << (unknown_tokens == 1 ? "" : "s")
1601 if (defaults.writeFile(FileName(defaults.absFileName())))
1602 setMessage(bformat(_("Document defaults saved in %1$s"),
1603 makeDisplayPath(fname)));
1605 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1609 case LFUN_BUFFER_PARAMS_APPLY: {
1610 BOOST_ASSERT(lyx_view_);
1611 biblio::CiteEngine const oldEngine =
1612 lyx_view_->buffer()->params().getEngine();
1614 Buffer * buffer = lyx_view_->buffer();
1616 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1618 Cursor & cur = view()->cursor();
1619 cur.recordUndoFullDocument();
1621 istringstream ss(argument);
1624 int const unknown_tokens = buffer->readHeader(lex);
1626 if (unknown_tokens != 0) {
1627 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1628 << unknown_tokens << " unknown token"
1629 << (unknown_tokens == 1 ? "" : "s")
1633 updateLayout(oldClass, buffer);
1635 biblio::CiteEngine const newEngine =
1636 lyx_view_->buffer()->params().getEngine();
1638 if (oldEngine != newEngine) {
1639 FuncRequest fr(LFUN_INSET_REFRESH);
1641 Inset & inset = lyx_view_->buffer()->inset();
1642 InsetIterator it = inset_iterator_begin(inset);
1643 InsetIterator const end = inset_iterator_end(inset);
1644 for (; it != end; ++it)
1645 if (it->lyxCode() == CITE_CODE)
1646 it->dispatch(cur, fr);
1649 updateFlags = Update::Force | Update::FitCursor;
1650 // We are here most certainaly because of a change in the document
1651 // It is then better to make sure that all dialogs are in sync
1652 // with current document settings. LyXView::restartCursor() achieve this.
1653 lyx_view_->restartCursor();
1657 case LFUN_LAYOUT_MODULES_CLEAR: {
1658 BOOST_ASSERT(lyx_view_);
1659 Buffer * buffer = lyx_view_->buffer();
1660 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1661 view()->cursor().recordUndoFullDocument();
1662 buffer->params().clearLayoutModules();
1663 buffer->params().makeTextClass();
1664 updateLayout(oldClass, buffer);
1665 updateFlags = Update::Force | Update::FitCursor;
1669 case LFUN_LAYOUT_MODULE_ADD: {
1670 BOOST_ASSERT(lyx_view_);
1671 Buffer * buffer = lyx_view_->buffer();
1672 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1673 view()->cursor().recordUndoFullDocument();
1674 buffer->params().addLayoutModule(argument);
1675 buffer->params().makeTextClass();
1676 updateLayout(oldClass, buffer);
1677 updateFlags = Update::Force | Update::FitCursor;
1681 case LFUN_TEXTCLASS_APPLY: {
1682 BOOST_ASSERT(lyx_view_);
1683 Buffer * buffer = lyx_view_->buffer();
1685 loadTextClass(argument);
1687 pair<bool, textclass_type> const tc_pair =
1688 textclasslist.numberOfClass(argument);
1693 textclass_type const old_class = buffer->params().getBaseClass();
1694 textclass_type const new_class = tc_pair.second;
1696 if (old_class == new_class)
1700 //Save the old, possibly modular, layout for use in conversion.
1701 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1702 view()->cursor().recordUndoFullDocument();
1703 buffer->params().setBaseClass(new_class);
1704 buffer->params().makeTextClass();
1705 updateLayout(oldClass, buffer);
1706 updateFlags = Update::Force | Update::FitCursor;
1710 case LFUN_LAYOUT_RELOAD: {
1711 BOOST_ASSERT(lyx_view_);
1712 Buffer * buffer = lyx_view_->buffer();
1713 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1714 textclass_type const tc = buffer->params().getBaseClass();
1715 textclasslist.reset(tc);
1716 buffer->params().setBaseClass(tc);
1717 buffer->params().makeTextClass();
1718 updateLayout(oldClass, buffer);
1719 updateFlags = Update::Force | Update::FitCursor;
1723 case LFUN_TEXTCLASS_LOAD:
1724 loadTextClass(argument);
1727 case LFUN_LYXRC_APPLY: {
1728 LyXRC const lyxrc_orig = lyxrc;
1730 istringstream ss(argument);
1731 bool const success = lyxrc.read(ss) == 0;
1734 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1735 << "Unable to read lyxrc data"
1740 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1742 theApp()->resetGui();
1744 /// We force the redraw in any case because there might be
1745 /// some screen font changes.
1746 /// FIXME: only the current view will be updated. the Gui
1747 /// class is able to furnish the list of views.
1748 updateFlags = Update::Force;
1752 case LFUN_BOOKMARK_GOTO:
1753 // go to bookmark, open unopened file and switch to buffer if necessary
1754 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1755 updateFlags = Update::FitCursor;
1758 case LFUN_BOOKMARK_CLEAR:
1759 LyX::ref().session().bookmarks().clear();
1763 BOOST_ASSERT(theApp());
1764 // Let the frontend dispatch its own actions.
1765 if (theApp()->dispatch(cmd))
1766 // Nothing more to do.
1769 // Let the current LyXView dispatch its own actions.
1770 BOOST_ASSERT(lyx_view_);
1771 if (lyx_view_->dispatch(cmd)) {
1772 if (lyx_view_->view())
1773 updateFlags = lyx_view_->view()->cursor().result().update();
1777 BOOST_ASSERT(lyx_view_->view());
1778 // Let the current BufferView dispatch its own actions.
1779 if (view()->dispatch(cmd)) {
1780 // The BufferView took care of its own updates if needed.
1781 updateFlags = Update::None;
1785 // Let the current Cursor dispatch its own actions.
1786 view()->cursor().getPos(cursorPosBeforeDispatchX_,
1787 cursorPosBeforeDispatchY_);
1788 view()->cursor().dispatch(cmd);
1789 updateFlags = view()->cursor().result().update();
1790 if (!view()->cursor().result().dispatched()) {
1791 // No update needed in this case (e.g. when reaching
1793 updateFlags = Update::None;
1797 if (lyx_view_ && lyx_view_->buffer()) {
1798 // BufferView::update() updates the ViewMetricsInfo and
1799 // also initializes the position cache for all insets in
1800 // (at least partially) visible top-level paragraphs.
1801 // We will redraw the screen only if needed.
1802 view()->processUpdateFlags(updateFlags);
1804 // if we executed a mutating lfun, mark the buffer as dirty
1806 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1807 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1808 lyx_view_->buffer()->markDirty();
1810 //Do we have a selection?
1811 theSelection().haveSelection(view()->cursor().selection());
1814 if (!quitting && lyx_view_) {
1815 // Some messages may already be translated, so we cannot use _()
1816 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1821 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1823 const bool verbose = (cmd.origin == FuncRequest::MENU
1824 || cmd.origin == FuncRequest::TOOLBAR
1825 || cmd.origin == FuncRequest::COMMANDBUFFER);
1827 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1828 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1830 lyx_view_->message(msg);
1834 docstring dispatch_msg = msg;
1835 if (!dispatch_msg.empty())
1836 dispatch_msg += ' ';
1838 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1840 bool argsadded = false;
1842 if (!cmd.argument().empty()) {
1843 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1844 comname += ' ' + cmd.argument();
1849 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1851 if (!shortcuts.empty())
1852 comname += ": " + shortcuts;
1853 else if (!argsadded && !cmd.argument().empty())
1854 comname += ' ' + cmd.argument();
1856 if (!comname.empty()) {
1857 comname = rtrim(comname);
1858 dispatch_msg += '(' + rtrim(comname) + ')';
1861 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1862 if (!dispatch_msg.empty())
1863 lyx_view_->message(dispatch_msg);
1867 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1869 lyx_view_->setBusy(true);
1871 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1874 lyx_view_->message(_("Document not loaded."));
1875 lyx_view_->setBusy(false);
1879 lyx_view_->setBuffer(newBuffer);
1881 // scroll to the position when the file was last closed
1882 if (lyxrc.use_lastfilepos) {
1883 LastFilePosSection::FilePos filepos =
1884 LyX::ref().session().lastFilePos().load(filename);
1885 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1889 LyX::ref().session().lastFiles().add(filename);
1891 lyx_view_->setBusy(false);
1896 void LyXFunc::open(string const & fname)
1898 string initpath = lyxrc.document_path;
1900 if (lyx_view_->buffer()) {
1901 string const trypath = lyx_view_->buffer()->filePath();
1902 // If directory is writeable, use this as default.
1903 if (FileName(trypath).isDirWritable())
1909 if (fname.empty()) {
1910 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
1911 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1912 dlg.setButton2(_("Examples|#E#e"),
1913 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1915 FileDialog::Result result =
1916 dlg.open(from_utf8(initpath),
1917 FileFilterList(_("LyX Documents (*.lyx)")),
1920 if (result.first == FileDialog::Later)
1923 filename = to_utf8(result.second);
1925 // check selected filename
1926 if (filename.empty()) {
1927 lyx_view_->message(_("Canceled."));
1933 // get absolute path of file and add ".lyx" to the filename if
1935 FileName const fullname =
1936 fileSearch(string(), filename, "lyx", support::may_not_exist);
1937 if (!fullname.empty())
1938 filename = fullname.absFilename();
1940 // if the file doesn't exist, let the user create one
1941 if (!fullname.exists()) {
1942 // the user specifically chose this name. Believe him.
1943 Buffer * const b = newFile(filename, string(), true);
1945 lyx_view_->setBuffer(b);
1949 docstring const disp_fn = makeDisplayPath(filename);
1950 lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
1953 Buffer * buf = loadAndViewFile(fullname);
1956 lyx_view_->setBuffer(buf);
1957 buf->errors("Parse");
1958 str2 = bformat(_("Document %1$s opened."), disp_fn);
1960 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1962 lyx_view_->message(str2);
1966 void LyXFunc::doImport(string const & argument)
1969 string filename = split(argument, format, ' ');
1971 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
1972 << " file: " << filename);
1974 // need user interaction
1975 if (filename.empty()) {
1976 string initpath = lyxrc.document_path;
1978 if (lyx_view_->buffer()) {
1979 string const trypath = lyx_view_->buffer()->filePath();
1980 // If directory is writeable, use this as default.
1981 if (FileName(trypath).isDirWritable())
1985 docstring const text = bformat(_("Select %1$s file to import"),
1986 formats.prettyName(format));
1988 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
1989 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1990 dlg.setButton2(_("Examples|#E#e"),
1991 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1993 docstring filter = formats.prettyName(format);
1996 filter += from_utf8(formats.extension(format));
1999 FileDialog::Result result =
2000 dlg.open(from_utf8(initpath),
2001 FileFilterList(filter),
2004 if (result.first == FileDialog::Later)
2007 filename = to_utf8(result.second);
2009 // check selected filename
2010 if (filename.empty())
2011 lyx_view_->message(_("Canceled."));
2014 if (filename.empty())
2017 // get absolute path of file
2018 FileName const fullname(makeAbsPath(filename));
2020 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2022 // Check if the document already is open
2023 Buffer * buf = theBufferList().getBuffer(lyxfile.absFilename());
2024 if (use_gui && buf) {
2025 lyx_view_->setBuffer(buf);
2026 if (!lyx_view_->closeBuffer()) {
2027 lyx_view_->message(_("Canceled."));
2032 // if the file exists already, and we didn't do
2033 // -i lyx thefile.lyx, warn
2034 if (lyxfile.exists() && fullname != lyxfile) {
2035 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2037 docstring text = bformat(_("The document %1$s already exists.\n\n"
2038 "Do you want to overwrite that document?"), file);
2039 int const ret = Alert::prompt(_("Overwrite document?"),
2040 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2043 lyx_view_->message(_("Canceled."));
2048 ErrorList errorList;
2049 import(lyx_view_, fullname, format, errorList);
2050 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2054 void LyXFunc::closeBuffer()
2056 // goto bookmark to update bookmark pit.
2057 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2058 gotoBookmark(i+1, false, false);
2060 lyx_view_->closeBuffer();
2064 void LyXFunc::reloadBuffer()
2066 FileName filename = lyx_view_->buffer()->fileName();
2067 // The user has already confirmed that the changes, if any, should
2068 // be discarded. So we just release the Buffer and don't call closeBuffer();
2069 theBufferList().release(lyx_view_->buffer());
2070 Buffer * buf = loadAndViewFile(filename);
2071 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2075 lyx_view_->setBuffer(buf);
2076 buf->errors("Parse");
2077 str = bformat(_("Document %1$s reloaded."), disp_fn);
2079 str = bformat(_("Could not reload document %1$s"), disp_fn);
2081 lyx_view_->message(str);
2084 // Each "lyx_view_" should have it's own message method. lyxview and
2085 // the minibuffer would use the minibuffer, but lyxserver would
2086 // send an ERROR signal to its client. Alejandro 970603
2087 // This function is bit problematic when it comes to NLS, to make the
2088 // lyx servers client be language indepenent we must not translate
2089 // strings sent to this func.
2090 void LyXFunc::setErrorMessage(docstring const & m) const
2092 dispatch_buffer = m;
2097 void LyXFunc::setMessage(docstring const & m) const
2099 dispatch_buffer = m;
2103 docstring const LyXFunc::viewStatusMessage()
2105 // When meta-fake key is pressed, show the key sequence so far + "M-".
2107 return keyseq.print(KeySequence::ForGui) + "M-";
2109 // Else, when a non-complete key sequence is pressed,
2110 // show the available options.
2111 if (keyseq.length() > 0 && !keyseq.deleted())
2112 return keyseq.printOptions(true);
2114 BOOST_ASSERT(lyx_view_);
2115 if (!lyx_view_->buffer())
2116 return _("Welcome to LyX!");
2118 return view()->cursor().currentState();
2122 BufferView * LyXFunc::view() const
2124 BOOST_ASSERT(lyx_view_);
2125 return lyx_view_->view();
2129 bool LyXFunc::wasMetaKey() const
2131 return (meta_fake_bit != NoModifier);
2135 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2138 lyx_view_->message(_("Converting document to new document class..."));
2140 StableDocIterator backcur(view()->cursor());
2141 ErrorList & el = buffer->errorList("Class Switch");
2142 cap::switchBetweenClasses(
2143 oldlayout, buffer->params().getTextClassPtr(),
2144 static_cast<InsetText &>(buffer->inset()), el);
2146 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2148 buffer->errors("Class Switch");
2149 updateLabels(*buffer);
2155 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2157 // Why the switch you might ask. It is a trick to ensure that all
2158 // the elements in the LyXRCTags enum is handled. As you can see
2159 // there are no breaks at all. So it is just a huge fall-through.
2160 // The nice thing is that we will get a warning from the compiler
2161 // if we forget an element.
2162 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2164 case LyXRC::RC_ACCEPT_COMPOUND:
2165 case LyXRC::RC_ALT_LANG:
2166 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2167 case LyXRC::RC_PLAINTEXT_LINELEN:
2168 case LyXRC::RC_AUTOREGIONDELETE:
2169 case LyXRC::RC_AUTORESET_OPTIONS:
2170 case LyXRC::RC_AUTOSAVE:
2171 case LyXRC::RC_AUTO_NUMBER:
2172 case LyXRC::RC_BACKUPDIR_PATH:
2173 case LyXRC::RC_BIBTEX_COMMAND:
2174 case LyXRC::RC_BINDFILE:
2175 case LyXRC::RC_CHECKLASTFILES:
2176 case LyXRC::RC_USELASTFILEPOS:
2177 case LyXRC::RC_LOADSESSION:
2178 case LyXRC::RC_CHKTEX_COMMAND:
2179 case LyXRC::RC_CONVERTER:
2180 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2181 case LyXRC::RC_COPIER:
2182 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2183 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2184 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2185 case LyXRC::RC_DATE_INSERT_FORMAT:
2186 case LyXRC::RC_DEFAULT_LANGUAGE:
2187 case LyXRC::RC_DEFAULT_PAPERSIZE:
2188 case LyXRC::RC_DEFFILE:
2189 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2190 case LyXRC::RC_DISPLAY_GRAPHICS:
2191 case LyXRC::RC_DOCUMENTPATH:
2192 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2193 FileName path(lyxrc_new.document_path);
2194 if (path.exists() && path.isDirectory())
2195 package().document_dir() = FileName(lyxrc.document_path);
2197 case LyXRC::RC_ESC_CHARS:
2198 case LyXRC::RC_EXAMPLEPATH:
2199 case LyXRC::RC_FONT_ENCODING:
2200 case LyXRC::RC_FORMAT:
2201 case LyXRC::RC_INDEX_COMMAND:
2202 case LyXRC::RC_INPUT:
2203 case LyXRC::RC_KBMAP:
2204 case LyXRC::RC_KBMAP_PRIMARY:
2205 case LyXRC::RC_KBMAP_SECONDARY:
2206 case LyXRC::RC_LABEL_INIT_LENGTH:
2207 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2208 case LyXRC::RC_LANGUAGE_AUTO_END:
2209 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2210 case LyXRC::RC_LANGUAGE_COMMAND_END:
2211 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2212 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2213 case LyXRC::RC_LANGUAGE_PACKAGE:
2214 case LyXRC::RC_LANGUAGE_USE_BABEL:
2215 case LyXRC::RC_MACRO_EDIT_STYLE:
2216 case LyXRC::RC_MAKE_BACKUP:
2217 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2218 case LyXRC::RC_MOUSE_WHEEL_SPEED:
2219 case LyXRC::RC_NUMLASTFILES:
2220 case LyXRC::RC_PATH_PREFIX:
2221 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2222 prependEnvPath("PATH", lyxrc.path_prefix);
2224 case LyXRC::RC_PERS_DICT:
2225 case LyXRC::RC_PREVIEW:
2226 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2227 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2228 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2229 case LyXRC::RC_PRINTCOPIESFLAG:
2230 case LyXRC::RC_PRINTER:
2231 case LyXRC::RC_PRINTEVENPAGEFLAG:
2232 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2233 case LyXRC::RC_PRINTFILEEXTENSION:
2234 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2235 case LyXRC::RC_PRINTODDPAGEFLAG:
2236 case LyXRC::RC_PRINTPAGERANGEFLAG:
2237 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2238 case LyXRC::RC_PRINTPAPERFLAG:
2239 case LyXRC::RC_PRINTREVERSEFLAG:
2240 case LyXRC::RC_PRINTSPOOL_COMMAND:
2241 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2242 case LyXRC::RC_PRINTTOFILE:
2243 case LyXRC::RC_PRINTTOPRINTER:
2244 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2245 case LyXRC::RC_PRINT_COMMAND:
2246 case LyXRC::RC_RTL_SUPPORT:
2247 case LyXRC::RC_SCREEN_DPI:
2248 case LyXRC::RC_SCREEN_FONT_ROMAN:
2249 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2250 case LyXRC::RC_SCREEN_FONT_SANS:
2251 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2252 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2253 case LyXRC::RC_SCREEN_FONT_SIZES:
2254 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2255 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2256 case LyXRC::RC_GEOMETRY_SESSION:
2257 case LyXRC::RC_SCREEN_ZOOM:
2258 case LyXRC::RC_SERVERPIPE:
2259 case LyXRC::RC_SET_COLOR:
2260 case LyXRC::RC_SHOW_BANNER:
2261 case LyXRC::RC_SPELL_COMMAND:
2262 case LyXRC::RC_TEMPDIRPATH:
2263 case LyXRC::RC_TEMPLATEPATH:
2264 case LyXRC::RC_TEX_ALLOWS_SPACES:
2265 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2266 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2267 os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2269 case LyXRC::RC_UIFILE:
2270 case LyXRC::RC_USER_EMAIL:
2271 case LyXRC::RC_USER_NAME:
2272 case LyXRC::RC_USETEMPDIR:
2273 case LyXRC::RC_USE_ALT_LANG:
2274 case LyXRC::RC_USE_CONVERTER_CACHE:
2275 case LyXRC::RC_USE_ESC_CHARS:
2276 case LyXRC::RC_USE_INP_ENC:
2277 case LyXRC::RC_USE_PERS_DICT:
2278 case LyXRC::RC_USE_TOOLTIP:
2279 case LyXRC::RC_USE_PIXMAP_CACHE:
2280 case LyXRC::RC_USE_SPELL_LIB:
2281 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2282 case LyXRC::RC_SORT_LAYOUTS:
2283 case LyXRC::RC_VIEWER:
2284 case LyXRC::RC_LAST: