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/FontLoader.h"
81 #include "frontends/KeySymbol.h"
82 #include "frontends/LyXView.h"
83 #include "frontends/Selection.h"
85 #include "support/environment.h"
86 #include "support/FileFilterList.h"
87 #include "support/FileName.h"
88 #include "support/filetools.h"
89 #include "support/lstrings.h"
90 #include "support/Path.h"
91 #include "support/Package.h"
92 #include "support/Systemcall.h"
93 #include "support/convert.h"
94 #include "support/os.h"
99 using namespace lyx::support;
103 using frontend::LyXView;
105 namespace Alert = frontend::Alert;
107 extern bool quitting;
113 bool import(LyXView * lv, FileName const & filename,
114 string const & format, ErrorList & errorList)
116 docstring const displaypath = makeDisplayPath(filename.absFilename());
117 lv->message(bformat(_("Importing %1$s..."), displaypath));
119 FileName const lyxfile(changeExtension(filename.absFilename(), ".lyx"));
121 string loader_format;
122 vector<string> loaders = theConverters().loaders();
123 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
124 for (vector<string>::const_iterator it = loaders.begin();
125 it != loaders.end(); ++it) {
126 if (theConverters().isReachable(format, *it)) {
127 string const tofile =
128 changeExtension(filename.absFilename(),
129 formats.extension(*it));
130 if (!theConverters().convert(0, filename, FileName(tofile),
131 filename, format, *it, errorList))
137 if (loader_format.empty()) {
138 frontend::Alert::error(_("Couldn't import file"),
139 bformat(_("No information for importing the format %1$s."),
140 formats.prettyName(format)));
144 loader_format = format;
148 if (loader_format == "lyx") {
149 Buffer * buf = theLyXFunc().loadAndViewFile(lyxfile);
152 lv->message(_("file not imported!"));
157 buf->errors("Parse");
159 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
164 bool as_paragraphs = loader_format == "textparagraph";
165 string filename2 = (loader_format == format) ? filename.absFilename()
166 : changeExtension(filename.absFilename(),
167 formats.extension(loader_format));
168 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
169 theLyXFunc().setLyXView(lv);
170 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
174 lv->message(_("imported."));
180 // This function runs "configure" and then rereads lyx.defaults to
181 // reconfigure the automatic settings.
182 void reconfigure(LyXView & lv, string const & option)
184 // emit message signal.
185 lv.message(_("Running configure..."));
187 // Run configure in user lyx directory
188 PathChanger p(package().user_support());
189 string configure_command = package().configure_command();
190 configure_command += option;
192 int ret = one.startscript(Systemcall::Wait, configure_command);
194 // emit message signal.
195 lv.message(_("Reloading configuration..."));
196 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
197 // Re-read packages.lst
198 LaTeXFeatures::getAvailable();
201 Alert::information(_("System reconfiguration failed"),
202 _("The system reconfiguration has failed.\n"
203 "Default textclass is used but LyX may "
204 "not be able to work properly.\n"
205 "Please reconfigure again if needed."));
208 Alert::information(_("System reconfigured"),
209 _("The system has been reconfigured.\n"
210 "You need to restart LyX to make use of any\n"
211 "updated document class specifications."));
215 bool getLocalStatus(Cursor cursor, FuncRequest const & cmd, FuncStatus & status)
217 // Try to fix cursor in case it is broken.
218 cursor.fixIfBroken();
220 // This is, of course, a mess. Better create a new doc iterator and use
221 // this in Inset::getStatus. This might require an additional
222 // BufferView * arg, though (which should be avoided)
223 //Cursor safe = *this;
225 for ( ; cursor.depth(); cursor.pop()) {
226 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
227 BOOST_ASSERT(cursor.idx() <= cursor.lastidx());
228 BOOST_ASSERT(cursor.pit() <= cursor.lastpit());
229 BOOST_ASSERT(cursor.pos() <= cursor.lastpos());
231 // The inset's getStatus() will return 'true' if it made
232 // a definitive decision on whether it want to handle the
233 // request or not. The result of this decision is put into
234 // the 'status' parameter.
235 if (cursor.inset().getStatus(cursor, cmd, status)) {
244 /** Return the change status at cursor position, taking in account the
245 * status at each level of the document iterator (a table in a deleted
246 * footnote is deleted).
247 * When \param outer is true, the top slice is not looked at.
249 Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
251 size_t const depth = dit.depth() - (outer ? 1 : 0);
253 for (size_t i = 0 ; i < depth ; ++i) {
254 CursorSlice const & slice = dit[i];
255 if (!slice.inset().inMathed()
256 && slice.pos() < slice.paragraph().size()) {
257 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
258 if (ch != Change::UNCHANGED)
262 return Change::UNCHANGED;
269 : lyx_view_(0), encoded_last_key(0), meta_fake_bit(NoModifier)
274 void LyXFunc::initKeySequences(KeyMap * kb)
276 keyseq = KeySequence(kb, kb);
277 cancel_meta_seq = KeySequence(kb, kb);
281 void LyXFunc::setLyXView(LyXView * lv)
283 if (!quitting && lyx_view_ && lyx_view_->view() && lyx_view_ != lv)
284 // save current selection to the selection buffer to allow
285 // middle-button paste in another window
286 cap::saveSelection(lyx_view_->view()->cursor());
291 void LyXFunc::handleKeyFunc(kb_action action)
293 char_type c = encoded_last_key;
298 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
299 lyx_view_->view()->getIntl().getTransManager().deadkey(
300 c, get_accent(action).accent, view()->cursor().innerText(), view()->cursor());
301 // Need to clear, in case the minibuffer calls these
304 // copied verbatim from do_accent_char
305 view()->cursor().resetAnchor();
306 view()->processUpdateFlags(Update::FitCursor);
310 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
312 BOOST_ASSERT(lyx_view_);
313 if (!LyX::ref().session().bookmarks().isValid(idx))
315 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(idx);
316 BOOST_ASSERT(!bm.filename.empty());
317 string const file = bm.filename.absFilename();
318 // if the file is not opened, open it.
319 if (!theBufferList().exists(file)) {
321 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
325 // open may fail, so we need to test it again
326 if (!theBufferList().exists(file))
329 // if the current buffer is not that one, switch to it.
330 if (lyx_view_->buffer()->absFileName() != file) {
333 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
335 // moveToPosition try paragraph id first and then paragraph (pit, pos).
336 if (!view()->moveToPosition(bm.bottom_pit, bm.bottom_pos,
337 bm.top_id, bm.top_pos))
340 // Cursor jump succeeded!
341 Cursor const & cur = view()->cursor();
342 pit_type new_pit = cur.pit();
343 pos_type new_pos = cur.pos();
344 int new_id = cur.paragraph().id();
346 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
347 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
348 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
349 || bm.top_id != new_id) {
350 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
351 new_pit, new_pos, new_id);
356 void LyXFunc::processKeySym(KeySymbol const & keysym, KeyModifier state)
358 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
360 // Do nothing if we have nothing (JMarc)
361 if (!keysym.isOK()) {
362 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
363 lyx_view_->restartCursor();
367 if (keysym.isModifier()) {
368 LYXERR(Debug::KEY, "isModifier true");
369 lyx_view_->restartCursor();
373 //Encoding const * encoding = view()->cursor().getEncoding();
374 //encoded_last_key = keysym.getISOEncoded(encoding ? encoding->name() : "");
375 // FIXME: encoded_last_key shadows the member variable of the same
376 // name. Is that intended?
377 char_type encoded_last_key = keysym.getUCSEncoded();
379 // Do a one-deep top-level lookup for
380 // cancel and meta-fake keys. RVDK_PATCH_5
381 cancel_meta_seq.reset();
383 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
384 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
386 // When not cancel or meta-fake, do the normal lookup.
387 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
388 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
389 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
390 // remove Caps Lock and Mod2 as a modifiers
391 func = keyseq.addkey(keysym, (state | meta_fake_bit));
392 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
395 // Dont remove this unless you know what you are doing.
396 meta_fake_bit = NoModifier;
398 // Can this happen now ?
399 if (func.action == LFUN_NOACTION)
400 func = FuncRequest(LFUN_COMMAND_PREFIX);
402 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
403 << keyseq.print(KeySequence::Portable) << ']');
405 // already here we know if it any point in going further
406 // why not return already here if action == -1 and
407 // num_bytes == 0? (Lgb)
409 if (keyseq.length() > 1)
410 lyx_view_->message(keyseq.print(KeySequence::ForGui));
413 // Maybe user can only reach the key via holding down shift.
414 // Let's see. But only if shift is the only modifier
415 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
416 LYXERR(Debug::KEY, "Trying without shift");
417 func = keyseq.addkey(keysym, NoModifier);
418 LYXERR(Debug::KEY, "Action now " << func.action);
421 if (func.action == LFUN_UNKNOWN_ACTION) {
422 // Hmm, we didn't match any of the keysequences. See
423 // if it's normal insertable text not already covered
425 if (keysym.isText() && keyseq.length() == 1) {
426 LYXERR(Debug::KEY, "isText() is true, inserting.");
427 func = FuncRequest(LFUN_SELF_INSERT,
428 FuncRequest::KEYBOARD);
430 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
431 lyx_view_->message(_("Unknown function."));
432 lyx_view_->restartCursor();
437 if (func.action == LFUN_SELF_INSERT) {
438 if (encoded_last_key != 0) {
439 docstring const arg(1, encoded_last_key);
440 dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
441 FuncRequest::KEYBOARD));
442 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
448 lyx_view_->restartCursor();
452 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
454 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
457 Buffer * buf = lyx_view_? lyx_view_->buffer() : 0;
459 if (cmd.action == LFUN_NOACTION) {
460 flag.message(from_utf8(N_("Nothing to do")));
465 switch (cmd.action) {
466 case LFUN_UNKNOWN_ACTION:
467 #ifndef HAVE_LIBAIKSAURUS
468 case LFUN_THESAURUS_ENTRY:
478 if (flag.unknown()) {
479 flag.message(from_utf8(N_("Unknown action")));
483 if (!flag.enabled()) {
484 if (flag.message().empty())
485 flag.message(from_utf8(N_("Command disabled")));
489 // Check whether we need a buffer
490 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
492 flag.message(from_utf8(N_("Command not allowed with"
493 "out any document open")));
498 // I would really like to avoid having this switch and rather try to
499 // encode this in the function itself.
500 // -- And I'd rather let an inset decide which LFUNs it is willing
501 // to handle (Andre')
503 switch (cmd.action) {
505 // FIXME: these cases should be hidden in GuiApplication::getStatus().
506 case LFUN_WINDOW_CLOSE:
508 return theApp()->getStatus(cmd);
512 // FIXME: these cases should be hidden in GuiView::getStatus().
513 case LFUN_DIALOG_TOGGLE:
514 case LFUN_DIALOG_SHOW:
515 case LFUN_DIALOG_UPDATE:
516 case LFUN_TOOLBAR_TOGGLE:
517 case LFUN_INSET_APPLY:
518 case LFUN_BUFFER_WRITE:
519 case LFUN_BUFFER_WRITE_AS:
521 return lyx_view_->getStatus(cmd);
525 case LFUN_BUFFER_TOGGLE_READ_ONLY:
526 flag.setOnOff(buf->isReadonly());
529 case LFUN_BUFFER_SWITCH:
530 // toggle on the current buffer, but do not toggle off
531 // the other ones (is that a good idea?)
532 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
536 case LFUN_BUFFER_EXPORT:
537 enable = cmd.argument() == "custom"
538 || buf->isExportable(to_utf8(cmd.argument()));
541 case LFUN_BUFFER_CHKTEX:
542 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
545 case LFUN_BUILD_PROGRAM:
546 enable = buf->isExportable("program");
549 case LFUN_VC_REGISTER:
550 enable = !buf->lyxvc().inUse();
552 case LFUN_VC_CHECK_IN:
553 enable = buf->lyxvc().inUse() && !buf->isReadonly();
555 case LFUN_VC_CHECK_OUT:
556 enable = buf->lyxvc().inUse() && buf->isReadonly();
559 case LFUN_VC_UNDO_LAST:
560 enable = buf->lyxvc().inUse();
562 case LFUN_BUFFER_RELOAD:
563 enable = !buf->isUnnamed() && buf->fileName().exists()
564 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
567 case LFUN_CITATION_INSERT: {
568 FuncRequest fr(LFUN_INSET_INSERT, "citation");
569 enable = getStatus(fr).enabled();
573 // This could be used for the no-GUI version. The GUI version is handled in
574 // LyXView::getStatus().
576 case LFUN_BUFFER_WRITE:
577 case LFUN_BUFFER_WRITE_AS: {
578 Buffer * b = theBufferList().getBuffer(cmd.getArg(0));
579 enable = b && (b->isUnnamed() || !b->isClean());
584 case LFUN_BUFFER_WRITE_ALL: {
585 // We enable the command only if there are some modified buffers
586 Buffer * first = theBufferList().first();
591 // We cannot use a for loop as the buffer list is a cycle.
597 b = theBufferList().next(b);
598 } while (b != first);
602 case LFUN_BOOKMARK_GOTO: {
603 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
604 enable = LyX::ref().session().bookmarks().isValid(num);
608 case LFUN_BOOKMARK_CLEAR:
609 enable = LyX::ref().session().bookmarks().size() > 0;
612 // this one is difficult to get right. As a half-baked
613 // solution, we consider only the first action of the sequence
614 case LFUN_COMMAND_SEQUENCE: {
615 // argument contains ';'-terminated commands
616 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
617 FuncRequest func(lyxaction.lookupFunc(firstcmd));
618 func.origin = cmd.origin;
619 flag = getStatus(func);
625 string name = to_utf8(cmd.argument());
626 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
627 func.origin = cmd.origin;
628 flag = getStatus(func);
629 LyX::ref().topLevelCmdDef().release(name);
631 // catch recursion or unknown command definiton
632 // all operations until the recursion or unknown command
633 // definiton occures are performed, so set the state to enabled
639 case LFUN_BUFFER_NEW:
640 case LFUN_BUFFER_NEW_TEMPLATE:
641 case LFUN_WORD_FIND_FORWARD:
642 case LFUN_WORD_FIND_BACKWARD:
643 case LFUN_COMMAND_PREFIX:
644 case LFUN_COMMAND_EXECUTE:
646 case LFUN_META_PREFIX:
647 case LFUN_BUFFER_CLOSE:
648 case LFUN_BUFFER_UPDATE:
649 case LFUN_BUFFER_VIEW:
650 case LFUN_MASTER_BUFFER_UPDATE:
651 case LFUN_MASTER_BUFFER_VIEW:
652 case LFUN_BUFFER_IMPORT:
653 case LFUN_BUFFER_AUTO_SAVE:
654 case LFUN_RECONFIGURE:
658 case LFUN_DROP_LAYOUTS_CHOICE:
660 case LFUN_SERVER_GET_NAME:
661 case LFUN_SERVER_NOTIFY:
662 case LFUN_SERVER_GOTO_FILE_ROW:
663 case LFUN_DIALOG_HIDE:
664 case LFUN_DIALOG_DISCONNECT_INSET:
665 case LFUN_BUFFER_CHILD_OPEN:
666 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
667 case LFUN_KEYMAP_OFF:
668 case LFUN_KEYMAP_PRIMARY:
669 case LFUN_KEYMAP_SECONDARY:
670 case LFUN_KEYMAP_TOGGLE:
672 case LFUN_BUFFER_EXPORT_CUSTOM:
673 case LFUN_BUFFER_PRINT:
674 case LFUN_PREFERENCES_SAVE:
675 case LFUN_SCREEN_FONT_UPDATE:
678 case LFUN_EXTERNAL_EDIT:
679 case LFUN_GRAPHICS_EDIT:
680 case LFUN_ALL_INSETS_TOGGLE:
681 case LFUN_BUFFER_LANGUAGE:
682 case LFUN_TEXTCLASS_APPLY:
683 case LFUN_TEXTCLASS_LOAD:
684 case LFUN_BUFFER_SAVE_AS_DEFAULT:
685 case LFUN_BUFFER_PARAMS_APPLY:
686 case LFUN_LAYOUT_MODULES_CLEAR:
687 case LFUN_LAYOUT_MODULE_ADD:
688 case LFUN_LAYOUT_RELOAD:
689 case LFUN_LYXRC_APPLY:
690 case LFUN_BUFFER_NEXT:
691 case LFUN_BUFFER_PREVIOUS:
692 case LFUN_WINDOW_NEW:
694 // these are handled in our dispatch()
702 if (!getLocalStatus(view()->cursor(), cmd, flag))
703 flag = view()->getStatus(cmd);
709 // Can we use a readonly buffer?
710 if (buf && buf->isReadonly()
711 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
712 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
713 flag.message(from_utf8(N_("Document is read-only")));
717 // Are we in a DELETED change-tracking region?
719 && lookupChangeType(view()->cursor(), true) == Change::DELETED
720 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
721 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
722 flag.message(from_utf8(N_("This portion of the document is deleted.")));
726 // the default error message if we disable the command
727 if (!flag.enabled() && flag.message().empty())
728 flag.message(from_utf8(N_("Command disabled")));
734 bool LyXFunc::ensureBufferClean(BufferView * bv)
736 Buffer & buf = bv->buffer();
740 docstring const file = buf.fileName().displayName(30);
741 docstring text = bformat(_("The document %1$s has unsaved "
742 "changes.\n\nDo you want to save "
743 "the document?"), file);
744 int const ret = Alert::prompt(_("Save changed document?"),
745 text, 0, 1, _("&Save"),
749 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
751 return buf.isClean();
757 void showPrintError(string const & name)
759 docstring str = bformat(_("Could not print the document %1$s.\n"
760 "Check that your printer is set up correctly."),
761 makeDisplayPath(name, 50));
762 Alert::error(_("Print document failed"), str);
766 void loadTextClass(string const & name)
768 pair<bool, textclass_type> const tc_pair =
769 textclasslist.numberOfClass(name);
771 if (!tc_pair.first) {
772 lyxerr << "Document class \"" << name
773 << "\" does not exist."
778 textclass_type const tc = tc_pair.second;
780 if (!textclasslist[tc].load()) {
781 docstring s = bformat(_("The document class %1$s."
782 "could not be loaded."),
783 from_utf8(textclasslist[tc].name()));
784 Alert::error(_("Could not load class"), s);
789 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
794 void LyXFunc::dispatch(FuncRequest const & cmd)
796 string const argument = to_utf8(cmd.argument());
797 kb_action const action = cmd.action;
799 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
800 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
802 // we have not done anything wrong yet.
804 dispatch_buffer.erase();
806 // redraw the screen at the end (first of the two drawing steps).
807 //This is done unless explicitely requested otherwise
808 Update::flags updateFlags = Update::FitCursor;
810 FuncStatus const flag = getStatus(cmd);
811 if (!flag.enabled()) {
812 // We cannot use this function here
813 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
814 << lyxaction.getActionName(action)
815 << " [" << action << "] is disabled at this location");
816 setErrorMessage(flag.message());
820 case LFUN_WORD_FIND_FORWARD:
821 case LFUN_WORD_FIND_BACKWARD: {
822 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
823 static docstring last_search;
824 docstring searched_string;
826 if (!cmd.argument().empty()) {
827 last_search = cmd.argument();
828 searched_string = cmd.argument();
830 searched_string = last_search;
833 if (searched_string.empty())
836 bool const fw = action == LFUN_WORD_FIND_FORWARD;
837 docstring const data =
838 find2string(searched_string, true, false, fw);
839 find(view(), FuncRequest(LFUN_WORD_FIND, data));
843 case LFUN_COMMAND_PREFIX:
844 BOOST_ASSERT(lyx_view_);
845 lyx_view_->message(keyseq.printOptions(true));
849 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
851 meta_fake_bit = NoModifier;
852 if (lyx_view_->buffer())
853 // cancel any selection
854 dispatch(FuncRequest(LFUN_MARK_OFF));
855 setMessage(from_ascii(N_("Cancel")));
858 case LFUN_META_PREFIX:
859 meta_fake_bit = AltModifier;
860 setMessage(keyseq.print(KeySequence::ForGui));
863 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
864 BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
865 Buffer * buf = lyx_view_->buffer();
866 if (buf->lyxvc().inUse())
867 buf->lyxvc().toggleReadOnly();
869 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
873 // --- Menus -----------------------------------------------
874 case LFUN_BUFFER_NEW:
875 lyx_view_->newDocument(argument, false);
876 updateFlags = Update::None;
879 case LFUN_BUFFER_NEW_TEMPLATE:
880 lyx_view_->newDocument(argument, true);
881 updateFlags = Update::None;
884 case LFUN_BUFFER_CLOSE:
886 updateFlags = Update::None;
889 case LFUN_BUFFER_RELOAD: {
890 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
891 docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
892 docstring text = bformat(_("Any changes will be lost. Are you sure "
893 "you want to revert to the saved version of the document %1$s?"), file);
894 int const ret = Alert::prompt(_("Revert to saved document?"),
895 text, 1, 1, _("&Revert"), _("&Cancel"));
902 case LFUN_BUFFER_UPDATE:
903 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
904 lyx_view_->buffer()->doExport(argument, true);
907 case LFUN_BUFFER_VIEW:
908 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
909 lyx_view_->buffer()->preview(argument);
912 case LFUN_MASTER_BUFFER_UPDATE:
913 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
914 lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
917 case LFUN_MASTER_BUFFER_VIEW:
918 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
919 lyx_view_->buffer()->masterBuffer()->preview(argument);
922 case LFUN_BUILD_PROGRAM:
923 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
924 lyx_view_->buffer()->doExport("program", true);
927 case LFUN_BUFFER_CHKTEX:
928 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
929 lyx_view_->buffer()->runChktex();
932 case LFUN_BUFFER_EXPORT:
933 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
934 if (argument == "custom")
935 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
937 lyx_view_->buffer()->doExport(argument, false);
940 case LFUN_BUFFER_EXPORT_CUSTOM: {
941 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
943 string command = split(argument, format_name, ' ');
944 Format const * format = formats.getFormat(format_name);
946 lyxerr << "Format \"" << format_name
947 << "\" not recognized!"
952 Buffer * buffer = lyx_view_->buffer();
954 // The name of the file created by the conversion process
957 // Output to filename
958 if (format->name() == "lyx") {
959 string const latexname = buffer->latexName(false);
960 filename = changeExtension(latexname,
961 format->extension());
962 filename = addName(buffer->temppath(), filename);
964 if (!buffer->writeFile(FileName(filename)))
968 buffer->doExport(format_name, true, filename);
971 // Substitute $$FName for filename
972 if (!contains(command, "$$FName"))
973 command = "( " + command + " ) < $$FName";
974 command = subst(command, "$$FName", filename);
976 // Execute the command in the background
978 call.startscript(Systemcall::DontWait, command);
982 case LFUN_BUFFER_PRINT: {
983 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
984 // FIXME: cmd.getArg() might fail if one of the arguments
985 // contains double quotes
986 string target = cmd.getArg(0);
987 string target_name = cmd.getArg(1);
988 string command = cmd.getArg(2);
991 || target_name.empty()
992 || command.empty()) {
993 lyxerr << "Unable to parse \""
994 << argument << '"' << endl;
997 if (target != "printer" && target != "file") {
998 lyxerr << "Unrecognized target \""
999 << target << '"' << endl;
1003 Buffer * buffer = lyx_view_->buffer();
1005 if (!buffer->doExport("dvi", true)) {
1006 showPrintError(buffer->absFileName());
1010 // Push directory path.
1011 string const path = buffer->temppath();
1012 // Prevent the compiler from optimizing away p
1016 // there are three cases here:
1017 // 1. we print to a file
1018 // 2. we print directly to a printer
1019 // 3. we print using a spool command (print to file first)
1022 string const dviname =
1023 changeExtension(buffer->latexName(true), "dvi");
1025 if (target == "printer") {
1026 if (!lyxrc.print_spool_command.empty()) {
1027 // case 3: print using a spool
1028 string const psname =
1029 changeExtension(dviname,".ps");
1030 command += ' ' + lyxrc.print_to_file
1033 + quoteName(dviname);
1036 lyxrc.print_spool_command + ' ';
1037 if (target_name != "default") {
1038 command2 += lyxrc.print_spool_printerprefix
1042 command2 += quoteName(psname);
1044 // If successful, then spool command
1045 res = one.startscript(
1050 res = one.startscript(
1051 Systemcall::DontWait,
1054 // case 2: print directly to a printer
1055 if (target_name != "default")
1056 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1057 res = one.startscript(
1058 Systemcall::DontWait,
1059 command + quoteName(dviname));
1063 // case 1: print to a file
1064 FileName const filename(makeAbsPath(target_name,
1065 lyx_view_->buffer()->filePath()));
1066 FileName const dvifile(makeAbsPath(dviname, path));
1067 if (filename.exists()) {
1068 docstring text = bformat(
1069 _("The file %1$s already exists.\n\n"
1070 "Do you want to overwrite that file?"),
1071 makeDisplayPath(filename.absFilename()));
1072 if (Alert::prompt(_("Overwrite file?"),
1073 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1076 command += ' ' + lyxrc.print_to_file
1077 + quoteName(filename.toFilesystemEncoding())
1079 + quoteName(dvifile.toFilesystemEncoding());
1080 res = one.startscript(Systemcall::DontWait,
1085 showPrintError(buffer->absFileName());
1089 case LFUN_BUFFER_IMPORT:
1093 case LFUN_BUFFER_AUTO_SAVE:
1094 lyx_view_->buffer()->autoSave();
1097 case LFUN_RECONFIGURE:
1098 BOOST_ASSERT(lyx_view_);
1099 // argument is any additional parameter to the configure.py command
1100 reconfigure(*lyx_view_, argument);
1103 case LFUN_HELP_OPEN: {
1104 BOOST_ASSERT(lyx_view_);
1105 string const arg = argument;
1107 setErrorMessage(from_ascii(N_("Missing argument")));
1110 FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1111 if (fname.empty()) {
1112 lyxerr << "LyX: unable to find documentation file `"
1113 << arg << "'. Bad installation?" << endl;
1116 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1117 makeDisplayPath(fname.absFilename())));
1118 Buffer * buf = loadAndViewFile(fname, false);
1121 lyx_view_->setBuffer(buf);
1122 buf->errors("Parse");
1124 updateFlags = Update::None;
1128 // --- version control -------------------------------
1129 case LFUN_VC_REGISTER:
1130 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1131 if (!ensureBufferClean(view()))
1133 if (!lyx_view_->buffer()->lyxvc().inUse()) {
1134 lyx_view_->buffer()->lyxvc().registrer();
1137 updateFlags = Update::Force;
1140 case LFUN_VC_CHECK_IN:
1141 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1142 if (!ensureBufferClean(view()))
1144 if (lyx_view_->buffer()->lyxvc().inUse()
1145 && !lyx_view_->buffer()->isReadonly()) {
1146 lyx_view_->buffer()->lyxvc().checkIn();
1151 case LFUN_VC_CHECK_OUT:
1152 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1153 if (!ensureBufferClean(view()))
1155 if (lyx_view_->buffer()->lyxvc().inUse()
1156 && lyx_view_->buffer()->isReadonly()) {
1157 lyx_view_->buffer()->lyxvc().checkOut();
1162 case LFUN_VC_REVERT:
1163 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1164 lyx_view_->buffer()->lyxvc().revert();
1168 case LFUN_VC_UNDO_LAST:
1169 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1170 lyx_view_->buffer()->lyxvc().undoLast();
1174 // --- buffers ----------------------------------------
1176 case LFUN_FILE_NEW: {
1177 BOOST_ASSERT(lyx_view_);
1179 string tmpname = split(argument, name, ':'); // Split filename
1180 Buffer * const b = newFile(name, tmpname);
1182 lyx_view_->setBuffer(b);
1183 updateFlags = Update::None;
1187 case LFUN_FILE_OPEN:
1188 BOOST_ASSERT(lyx_view_);
1190 updateFlags = Update::None;
1193 // --- lyxserver commands ----------------------------
1194 case LFUN_SERVER_GET_NAME:
1195 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1196 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1197 LYXERR(Debug::INFO, "FNAME["
1198 << lyx_view_->buffer()->absFileName() << ']');
1201 case LFUN_SERVER_NOTIFY:
1202 dispatch_buffer = keyseq.print(KeySequence::Portable);
1203 theServer().notifyClient(to_utf8(dispatch_buffer));
1206 case LFUN_SERVER_GOTO_FILE_ROW: {
1207 BOOST_ASSERT(lyx_view_);
1210 istringstream is(argument);
1211 is >> file_name >> row;
1213 bool loaded = false;
1214 if (prefixIs(file_name, package().temp_dir().absFilename()))
1215 // Needed by inverse dvi search. If it is a file
1216 // in tmpdir, call the apropriated function
1217 buf = theBufferList().getBufferFromTmp(file_name);
1219 // Must replace extension of the file to be .lyx
1220 // and get full path
1221 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1222 // Either change buffer or load the file
1223 if (theBufferList().exists(s.absFilename()))
1224 buf = theBufferList().getBuffer(s.absFilename());
1226 buf = loadAndViewFile(s);
1232 updateFlags = Update::None;
1237 lyx_view_->setBuffer(buf);
1238 view()->setCursorFromRow(row);
1240 buf->errors("Parse");
1241 updateFlags = Update::FitCursor;
1246 case LFUN_DIALOG_SHOW_NEW_INSET: {
1247 BOOST_ASSERT(lyx_view_);
1248 string const name = cmd.getArg(0);
1249 InsetCode code = insetCode(name);
1250 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1251 bool insetCodeOK = true;
1260 case HYPERLINK_CODE: {
1261 InsetCommandParams p(code);
1262 data = InsetCommandMailer::params2string(name, p);
1265 case INCLUDE_CODE: {
1266 // data is the include type: one of "include",
1267 // "input", "verbatiminput" or "verbatiminput*"
1269 // default type is requested
1271 InsetCommandParams p(INCLUDE_CODE, data);
1272 data = InsetCommandMailer::params2string("include", p);
1276 // \c data == "Boxed" || "Frameless" etc
1277 InsetBoxParams p(data);
1278 data = InsetBoxMailer::params2string(p);
1282 InsetBranchParams p;
1283 data = InsetBranchMailer::params2string(p);
1287 InsetCommandParams p(CITE_CODE);
1288 data = InsetCommandMailer::params2string(name, p);
1292 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1295 case EXTERNAL_CODE: {
1296 InsetExternalParams p;
1297 Buffer const & buffer = *lyx_view_->buffer();
1298 data = InsetExternalMailer::params2string(p, buffer);
1303 data = InsetFloatMailer::params2string(p);
1306 case LISTINGS_CODE: {
1307 InsetListingsParams p;
1308 data = InsetListingsMailer::params2string(p);
1311 case GRAPHICS_CODE: {
1312 InsetGraphicsParams p;
1313 Buffer const & buffer = *lyx_view_->buffer();
1314 data = InsetGraphicsMailer::params2string(p, buffer);
1319 data = InsetNoteMailer::params2string(p);
1324 data = InsetVSpaceMailer::params2string(space);
1329 data = InsetWrapMailer::params2string(p);
1333 lyxerr << "Inset type '" << name <<
1334 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1335 insetCodeOK = false;
1337 } // end switch(code)
1339 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1343 case LFUN_CITATION_INSERT: {
1344 BOOST_ASSERT(lyx_view_);
1345 if (!argument.empty()) {
1346 // we can have one optional argument, delimited by '|'
1347 // citation-insert <key>|<text_before>
1348 // this should be enhanced to also support text_after
1349 // and citation style
1350 string arg = argument;
1352 if (contains(argument, "|")) {
1353 arg = token(argument, '|', 0);
1354 opt1 = token(argument, '|', 1);
1356 InsetCommandParams icp(CITE_CODE);
1357 icp["key"] = from_utf8(arg);
1359 icp["before"] = from_utf8(opt1);
1360 string icstr = InsetCommandMailer::params2string("citation", icp);
1361 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1364 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1368 case LFUN_BUFFER_CHILD_OPEN: {
1369 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1370 Buffer * parent = lyx_view_->buffer();
1371 FileName filename = makeAbsPath(argument, parent->filePath());
1372 view()->saveBookmark(false);
1374 bool parsed = false;
1375 if (theBufferList().exists(filename.absFilename())) {
1376 child = theBufferList().getBuffer(filename.absFilename());
1378 setMessage(bformat(_("Opening child document %1$s..."),
1379 makeDisplayPath(filename.absFilename())));
1380 child = loadAndViewFile(filename, true);
1384 // Set the parent name of the child document.
1385 // This makes insertion of citations and references in the child work,
1386 // when the target is in the parent or another child document.
1387 child->setParent(parent);
1388 updateLabels(*child->masterBuffer());
1389 lyx_view_->setBuffer(child);
1391 child->errors("Parse");
1394 // If a screen update is required (in case where auto_open is false),
1395 // setBuffer() would have taken care of it already. Otherwise we shall
1396 // reset the update flag because it can cause a circular problem.
1398 updateFlags = Update::None;
1402 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1403 BOOST_ASSERT(lyx_view_);
1404 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1407 case LFUN_KEYMAP_OFF:
1408 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1409 lyx_view_->view()->getIntl().keyMapOn(false);
1412 case LFUN_KEYMAP_PRIMARY:
1413 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1414 lyx_view_->view()->getIntl().keyMapPrim();
1417 case LFUN_KEYMAP_SECONDARY:
1418 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1419 lyx_view_->view()->getIntl().keyMapSec();
1422 case LFUN_KEYMAP_TOGGLE:
1423 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1424 lyx_view_->view()->getIntl().toggleKeyMap();
1430 string rest = split(argument, countstr, ' ');
1431 istringstream is(countstr);
1434 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1435 for (int i = 0; i < count; ++i)
1436 dispatch(lyxaction.lookupFunc(rest));
1440 case LFUN_COMMAND_SEQUENCE: {
1441 // argument contains ';'-terminated commands
1442 string arg = argument;
1443 while (!arg.empty()) {
1445 arg = split(arg, first, ';');
1446 FuncRequest func(lyxaction.lookupFunc(first));
1447 func.origin = cmd.origin;
1455 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1456 func.origin = cmd.origin;
1458 LyX::ref().topLevelCmdDef().release(argument);
1460 if (func.action == LFUN_UNKNOWN_ACTION) {
1461 // unknown command definition
1462 lyxerr << "Warning: unknown command definition `"
1466 // recursion detected
1467 lyxerr << "Warning: Recursion in the command definition `"
1468 << argument << "' detected"
1475 case LFUN_PREFERENCES_SAVE: {
1476 lyxrc.write(makeAbsPath("preferences",
1477 package().user_support().absFilename()),
1482 case LFUN_SET_COLOR: {
1484 string const x11_name = split(argument, lyx_name, ' ');
1485 if (lyx_name.empty() || x11_name.empty()) {
1486 setErrorMessage(from_ascii(N_(
1487 "Syntax: set-color <lyx_name>"
1492 bool const graphicsbg_changed =
1493 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1494 x11_name != lcolor.getX11Name(Color_graphicsbg));
1496 if (!lcolor.setColor(lyx_name, x11_name)) {
1498 bformat(_("Set-color \"%1$s\" failed "
1499 "- color is undefined or "
1500 "may not be redefined"),
1501 from_utf8(lyx_name)));
1505 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1507 if (graphicsbg_changed) {
1508 // FIXME: The graphics cache no longer has a changeDisplay method.
1510 graphics::GCache::get().changeDisplay(true);
1517 BOOST_ASSERT(lyx_view_);
1518 lyx_view_->message(from_utf8(argument));
1521 case LFUN_EXTERNAL_EDIT: {
1522 BOOST_ASSERT(lyx_view_);
1523 FuncRequest fr(action, argument);
1524 InsetExternal().dispatch(view()->cursor(), fr);
1528 case LFUN_GRAPHICS_EDIT: {
1529 FuncRequest fr(action, argument);
1530 InsetGraphics().dispatch(view()->cursor(), fr);
1534 case LFUN_ALL_INSETS_TOGGLE: {
1535 BOOST_ASSERT(lyx_view_);
1537 string const name = split(argument, action, ' ');
1538 InsetCode const inset_code = insetCode(name);
1540 Cursor & cur = view()->cursor();
1541 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1543 Inset & inset = lyx_view_->buffer()->inset();
1544 InsetIterator it = inset_iterator_begin(inset);
1545 InsetIterator const end = inset_iterator_end(inset);
1546 for (; it != end; ++it) {
1547 if (!it->asInsetMath()
1548 && (inset_code == NO_CODE
1549 || inset_code == it->lyxCode())) {
1550 Cursor tmpcur = cur;
1551 tmpcur.pushBackward(*it);
1552 it->dispatch(tmpcur, fr);
1555 updateFlags = Update::Force | Update::FitCursor;
1559 case LFUN_BUFFER_LANGUAGE: {
1560 BOOST_ASSERT(lyx_view_);
1561 Buffer & buffer = *lyx_view_->buffer();
1562 Language const * oldL = buffer.params().language;
1563 Language const * newL = languages.getLanguage(argument);
1564 if (!newL || oldL == newL)
1567 if (oldL->rightToLeft() == newL->rightToLeft()
1568 && !buffer.isMultiLingual())
1569 buffer.changeLanguage(oldL, newL);
1573 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1574 string const fname =
1575 addName(addPath(package().user_support().absFilename(), "templates/"),
1577 Buffer defaults(fname);
1579 istringstream ss(argument);
1582 int const unknown_tokens = defaults.readHeader(lex);
1584 if (unknown_tokens != 0) {
1585 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1586 << unknown_tokens << " unknown token"
1587 << (unknown_tokens == 1 ? "" : "s")
1591 if (defaults.writeFile(FileName(defaults.absFileName())))
1592 setMessage(bformat(_("Document defaults saved in %1$s"),
1593 makeDisplayPath(fname)));
1595 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1599 case LFUN_BUFFER_PARAMS_APPLY: {
1600 BOOST_ASSERT(lyx_view_);
1601 biblio::CiteEngine const oldEngine =
1602 lyx_view_->buffer()->params().getEngine();
1604 Buffer * buffer = lyx_view_->buffer();
1606 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1608 Cursor & cur = view()->cursor();
1609 cur.recordUndoFullDocument();
1611 istringstream ss(argument);
1614 int const unknown_tokens = buffer->readHeader(lex);
1616 if (unknown_tokens != 0) {
1617 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1618 << unknown_tokens << " unknown token"
1619 << (unknown_tokens == 1 ? "" : "s")
1623 updateLayout(oldClass, buffer);
1625 biblio::CiteEngine const newEngine =
1626 lyx_view_->buffer()->params().getEngine();
1628 if (oldEngine != newEngine) {
1629 FuncRequest fr(LFUN_INSET_REFRESH);
1631 Inset & inset = lyx_view_->buffer()->inset();
1632 InsetIterator it = inset_iterator_begin(inset);
1633 InsetIterator const end = inset_iterator_end(inset);
1634 for (; it != end; ++it)
1635 if (it->lyxCode() == CITE_CODE)
1636 it->dispatch(cur, fr);
1639 updateFlags = Update::Force | Update::FitCursor;
1640 // We are here most certainaly because of a change in the document
1641 // It is then better to make sure that all dialogs are in sync
1642 // with current document settings. LyXView::restartCursor() achieve this.
1643 lyx_view_->restartCursor();
1647 case LFUN_LAYOUT_MODULES_CLEAR: {
1648 BOOST_ASSERT(lyx_view_);
1649 Buffer * buffer = lyx_view_->buffer();
1650 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1651 view()->cursor().recordUndoFullDocument();
1652 buffer->params().clearLayoutModules();
1653 updateLayout(oldClass, buffer);
1654 updateFlags = Update::Force | Update::FitCursor;
1658 case LFUN_LAYOUT_MODULE_ADD: {
1659 BOOST_ASSERT(lyx_view_);
1660 Buffer * buffer = lyx_view_->buffer();
1661 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1662 view()->cursor().recordUndoFullDocument();
1663 buffer->params().addLayoutModule(argument);
1664 updateLayout(oldClass, buffer);
1665 updateFlags = Update::Force | Update::FitCursor;
1669 case LFUN_TEXTCLASS_APPLY: {
1670 BOOST_ASSERT(lyx_view_);
1671 Buffer * buffer = lyx_view_->buffer();
1673 loadTextClass(argument);
1675 pair<bool, textclass_type> const tc_pair =
1676 textclasslist.numberOfClass(argument);
1681 textclass_type const old_class = buffer->params().getBaseClass();
1682 textclass_type const new_class = tc_pair.second;
1684 if (old_class == new_class)
1688 //Save the old, possibly modular, layout for use in conversion.
1689 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1690 view()->cursor().recordUndoFullDocument();
1691 buffer->params().setBaseClass(new_class);
1692 updateLayout(oldClass, buffer);
1693 updateFlags = Update::Force | Update::FitCursor;
1697 case LFUN_LAYOUT_RELOAD: {
1698 BOOST_ASSERT(lyx_view_);
1699 Buffer * buffer = lyx_view_->buffer();
1700 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1701 textclass_type const tc = buffer->params().getBaseClass();
1702 textclasslist.reset(tc);
1703 buffer->params().setBaseClass(tc);
1704 updateLayout(oldClass, buffer);
1705 updateFlags = Update::Force | Update::FitCursor;
1709 case LFUN_TEXTCLASS_LOAD:
1710 loadTextClass(argument);
1713 case LFUN_LYXRC_APPLY: {
1714 LyXRC const lyxrc_orig = lyxrc;
1716 istringstream ss(argument);
1717 bool const success = lyxrc.read(ss) == 0;
1720 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1721 << "Unable to read lyxrc data"
1726 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1728 theApp()->resetGui();
1730 /// We force the redraw in any case because there might be
1731 /// some screen font changes.
1732 /// FIXME: only the current view will be updated. the Gui
1733 /// class is able to furnish the list of views.
1734 updateFlags = Update::Force;
1738 case LFUN_BOOKMARK_GOTO:
1739 // go to bookmark, open unopened file and switch to buffer if necessary
1740 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1743 case LFUN_BOOKMARK_CLEAR:
1744 LyX::ref().session().bookmarks().clear();
1748 BOOST_ASSERT(theApp());
1749 // Let the frontend dispatch its own actions.
1750 if (theApp()->dispatch(cmd))
1751 // Nothing more to do.
1754 // Let the current LyXView dispatch its own actions.
1755 BOOST_ASSERT(lyx_view_);
1756 if (lyx_view_->dispatch(cmd)) {
1757 if (lyx_view_->view())
1758 updateFlags = lyx_view_->view()->cursor().result().update();
1762 // FIXME: Probably a good idea to inverse the Cursor and BufferView
1765 // Let the current Cursor dispatch its own actions.
1766 BOOST_ASSERT(lyx_view_->view());
1767 view()->cursor().getPos(cursorPosBeforeDispatchX_,
1768 cursorPosBeforeDispatchY_);
1769 view()->cursor().dispatch(cmd);
1770 updateFlags = view()->cursor().result().update();
1771 if (!view()->cursor().result().dispatched())
1772 // Let the current BufferView dispatch its own actions.
1773 updateFlags = view()->dispatch(cmd);
1778 if (lyx_view_ && lyx_view_->buffer()) {
1779 // BufferView::update() updates the ViewMetricsInfo and
1780 // also initializes the position cache for all insets in
1781 // (at least partially) visible top-level paragraphs.
1782 // We will redraw the screen only if needed.
1783 view()->processUpdateFlags(updateFlags);
1785 // if we executed a mutating lfun, mark the buffer as dirty
1787 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1788 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1789 lyx_view_->buffer()->markDirty();
1791 //Do we have a selection?
1792 theSelection().haveSelection(view()->cursor().selection());
1795 if (!quitting && lyx_view_) {
1796 // Some messages may already be translated, so we cannot use _()
1797 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1802 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1804 const bool verbose = (cmd.origin == FuncRequest::MENU
1805 || cmd.origin == FuncRequest::TOOLBAR
1806 || cmd.origin == FuncRequest::COMMANDBUFFER);
1808 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1809 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1811 lyx_view_->message(msg);
1815 docstring dispatch_msg = msg;
1816 if (!dispatch_msg.empty())
1817 dispatch_msg += ' ';
1819 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1821 bool argsadded = false;
1823 if (!cmd.argument().empty()) {
1824 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1825 comname += ' ' + cmd.argument();
1830 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1832 if (!shortcuts.empty())
1833 comname += ": " + shortcuts;
1834 else if (!argsadded && !cmd.argument().empty())
1835 comname += ' ' + cmd.argument();
1837 if (!comname.empty()) {
1838 comname = rtrim(comname);
1839 dispatch_msg += '(' + rtrim(comname) + ')';
1842 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1843 if (!dispatch_msg.empty())
1844 lyx_view_->message(dispatch_msg);
1848 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1850 lyx_view_->setBusy(true);
1852 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1855 lyx_view_->message(_("Document not loaded."));
1856 lyx_view_->setBusy(false);
1860 lyx_view_->setBuffer(newBuffer);
1862 // scroll to the position when the file was last closed
1863 if (lyxrc.use_lastfilepos) {
1864 LastFilePosSection::FilePos filepos =
1865 LyX::ref().session().lastFilePos().load(filename);
1866 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1870 LyX::ref().session().lastFiles().add(filename);
1872 lyx_view_->setBusy(false);
1877 void LyXFunc::open(string const & fname)
1879 string initpath = lyxrc.document_path;
1881 if (lyx_view_->buffer()) {
1882 string const trypath = lyx_view_->buffer()->filePath();
1883 // If directory is writeable, use this as default.
1884 if (FileName(trypath).isDirWritable())
1890 if (fname.empty()) {
1891 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
1892 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1893 dlg.setButton2(_("Examples|#E#e"),
1894 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1896 FileDialog::Result result =
1897 dlg.open(from_utf8(initpath),
1898 FileFilterList(_("LyX Documents (*.lyx)")),
1901 if (result.first == FileDialog::Later)
1904 filename = to_utf8(result.second);
1906 // check selected filename
1907 if (filename.empty()) {
1908 lyx_view_->message(_("Canceled."));
1914 // get absolute path of file and add ".lyx" to the filename if
1916 FileName const fullname = fileSearch(string(), filename, "lyx");
1917 if (!fullname.empty())
1918 filename = fullname.absFilename();
1920 // if the file doesn't exist, let the user create one
1921 if (!fullname.exists()) {
1922 // the user specifically chose this name. Believe him.
1923 Buffer * const b = newFile(filename, string(), true);
1925 lyx_view_->setBuffer(b);
1929 docstring const disp_fn = makeDisplayPath(filename);
1930 lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
1933 Buffer * buf = loadAndViewFile(fullname);
1936 lyx_view_->setBuffer(buf);
1937 buf->errors("Parse");
1938 str2 = bformat(_("Document %1$s opened."), disp_fn);
1940 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1942 lyx_view_->message(str2);
1946 void LyXFunc::doImport(string const & argument)
1949 string filename = split(argument, format, ' ');
1951 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
1952 << " file: " << filename);
1954 // need user interaction
1955 if (filename.empty()) {
1956 string initpath = lyxrc.document_path;
1958 if (lyx_view_->buffer()) {
1959 string const trypath = lyx_view_->buffer()->filePath();
1960 // If directory is writeable, use this as default.
1961 if (FileName(trypath).isDirWritable())
1965 docstring const text = bformat(_("Select %1$s file to import"),
1966 formats.prettyName(format));
1968 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
1969 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1970 dlg.setButton2(_("Examples|#E#e"),
1971 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1973 docstring filter = formats.prettyName(format);
1976 filter += from_utf8(formats.extension(format));
1979 FileDialog::Result result =
1980 dlg.open(from_utf8(initpath),
1981 FileFilterList(filter),
1984 if (result.first == FileDialog::Later)
1987 filename = to_utf8(result.second);
1989 // check selected filename
1990 if (filename.empty())
1991 lyx_view_->message(_("Canceled."));
1994 if (filename.empty())
1997 // get absolute path of file
1998 FileName const fullname(makeAbsPath(filename));
2000 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2002 // Check if the document already is open
2003 Buffer * buf = theBufferList().getBuffer(lyxfile.absFilename());
2004 if (use_gui && buf) {
2005 lyx_view_->setBuffer(buf);
2006 if (!lyx_view_->closeBuffer()) {
2007 lyx_view_->message(_("Canceled."));
2012 // if the file exists already, and we didn't do
2013 // -i lyx thefile.lyx, warn
2014 if (lyxfile.exists() && fullname != lyxfile) {
2015 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2017 docstring text = bformat(_("The document %1$s already exists.\n\n"
2018 "Do you want to overwrite that document?"), file);
2019 int const ret = Alert::prompt(_("Overwrite document?"),
2020 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2023 lyx_view_->message(_("Canceled."));
2028 ErrorList errorList;
2029 import(lyx_view_, fullname, format, errorList);
2030 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2034 void LyXFunc::closeBuffer()
2036 // goto bookmark to update bookmark pit.
2037 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2038 gotoBookmark(i+1, false, false);
2040 lyx_view_->closeBuffer();
2044 void LyXFunc::reloadBuffer()
2046 FileName filename = lyx_view_->buffer()->fileName();
2047 // The user has already confirmed that the changes, if any, should
2048 // be discarded. So we just release the Buffer and don't call closeBuffer();
2049 theBufferList().release(lyx_view_->buffer());
2050 Buffer * buf = loadAndViewFile(filename);
2051 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2055 lyx_view_->setBuffer(buf);
2056 buf->errors("Parse");
2057 str = bformat(_("Document %1$s reloaded."), disp_fn);
2059 str = bformat(_("Could not reload document %1$s"), disp_fn);
2061 lyx_view_->message(str);
2064 // Each "lyx_view_" should have it's own message method. lyxview and
2065 // the minibuffer would use the minibuffer, but lyxserver would
2066 // send an ERROR signal to its client. Alejandro 970603
2067 // This function is bit problematic when it comes to NLS, to make the
2068 // lyx servers client be language indepenent we must not translate
2069 // strings sent to this func.
2070 void LyXFunc::setErrorMessage(docstring const & m) const
2072 dispatch_buffer = m;
2077 void LyXFunc::setMessage(docstring const & m) const
2079 dispatch_buffer = m;
2083 docstring const LyXFunc::viewStatusMessage()
2085 // When meta-fake key is pressed, show the key sequence so far + "M-".
2087 return keyseq.print(KeySequence::ForGui) + "M-";
2089 // Else, when a non-complete key sequence is pressed,
2090 // show the available options.
2091 if (keyseq.length() > 0 && !keyseq.deleted())
2092 return keyseq.printOptions(true);
2094 BOOST_ASSERT(lyx_view_);
2095 if (!lyx_view_->buffer())
2096 return _("Welcome to LyX!");
2098 return view()->cursor().currentState();
2102 BufferView * LyXFunc::view() const
2104 BOOST_ASSERT(lyx_view_);
2105 return lyx_view_->view();
2109 bool LyXFunc::wasMetaKey() const
2111 return (meta_fake_bit != NoModifier);
2115 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2118 lyx_view_->message(_("Converting document to new document class..."));
2120 StableDocIterator backcur(view()->cursor());
2121 ErrorList & el = buffer->errorList("Class Switch");
2122 cap::switchBetweenClasses(
2123 oldlayout, buffer->params().getTextClassPtr(),
2124 static_cast<InsetText &>(buffer->inset()), el);
2126 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2128 buffer->errors("Class Switch");
2129 updateLabels(*buffer);
2135 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2137 // Why the switch you might ask. It is a trick to ensure that all
2138 // the elements in the LyXRCTags enum is handled. As you can see
2139 // there are no breaks at all. So it is just a huge fall-through.
2140 // The nice thing is that we will get a warning from the compiler
2141 // if we forget an element.
2142 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2144 case LyXRC::RC_ACCEPT_COMPOUND:
2145 case LyXRC::RC_ALT_LANG:
2146 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2147 case LyXRC::RC_PLAINTEXT_LINELEN:
2148 case LyXRC::RC_AUTOREGIONDELETE:
2149 case LyXRC::RC_AUTORESET_OPTIONS:
2150 case LyXRC::RC_AUTOSAVE:
2151 case LyXRC::RC_AUTO_NUMBER:
2152 case LyXRC::RC_BACKUPDIR_PATH:
2153 case LyXRC::RC_BIBTEX_COMMAND:
2154 case LyXRC::RC_BINDFILE:
2155 case LyXRC::RC_CHECKLASTFILES:
2156 case LyXRC::RC_USELASTFILEPOS:
2157 case LyXRC::RC_LOADSESSION:
2158 case LyXRC::RC_CHKTEX_COMMAND:
2159 case LyXRC::RC_CONVERTER:
2160 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2161 case LyXRC::RC_COPIER:
2162 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2163 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2164 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2165 case LyXRC::RC_DATE_INSERT_FORMAT:
2166 case LyXRC::RC_DEFAULT_LANGUAGE:
2167 case LyXRC::RC_DEFAULT_PAPERSIZE:
2168 case LyXRC::RC_DEFFILE:
2169 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2170 case LyXRC::RC_DISPLAY_GRAPHICS:
2171 case LyXRC::RC_DOCUMENTPATH:
2172 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2173 FileName path(lyxrc_new.document_path);
2174 if (path.exists() && path.isDirectory())
2175 package().document_dir() = FileName(lyxrc.document_path);
2177 case LyXRC::RC_ESC_CHARS:
2178 case LyXRC::RC_EXAMPLEPATH:
2179 case LyXRC::RC_FONT_ENCODING:
2180 case LyXRC::RC_FORMAT:
2181 case LyXRC::RC_INDEX_COMMAND:
2182 case LyXRC::RC_INPUT:
2183 case LyXRC::RC_KBMAP:
2184 case LyXRC::RC_KBMAP_PRIMARY:
2185 case LyXRC::RC_KBMAP_SECONDARY:
2186 case LyXRC::RC_LABEL_INIT_LENGTH:
2187 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2188 case LyXRC::RC_LANGUAGE_AUTO_END:
2189 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2190 case LyXRC::RC_LANGUAGE_COMMAND_END:
2191 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2192 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2193 case LyXRC::RC_LANGUAGE_PACKAGE:
2194 case LyXRC::RC_LANGUAGE_USE_BABEL:
2195 case LyXRC::RC_MAKE_BACKUP:
2196 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2197 case LyXRC::RC_NUMLASTFILES:
2198 case LyXRC::RC_PATH_PREFIX:
2199 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2200 prependEnvPath("PATH", lyxrc.path_prefix);
2202 case LyXRC::RC_PERS_DICT:
2203 case LyXRC::RC_PREVIEW:
2204 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2205 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2206 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2207 case LyXRC::RC_PRINTCOPIESFLAG:
2208 case LyXRC::RC_PRINTER:
2209 case LyXRC::RC_PRINTEVENPAGEFLAG:
2210 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2211 case LyXRC::RC_PRINTFILEEXTENSION:
2212 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2213 case LyXRC::RC_PRINTODDPAGEFLAG:
2214 case LyXRC::RC_PRINTPAGERANGEFLAG:
2215 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2216 case LyXRC::RC_PRINTPAPERFLAG:
2217 case LyXRC::RC_PRINTREVERSEFLAG:
2218 case LyXRC::RC_PRINTSPOOL_COMMAND:
2219 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2220 case LyXRC::RC_PRINTTOFILE:
2221 case LyXRC::RC_PRINTTOPRINTER:
2222 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2223 case LyXRC::RC_PRINT_COMMAND:
2224 case LyXRC::RC_RTL_SUPPORT:
2225 case LyXRC::RC_SCREEN_DPI:
2226 case LyXRC::RC_SCREEN_FONT_ROMAN:
2227 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2228 case LyXRC::RC_SCREEN_FONT_SANS:
2229 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2230 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2231 case LyXRC::RC_SCREEN_FONT_SIZES:
2232 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2233 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2234 case LyXRC::RC_GEOMETRY_SESSION:
2235 case LyXRC::RC_SCREEN_ZOOM:
2236 case LyXRC::RC_SERVERPIPE:
2237 case LyXRC::RC_SET_COLOR:
2238 case LyXRC::RC_SHOW_BANNER:
2239 case LyXRC::RC_SPELL_COMMAND:
2240 case LyXRC::RC_TEMPDIRPATH:
2241 case LyXRC::RC_TEMPLATEPATH:
2242 case LyXRC::RC_TEX_ALLOWS_SPACES:
2243 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2244 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2245 os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2247 case LyXRC::RC_UIFILE:
2248 case LyXRC::RC_USER_EMAIL:
2249 case LyXRC::RC_USER_NAME:
2250 case LyXRC::RC_USETEMPDIR:
2251 case LyXRC::RC_USE_ALT_LANG:
2252 case LyXRC::RC_USE_CONVERTER_CACHE:
2253 case LyXRC::RC_USE_ESC_CHARS:
2254 case LyXRC::RC_USE_INP_ENC:
2255 case LyXRC::RC_USE_PERS_DICT:
2256 case LyXRC::RC_USE_PIXMAP_CACHE:
2257 case LyXRC::RC_USE_SPELL_LIB:
2258 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2259 case LyXRC::RC_SORT_LAYOUTS:
2260 case LyXRC::RC_VIEWER:
2261 case LyXRC::RC_LAST: