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 if (cmd.argument() == "prefs"
517 || cmd.argument() == "aboutlyx")
520 return lyx_view_->getStatus(cmd);
525 case LFUN_TOOLBAR_TOGGLE:
526 case LFUN_INSET_APPLY:
527 case LFUN_BUFFER_WRITE:
528 case LFUN_BUFFER_WRITE_AS:
530 return lyx_view_->getStatus(cmd);
534 case LFUN_BUFFER_TOGGLE_READ_ONLY:
535 flag.setOnOff(buf->isReadonly());
538 case LFUN_BUFFER_SWITCH:
539 // toggle on the current buffer, but do not toggle off
540 // the other ones (is that a good idea?)
541 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
545 case LFUN_BUFFER_EXPORT:
546 enable = cmd.argument() == "custom"
547 || buf->isExportable(to_utf8(cmd.argument()));
550 case LFUN_BUFFER_CHKTEX:
551 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
554 case LFUN_BUILD_PROGRAM:
555 enable = buf->isExportable("program");
558 case LFUN_VC_REGISTER:
559 enable = !buf->lyxvc().inUse();
561 case LFUN_VC_CHECK_IN:
562 enable = buf->lyxvc().inUse() && !buf->isReadonly();
564 case LFUN_VC_CHECK_OUT:
565 enable = buf->lyxvc().inUse() && buf->isReadonly();
568 case LFUN_VC_UNDO_LAST:
569 enable = buf->lyxvc().inUse();
571 case LFUN_BUFFER_RELOAD:
572 enable = !buf->isUnnamed() && buf->fileName().exists()
573 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
576 case LFUN_CITATION_INSERT: {
577 FuncRequest fr(LFUN_INSET_INSERT, "citation");
578 enable = getStatus(fr).enabled();
582 // This could be used for the no-GUI version. The GUI version is handled in
583 // LyXView::getStatus(). See above.
585 case LFUN_BUFFER_WRITE:
586 case LFUN_BUFFER_WRITE_AS: {
587 Buffer * b = theBufferList().getBuffer(cmd.getArg(0));
588 enable = b && (b->isUnnamed() || !b->isClean());
593 case LFUN_BUFFER_WRITE_ALL: {
594 // We enable the command only if there are some modified buffers
595 Buffer * first = theBufferList().first();
600 // We cannot use a for loop as the buffer list is a cycle.
606 b = theBufferList().next(b);
607 } while (b != first);
611 case LFUN_BOOKMARK_GOTO: {
612 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
613 enable = LyX::ref().session().bookmarks().isValid(num);
617 case LFUN_BOOKMARK_CLEAR:
618 enable = LyX::ref().session().bookmarks().size() > 0;
621 // this one is difficult to get right. As a half-baked
622 // solution, we consider only the first action of the sequence
623 case LFUN_COMMAND_SEQUENCE: {
624 // argument contains ';'-terminated commands
625 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
626 FuncRequest func(lyxaction.lookupFunc(firstcmd));
627 func.origin = cmd.origin;
628 flag = getStatus(func);
634 string name = to_utf8(cmd.argument());
635 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
636 func.origin = cmd.origin;
637 flag = getStatus(func);
638 LyX::ref().topLevelCmdDef().release(name);
640 // catch recursion or unknown command definiton
641 // all operations until the recursion or unknown command
642 // definiton occures are performed, so set the state to enabled
648 case LFUN_BUFFER_NEW:
649 case LFUN_BUFFER_NEW_TEMPLATE:
650 case LFUN_WORD_FIND_FORWARD:
651 case LFUN_WORD_FIND_BACKWARD:
652 case LFUN_COMMAND_PREFIX:
653 case LFUN_COMMAND_EXECUTE:
655 case LFUN_META_PREFIX:
656 case LFUN_BUFFER_CLOSE:
657 case LFUN_BUFFER_UPDATE:
658 case LFUN_BUFFER_VIEW:
659 case LFUN_MASTER_BUFFER_UPDATE:
660 case LFUN_MASTER_BUFFER_VIEW:
661 case LFUN_BUFFER_IMPORT:
662 case LFUN_BUFFER_AUTO_SAVE:
663 case LFUN_RECONFIGURE:
667 case LFUN_DROP_LAYOUTS_CHOICE:
669 case LFUN_SERVER_GET_NAME:
670 case LFUN_SERVER_NOTIFY:
671 case LFUN_SERVER_GOTO_FILE_ROW:
672 case LFUN_DIALOG_HIDE:
673 case LFUN_DIALOG_DISCONNECT_INSET:
674 case LFUN_BUFFER_CHILD_OPEN:
675 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
676 case LFUN_KEYMAP_OFF:
677 case LFUN_KEYMAP_PRIMARY:
678 case LFUN_KEYMAP_SECONDARY:
679 case LFUN_KEYMAP_TOGGLE:
681 case LFUN_BUFFER_EXPORT_CUSTOM:
682 case LFUN_BUFFER_PRINT:
683 case LFUN_PREFERENCES_SAVE:
684 case LFUN_SCREEN_FONT_UPDATE:
687 case LFUN_EXTERNAL_EDIT:
688 case LFUN_GRAPHICS_EDIT:
689 case LFUN_ALL_INSETS_TOGGLE:
690 case LFUN_BUFFER_LANGUAGE:
691 case LFUN_TEXTCLASS_APPLY:
692 case LFUN_TEXTCLASS_LOAD:
693 case LFUN_BUFFER_SAVE_AS_DEFAULT:
694 case LFUN_BUFFER_PARAMS_APPLY:
695 case LFUN_LAYOUT_MODULES_CLEAR:
696 case LFUN_LAYOUT_MODULE_ADD:
697 case LFUN_LAYOUT_RELOAD:
698 case LFUN_LYXRC_APPLY:
699 case LFUN_BUFFER_NEXT:
700 case LFUN_BUFFER_PREVIOUS:
701 case LFUN_WINDOW_NEW:
703 // these are handled in our dispatch()
711 if (!getLocalStatus(view()->cursor(), cmd, flag))
712 flag = view()->getStatus(cmd);
718 // Can we use a readonly buffer?
719 if (buf && buf->isReadonly()
720 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
721 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
722 flag.message(from_utf8(N_("Document is read-only")));
726 // Are we in a DELETED change-tracking region?
728 && lookupChangeType(view()->cursor(), true) == Change::DELETED
729 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
730 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
731 flag.message(from_utf8(N_("This portion of the document is deleted.")));
735 // the default error message if we disable the command
736 if (!flag.enabled() && flag.message().empty())
737 flag.message(from_utf8(N_("Command disabled")));
743 bool LyXFunc::ensureBufferClean(BufferView * bv)
745 Buffer & buf = bv->buffer();
749 docstring const file = buf.fileName().displayName(30);
750 docstring text = bformat(_("The document %1$s has unsaved "
751 "changes.\n\nDo you want to save "
752 "the document?"), file);
753 int const ret = Alert::prompt(_("Save changed document?"),
754 text, 0, 1, _("&Save"),
758 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
760 return buf.isClean();
766 void showPrintError(string const & name)
768 docstring str = bformat(_("Could not print the document %1$s.\n"
769 "Check that your printer is set up correctly."),
770 makeDisplayPath(name, 50));
771 Alert::error(_("Print document failed"), str);
775 void loadTextClass(string const & name)
777 pair<bool, textclass_type> const tc_pair =
778 textclasslist.numberOfClass(name);
780 if (!tc_pair.first) {
781 lyxerr << "Document class \"" << name
782 << "\" does not exist."
787 textclass_type const tc = tc_pair.second;
789 if (!textclasslist[tc].load()) {
790 docstring s = bformat(_("The document class %1$s."
791 "could not be loaded."),
792 from_utf8(textclasslist[tc].name()));
793 Alert::error(_("Could not load class"), s);
798 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
803 void LyXFunc::dispatch(FuncRequest const & cmd)
805 string const argument = to_utf8(cmd.argument());
806 kb_action const action = cmd.action;
808 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
809 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
811 // we have not done anything wrong yet.
813 dispatch_buffer.erase();
815 // redraw the screen at the end (first of the two drawing steps).
816 //This is done unless explicitely requested otherwise
817 Update::flags updateFlags = Update::FitCursor;
819 FuncStatus const flag = getStatus(cmd);
820 if (!flag.enabled()) {
821 // We cannot use this function here
822 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
823 << lyxaction.getActionName(action)
824 << " [" << action << "] is disabled at this location");
825 setErrorMessage(flag.message());
829 case LFUN_WORD_FIND_FORWARD:
830 case LFUN_WORD_FIND_BACKWARD: {
831 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
832 static docstring last_search;
833 docstring searched_string;
835 if (!cmd.argument().empty()) {
836 last_search = cmd.argument();
837 searched_string = cmd.argument();
839 searched_string = last_search;
842 if (searched_string.empty())
845 bool const fw = action == LFUN_WORD_FIND_FORWARD;
846 docstring const data =
847 find2string(searched_string, true, false, fw);
848 find(view(), FuncRequest(LFUN_WORD_FIND, data));
852 case LFUN_COMMAND_PREFIX:
853 BOOST_ASSERT(lyx_view_);
854 lyx_view_->message(keyseq.printOptions(true));
858 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
860 meta_fake_bit = NoModifier;
861 if (lyx_view_->buffer())
862 // cancel any selection
863 dispatch(FuncRequest(LFUN_MARK_OFF));
864 setMessage(from_ascii(N_("Cancel")));
867 case LFUN_META_PREFIX:
868 meta_fake_bit = AltModifier;
869 setMessage(keyseq.print(KeySequence::ForGui));
872 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
873 BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
874 Buffer * buf = lyx_view_->buffer();
875 if (buf->lyxvc().inUse())
876 buf->lyxvc().toggleReadOnly();
878 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
882 // --- Menus -----------------------------------------------
883 case LFUN_BUFFER_NEW:
884 lyx_view_->newDocument(argument, false);
885 updateFlags = Update::None;
888 case LFUN_BUFFER_NEW_TEMPLATE:
889 lyx_view_->newDocument(argument, true);
890 updateFlags = Update::None;
893 case LFUN_BUFFER_CLOSE:
895 updateFlags = Update::None;
898 case LFUN_BUFFER_RELOAD: {
899 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
900 docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
901 docstring text = bformat(_("Any changes will be lost. Are you sure "
902 "you want to revert to the saved version of the document %1$s?"), file);
903 int const ret = Alert::prompt(_("Revert to saved document?"),
904 text, 1, 1, _("&Revert"), _("&Cancel"));
911 case LFUN_BUFFER_UPDATE:
912 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
913 lyx_view_->buffer()->doExport(argument, true);
916 case LFUN_BUFFER_VIEW:
917 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
918 lyx_view_->buffer()->preview(argument);
921 case LFUN_MASTER_BUFFER_UPDATE:
922 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
923 lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
926 case LFUN_MASTER_BUFFER_VIEW:
927 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
928 lyx_view_->buffer()->masterBuffer()->preview(argument);
931 case LFUN_BUILD_PROGRAM:
932 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
933 lyx_view_->buffer()->doExport("program", true);
936 case LFUN_BUFFER_CHKTEX:
937 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
938 lyx_view_->buffer()->runChktex();
941 case LFUN_BUFFER_EXPORT:
942 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
943 if (argument == "custom")
944 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
946 lyx_view_->buffer()->doExport(argument, false);
949 case LFUN_BUFFER_EXPORT_CUSTOM: {
950 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
952 string command = split(argument, format_name, ' ');
953 Format const * format = formats.getFormat(format_name);
955 lyxerr << "Format \"" << format_name
956 << "\" not recognized!"
961 Buffer * buffer = lyx_view_->buffer();
963 // The name of the file created by the conversion process
966 // Output to filename
967 if (format->name() == "lyx") {
968 string const latexname = buffer->latexName(false);
969 filename = changeExtension(latexname,
970 format->extension());
971 filename = addName(buffer->temppath(), filename);
973 if (!buffer->writeFile(FileName(filename)))
977 buffer->doExport(format_name, true, filename);
980 // Substitute $$FName for filename
981 if (!contains(command, "$$FName"))
982 command = "( " + command + " ) < $$FName";
983 command = subst(command, "$$FName", filename);
985 // Execute the command in the background
987 call.startscript(Systemcall::DontWait, command);
991 case LFUN_BUFFER_PRINT: {
992 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
993 // FIXME: cmd.getArg() might fail if one of the arguments
994 // contains double quotes
995 string target = cmd.getArg(0);
996 string target_name = cmd.getArg(1);
997 string command = cmd.getArg(2);
1000 || target_name.empty()
1001 || command.empty()) {
1002 lyxerr << "Unable to parse \""
1003 << argument << '"' << endl;
1006 if (target != "printer" && target != "file") {
1007 lyxerr << "Unrecognized target \""
1008 << target << '"' << endl;
1012 Buffer * buffer = lyx_view_->buffer();
1014 if (!buffer->doExport("dvi", true)) {
1015 showPrintError(buffer->absFileName());
1019 // Push directory path.
1020 string const path = buffer->temppath();
1021 // Prevent the compiler from optimizing away p
1025 // there are three cases here:
1026 // 1. we print to a file
1027 // 2. we print directly to a printer
1028 // 3. we print using a spool command (print to file first)
1031 string const dviname =
1032 changeExtension(buffer->latexName(true), "dvi");
1034 if (target == "printer") {
1035 if (!lyxrc.print_spool_command.empty()) {
1036 // case 3: print using a spool
1037 string const psname =
1038 changeExtension(dviname,".ps");
1039 command += ' ' + lyxrc.print_to_file
1042 + quoteName(dviname);
1045 lyxrc.print_spool_command + ' ';
1046 if (target_name != "default") {
1047 command2 += lyxrc.print_spool_printerprefix
1051 command2 += quoteName(psname);
1053 // If successful, then spool command
1054 res = one.startscript(
1059 res = one.startscript(
1060 Systemcall::DontWait,
1063 // case 2: print directly to a printer
1064 if (target_name != "default")
1065 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1066 res = one.startscript(
1067 Systemcall::DontWait,
1068 command + quoteName(dviname));
1072 // case 1: print to a file
1073 FileName const filename(makeAbsPath(target_name,
1074 lyx_view_->buffer()->filePath()));
1075 FileName const dvifile(makeAbsPath(dviname, path));
1076 if (filename.exists()) {
1077 docstring text = bformat(
1078 _("The file %1$s already exists.\n\n"
1079 "Do you want to overwrite that file?"),
1080 makeDisplayPath(filename.absFilename()));
1081 if (Alert::prompt(_("Overwrite file?"),
1082 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1085 command += ' ' + lyxrc.print_to_file
1086 + quoteName(filename.toFilesystemEncoding())
1088 + quoteName(dvifile.toFilesystemEncoding());
1089 res = one.startscript(Systemcall::DontWait,
1094 showPrintError(buffer->absFileName());
1098 case LFUN_BUFFER_IMPORT:
1102 case LFUN_BUFFER_AUTO_SAVE:
1103 lyx_view_->buffer()->autoSave();
1106 case LFUN_RECONFIGURE:
1107 BOOST_ASSERT(lyx_view_);
1108 // argument is any additional parameter to the configure.py command
1109 reconfigure(*lyx_view_, argument);
1112 case LFUN_HELP_OPEN: {
1113 BOOST_ASSERT(lyx_view_);
1114 string const arg = argument;
1116 setErrorMessage(from_ascii(N_("Missing argument")));
1119 FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1120 if (fname.empty()) {
1121 lyxerr << "LyX: unable to find documentation file `"
1122 << arg << "'. Bad installation?" << endl;
1125 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1126 makeDisplayPath(fname.absFilename())));
1127 Buffer * buf = loadAndViewFile(fname, false);
1130 lyx_view_->setBuffer(buf);
1131 buf->errors("Parse");
1133 updateFlags = Update::None;
1137 // --- version control -------------------------------
1138 case LFUN_VC_REGISTER:
1139 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1140 if (!ensureBufferClean(view()))
1142 if (!lyx_view_->buffer()->lyxvc().inUse()) {
1143 lyx_view_->buffer()->lyxvc().registrer();
1146 updateFlags = Update::Force;
1149 case LFUN_VC_CHECK_IN:
1150 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1151 if (!ensureBufferClean(view()))
1153 if (lyx_view_->buffer()->lyxvc().inUse()
1154 && !lyx_view_->buffer()->isReadonly()) {
1155 lyx_view_->buffer()->lyxvc().checkIn();
1160 case LFUN_VC_CHECK_OUT:
1161 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1162 if (!ensureBufferClean(view()))
1164 if (lyx_view_->buffer()->lyxvc().inUse()
1165 && lyx_view_->buffer()->isReadonly()) {
1166 lyx_view_->buffer()->lyxvc().checkOut();
1171 case LFUN_VC_REVERT:
1172 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1173 lyx_view_->buffer()->lyxvc().revert();
1177 case LFUN_VC_UNDO_LAST:
1178 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1179 lyx_view_->buffer()->lyxvc().undoLast();
1183 // --- buffers ----------------------------------------
1185 case LFUN_FILE_NEW: {
1186 BOOST_ASSERT(lyx_view_);
1188 string tmpname = split(argument, name, ':'); // Split filename
1189 Buffer * const b = newFile(name, tmpname);
1191 lyx_view_->setBuffer(b);
1192 updateFlags = Update::None;
1196 case LFUN_FILE_OPEN:
1197 BOOST_ASSERT(lyx_view_);
1199 updateFlags = Update::None;
1202 // --- lyxserver commands ----------------------------
1203 case LFUN_SERVER_GET_NAME:
1204 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1205 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1206 LYXERR(Debug::INFO, "FNAME["
1207 << lyx_view_->buffer()->absFileName() << ']');
1210 case LFUN_SERVER_NOTIFY:
1211 dispatch_buffer = keyseq.print(KeySequence::Portable);
1212 theServer().notifyClient(to_utf8(dispatch_buffer));
1215 case LFUN_SERVER_GOTO_FILE_ROW: {
1216 BOOST_ASSERT(lyx_view_);
1219 istringstream is(argument);
1220 is >> file_name >> row;
1222 bool loaded = false;
1223 if (prefixIs(file_name, package().temp_dir().absFilename()))
1224 // Needed by inverse dvi search. If it is a file
1225 // in tmpdir, call the apropriated function
1226 buf = theBufferList().getBufferFromTmp(file_name);
1228 // Must replace extension of the file to be .lyx
1229 // and get full path
1230 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1231 // Either change buffer or load the file
1232 if (theBufferList().exists(s.absFilename()))
1233 buf = theBufferList().getBuffer(s.absFilename());
1235 buf = loadAndViewFile(s);
1241 updateFlags = Update::None;
1246 lyx_view_->setBuffer(buf);
1247 view()->setCursorFromRow(row);
1249 buf->errors("Parse");
1250 updateFlags = Update::FitCursor;
1255 case LFUN_DIALOG_SHOW_NEW_INSET: {
1256 BOOST_ASSERT(lyx_view_);
1257 string const name = cmd.getArg(0);
1258 InsetCode code = insetCode(name);
1259 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1260 bool insetCodeOK = true;
1269 case HYPERLINK_CODE: {
1270 InsetCommandParams p(code);
1271 data = InsetCommandMailer::params2string(name, p);
1274 case INCLUDE_CODE: {
1275 // data is the include type: one of "include",
1276 // "input", "verbatiminput" or "verbatiminput*"
1278 // default type is requested
1280 InsetCommandParams p(INCLUDE_CODE, data);
1281 data = InsetCommandMailer::params2string("include", p);
1285 // \c data == "Boxed" || "Frameless" etc
1286 InsetBoxParams p(data);
1287 data = InsetBoxMailer::params2string(p);
1291 InsetBranchParams p;
1292 data = InsetBranchMailer::params2string(p);
1296 InsetCommandParams p(CITE_CODE);
1297 data = InsetCommandMailer::params2string(name, p);
1301 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1304 case EXTERNAL_CODE: {
1305 InsetExternalParams p;
1306 Buffer const & buffer = *lyx_view_->buffer();
1307 data = InsetExternalMailer::params2string(p, buffer);
1312 data = InsetFloatMailer::params2string(p);
1315 case LISTINGS_CODE: {
1316 InsetListingsParams p;
1317 data = InsetListingsMailer::params2string(p);
1320 case GRAPHICS_CODE: {
1321 InsetGraphicsParams p;
1322 Buffer const & buffer = *lyx_view_->buffer();
1323 data = InsetGraphicsMailer::params2string(p, buffer);
1328 data = InsetNoteMailer::params2string(p);
1333 data = InsetVSpaceMailer::params2string(space);
1338 data = InsetWrapMailer::params2string(p);
1342 lyxerr << "Inset type '" << name <<
1343 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1344 insetCodeOK = false;
1346 } // end switch(code)
1348 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1352 case LFUN_CITATION_INSERT: {
1353 BOOST_ASSERT(lyx_view_);
1354 if (!argument.empty()) {
1355 // we can have one optional argument, delimited by '|'
1356 // citation-insert <key>|<text_before>
1357 // this should be enhanced to also support text_after
1358 // and citation style
1359 string arg = argument;
1361 if (contains(argument, "|")) {
1362 arg = token(argument, '|', 0);
1363 opt1 = token(argument, '|', 1);
1365 InsetCommandParams icp(CITE_CODE);
1366 icp["key"] = from_utf8(arg);
1368 icp["before"] = from_utf8(opt1);
1369 string icstr = InsetCommandMailer::params2string("citation", icp);
1370 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1373 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1377 case LFUN_BUFFER_CHILD_OPEN: {
1378 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1379 Buffer * parent = lyx_view_->buffer();
1380 FileName filename = makeAbsPath(argument, parent->filePath());
1381 view()->saveBookmark(false);
1383 bool parsed = false;
1384 if (theBufferList().exists(filename.absFilename())) {
1385 child = theBufferList().getBuffer(filename.absFilename());
1387 setMessage(bformat(_("Opening child document %1$s..."),
1388 makeDisplayPath(filename.absFilename())));
1389 child = loadAndViewFile(filename, true);
1393 // Set the parent name of the child document.
1394 // This makes insertion of citations and references in the child work,
1395 // when the target is in the parent or another child document.
1396 child->setParent(parent);
1397 updateLabels(*child->masterBuffer());
1398 lyx_view_->setBuffer(child);
1400 child->errors("Parse");
1403 // If a screen update is required (in case where auto_open is false),
1404 // setBuffer() would have taken care of it already. Otherwise we shall
1405 // reset the update flag because it can cause a circular problem.
1407 updateFlags = Update::None;
1411 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1412 BOOST_ASSERT(lyx_view_);
1413 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1416 case LFUN_KEYMAP_OFF:
1417 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1418 lyx_view_->view()->getIntl().keyMapOn(false);
1421 case LFUN_KEYMAP_PRIMARY:
1422 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1423 lyx_view_->view()->getIntl().keyMapPrim();
1426 case LFUN_KEYMAP_SECONDARY:
1427 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1428 lyx_view_->view()->getIntl().keyMapSec();
1431 case LFUN_KEYMAP_TOGGLE:
1432 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1433 lyx_view_->view()->getIntl().toggleKeyMap();
1439 string rest = split(argument, countstr, ' ');
1440 istringstream is(countstr);
1443 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1444 for (int i = 0; i < count; ++i)
1445 dispatch(lyxaction.lookupFunc(rest));
1449 case LFUN_COMMAND_SEQUENCE: {
1450 // argument contains ';'-terminated commands
1451 string arg = argument;
1452 while (!arg.empty()) {
1454 arg = split(arg, first, ';');
1455 FuncRequest func(lyxaction.lookupFunc(first));
1456 func.origin = cmd.origin;
1464 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1465 func.origin = cmd.origin;
1467 LyX::ref().topLevelCmdDef().release(argument);
1469 if (func.action == LFUN_UNKNOWN_ACTION) {
1470 // unknown command definition
1471 lyxerr << "Warning: unknown command definition `"
1475 // recursion detected
1476 lyxerr << "Warning: Recursion in the command definition `"
1477 << argument << "' detected"
1484 case LFUN_PREFERENCES_SAVE: {
1485 lyxrc.write(makeAbsPath("preferences",
1486 package().user_support().absFilename()),
1491 case LFUN_SET_COLOR: {
1493 string const x11_name = split(argument, lyx_name, ' ');
1494 if (lyx_name.empty() || x11_name.empty()) {
1495 setErrorMessage(from_ascii(N_(
1496 "Syntax: set-color <lyx_name>"
1501 bool const graphicsbg_changed =
1502 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1503 x11_name != lcolor.getX11Name(Color_graphicsbg));
1505 if (!lcolor.setColor(lyx_name, x11_name)) {
1507 bformat(_("Set-color \"%1$s\" failed "
1508 "- color is undefined or "
1509 "may not be redefined"),
1510 from_utf8(lyx_name)));
1514 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1516 if (graphicsbg_changed) {
1517 // FIXME: The graphics cache no longer has a changeDisplay method.
1519 graphics::GCache::get().changeDisplay(true);
1526 BOOST_ASSERT(lyx_view_);
1527 lyx_view_->message(from_utf8(argument));
1530 case LFUN_EXTERNAL_EDIT: {
1531 BOOST_ASSERT(lyx_view_);
1532 FuncRequest fr(action, argument);
1533 InsetExternal().dispatch(view()->cursor(), fr);
1537 case LFUN_GRAPHICS_EDIT: {
1538 FuncRequest fr(action, argument);
1539 InsetGraphics().dispatch(view()->cursor(), fr);
1543 case LFUN_ALL_INSETS_TOGGLE: {
1544 BOOST_ASSERT(lyx_view_);
1546 string const name = split(argument, action, ' ');
1547 InsetCode const inset_code = insetCode(name);
1549 Cursor & cur = view()->cursor();
1550 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1552 Inset & inset = lyx_view_->buffer()->inset();
1553 InsetIterator it = inset_iterator_begin(inset);
1554 InsetIterator const end = inset_iterator_end(inset);
1555 for (; it != end; ++it) {
1556 if (!it->asInsetMath()
1557 && (inset_code == NO_CODE
1558 || inset_code == it->lyxCode())) {
1559 Cursor tmpcur = cur;
1560 tmpcur.pushBackward(*it);
1561 it->dispatch(tmpcur, fr);
1564 updateFlags = Update::Force | Update::FitCursor;
1568 case LFUN_BUFFER_LANGUAGE: {
1569 BOOST_ASSERT(lyx_view_);
1570 Buffer & buffer = *lyx_view_->buffer();
1571 Language const * oldL = buffer.params().language;
1572 Language const * newL = languages.getLanguage(argument);
1573 if (!newL || oldL == newL)
1576 if (oldL->rightToLeft() == newL->rightToLeft()
1577 && !buffer.isMultiLingual())
1578 buffer.changeLanguage(oldL, newL);
1582 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1583 string const fname =
1584 addName(addPath(package().user_support().absFilename(), "templates/"),
1586 Buffer defaults(fname);
1588 istringstream ss(argument);
1591 int const unknown_tokens = defaults.readHeader(lex);
1593 if (unknown_tokens != 0) {
1594 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1595 << unknown_tokens << " unknown token"
1596 << (unknown_tokens == 1 ? "" : "s")
1600 if (defaults.writeFile(FileName(defaults.absFileName())))
1601 setMessage(bformat(_("Document defaults saved in %1$s"),
1602 makeDisplayPath(fname)));
1604 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1608 case LFUN_BUFFER_PARAMS_APPLY: {
1609 BOOST_ASSERT(lyx_view_);
1610 biblio::CiteEngine const oldEngine =
1611 lyx_view_->buffer()->params().getEngine();
1613 Buffer * buffer = lyx_view_->buffer();
1615 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1617 Cursor & cur = view()->cursor();
1618 cur.recordUndoFullDocument();
1620 istringstream ss(argument);
1623 int const unknown_tokens = buffer->readHeader(lex);
1625 if (unknown_tokens != 0) {
1626 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1627 << unknown_tokens << " unknown token"
1628 << (unknown_tokens == 1 ? "" : "s")
1632 updateLayout(oldClass, buffer);
1634 biblio::CiteEngine const newEngine =
1635 lyx_view_->buffer()->params().getEngine();
1637 if (oldEngine != newEngine) {
1638 FuncRequest fr(LFUN_INSET_REFRESH);
1640 Inset & inset = lyx_view_->buffer()->inset();
1641 InsetIterator it = inset_iterator_begin(inset);
1642 InsetIterator const end = inset_iterator_end(inset);
1643 for (; it != end; ++it)
1644 if (it->lyxCode() == CITE_CODE)
1645 it->dispatch(cur, fr);
1648 updateFlags = Update::Force | Update::FitCursor;
1649 // We are here most certainaly because of a change in the document
1650 // It is then better to make sure that all dialogs are in sync
1651 // with current document settings. LyXView::restartCursor() achieve this.
1652 lyx_view_->restartCursor();
1656 case LFUN_LAYOUT_MODULES_CLEAR: {
1657 BOOST_ASSERT(lyx_view_);
1658 Buffer * buffer = lyx_view_->buffer();
1659 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1660 view()->cursor().recordUndoFullDocument();
1661 buffer->params().clearLayoutModules();
1662 buffer->params().makeTextClass();
1663 updateLayout(oldClass, buffer);
1664 updateFlags = Update::Force | Update::FitCursor;
1668 case LFUN_LAYOUT_MODULE_ADD: {
1669 BOOST_ASSERT(lyx_view_);
1670 Buffer * buffer = lyx_view_->buffer();
1671 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1672 view()->cursor().recordUndoFullDocument();
1673 buffer->params().addLayoutModule(argument);
1674 buffer->params().makeTextClass();
1675 updateLayout(oldClass, buffer);
1676 updateFlags = Update::Force | Update::FitCursor;
1680 case LFUN_TEXTCLASS_APPLY: {
1681 BOOST_ASSERT(lyx_view_);
1682 Buffer * buffer = lyx_view_->buffer();
1684 loadTextClass(argument);
1686 pair<bool, textclass_type> const tc_pair =
1687 textclasslist.numberOfClass(argument);
1692 textclass_type const old_class = buffer->params().getBaseClass();
1693 textclass_type const new_class = tc_pair.second;
1695 if (old_class == new_class)
1699 //Save the old, possibly modular, layout for use in conversion.
1700 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1701 view()->cursor().recordUndoFullDocument();
1702 buffer->params().setBaseClass(new_class);
1703 buffer->params().makeTextClass();
1704 updateLayout(oldClass, buffer);
1705 updateFlags = Update::Force | Update::FitCursor;
1709 case LFUN_LAYOUT_RELOAD: {
1710 BOOST_ASSERT(lyx_view_);
1711 Buffer * buffer = lyx_view_->buffer();
1712 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1713 textclass_type const tc = buffer->params().getBaseClass();
1714 textclasslist.reset(tc);
1715 buffer->params().setBaseClass(tc);
1716 buffer->params().makeTextClass();
1717 updateLayout(oldClass, buffer);
1718 updateFlags = Update::Force | Update::FitCursor;
1722 case LFUN_TEXTCLASS_LOAD:
1723 loadTextClass(argument);
1726 case LFUN_LYXRC_APPLY: {
1727 LyXRC const lyxrc_orig = lyxrc;
1729 istringstream ss(argument);
1730 bool const success = lyxrc.read(ss) == 0;
1733 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1734 << "Unable to read lyxrc data"
1739 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1741 theApp()->resetGui();
1743 /// We force the redraw in any case because there might be
1744 /// some screen font changes.
1745 /// FIXME: only the current view will be updated. the Gui
1746 /// class is able to furnish the list of views.
1747 updateFlags = Update::Force;
1751 case LFUN_BOOKMARK_GOTO:
1752 // go to bookmark, open unopened file and switch to buffer if necessary
1753 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1754 updateFlags = Update::FitCursor;
1757 case LFUN_BOOKMARK_CLEAR:
1758 LyX::ref().session().bookmarks().clear();
1762 BOOST_ASSERT(theApp());
1763 // Let the frontend dispatch its own actions.
1764 if (theApp()->dispatch(cmd))
1765 // Nothing more to do.
1768 // Let the current LyXView dispatch its own actions.
1769 BOOST_ASSERT(lyx_view_);
1770 if (lyx_view_->dispatch(cmd)) {
1771 if (lyx_view_->view())
1772 updateFlags = lyx_view_->view()->cursor().result().update();
1776 BOOST_ASSERT(lyx_view_->view());
1777 // Let the current BufferView dispatch its own actions.
1778 if (view()->dispatch(cmd)) {
1779 // The BufferView took care of its own updates if needed.
1780 updateFlags = Update::None;
1784 // Let the current Cursor dispatch its own actions.
1785 view()->cursor().getPos(cursorPosBeforeDispatchX_,
1786 cursorPosBeforeDispatchY_);
1787 view()->cursor().dispatch(cmd);
1788 updateFlags = view()->cursor().result().update();
1789 if (!view()->cursor().result().dispatched()) {
1790 // No update needed in this case (e.g. when reaching
1792 updateFlags = Update::None;
1796 if (lyx_view_ && lyx_view_->buffer()) {
1797 // BufferView::update() updates the ViewMetricsInfo and
1798 // also initializes the position cache for all insets in
1799 // (at least partially) visible top-level paragraphs.
1800 // We will redraw the screen only if needed.
1801 view()->processUpdateFlags(updateFlags);
1803 // if we executed a mutating lfun, mark the buffer as dirty
1805 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1806 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1807 lyx_view_->buffer()->markDirty();
1809 //Do we have a selection?
1810 theSelection().haveSelection(view()->cursor().selection());
1813 if (!quitting && lyx_view_) {
1814 // Some messages may already be translated, so we cannot use _()
1815 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1820 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1822 const bool verbose = (cmd.origin == FuncRequest::MENU
1823 || cmd.origin == FuncRequest::TOOLBAR
1824 || cmd.origin == FuncRequest::COMMANDBUFFER);
1826 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1827 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1829 lyx_view_->message(msg);
1833 docstring dispatch_msg = msg;
1834 if (!dispatch_msg.empty())
1835 dispatch_msg += ' ';
1837 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1839 bool argsadded = false;
1841 if (!cmd.argument().empty()) {
1842 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1843 comname += ' ' + cmd.argument();
1848 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1850 if (!shortcuts.empty())
1851 comname += ": " + shortcuts;
1852 else if (!argsadded && !cmd.argument().empty())
1853 comname += ' ' + cmd.argument();
1855 if (!comname.empty()) {
1856 comname = rtrim(comname);
1857 dispatch_msg += '(' + rtrim(comname) + ')';
1860 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1861 if (!dispatch_msg.empty())
1862 lyx_view_->message(dispatch_msg);
1866 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1868 lyx_view_->setBusy(true);
1870 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1873 lyx_view_->message(_("Document not loaded."));
1874 lyx_view_->setBusy(false);
1878 lyx_view_->setBuffer(newBuffer);
1880 // scroll to the position when the file was last closed
1881 if (lyxrc.use_lastfilepos) {
1882 LastFilePosSection::FilePos filepos =
1883 LyX::ref().session().lastFilePos().load(filename);
1884 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1888 LyX::ref().session().lastFiles().add(filename);
1890 lyx_view_->setBusy(false);
1895 void LyXFunc::open(string const & fname)
1897 string initpath = lyxrc.document_path;
1899 if (lyx_view_->buffer()) {
1900 string const trypath = lyx_view_->buffer()->filePath();
1901 // If directory is writeable, use this as default.
1902 if (FileName(trypath).isDirWritable())
1908 if (fname.empty()) {
1909 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
1910 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1911 dlg.setButton2(_("Examples|#E#e"),
1912 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1914 FileDialog::Result result =
1915 dlg.open(from_utf8(initpath),
1916 FileFilterList(_("LyX Documents (*.lyx)")),
1919 if (result.first == FileDialog::Later)
1922 filename = to_utf8(result.second);
1924 // check selected filename
1925 if (filename.empty()) {
1926 lyx_view_->message(_("Canceled."));
1932 // get absolute path of file and add ".lyx" to the filename if
1934 FileName const fullname = fileSearch(string(), filename, "lyx");
1935 if (!fullname.empty())
1936 filename = fullname.absFilename();
1938 // if the file doesn't exist, let the user create one
1939 if (!fullname.exists()) {
1940 // the user specifically chose this name. Believe him.
1941 Buffer * const b = newFile(filename, string(), true);
1943 lyx_view_->setBuffer(b);
1947 docstring const disp_fn = makeDisplayPath(filename);
1948 lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
1951 Buffer * buf = loadAndViewFile(fullname);
1954 lyx_view_->setBuffer(buf);
1955 buf->errors("Parse");
1956 str2 = bformat(_("Document %1$s opened."), disp_fn);
1958 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1960 lyx_view_->message(str2);
1964 void LyXFunc::doImport(string const & argument)
1967 string filename = split(argument, format, ' ');
1969 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
1970 << " file: " << filename);
1972 // need user interaction
1973 if (filename.empty()) {
1974 string initpath = lyxrc.document_path;
1976 if (lyx_view_->buffer()) {
1977 string const trypath = lyx_view_->buffer()->filePath();
1978 // If directory is writeable, use this as default.
1979 if (FileName(trypath).isDirWritable())
1983 docstring const text = bformat(_("Select %1$s file to import"),
1984 formats.prettyName(format));
1986 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
1987 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1988 dlg.setButton2(_("Examples|#E#e"),
1989 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1991 docstring filter = formats.prettyName(format);
1994 filter += from_utf8(formats.extension(format));
1997 FileDialog::Result result =
1998 dlg.open(from_utf8(initpath),
1999 FileFilterList(filter),
2002 if (result.first == FileDialog::Later)
2005 filename = to_utf8(result.second);
2007 // check selected filename
2008 if (filename.empty())
2009 lyx_view_->message(_("Canceled."));
2012 if (filename.empty())
2015 // get absolute path of file
2016 FileName const fullname(makeAbsPath(filename));
2018 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2020 // Check if the document already is open
2021 Buffer * buf = theBufferList().getBuffer(lyxfile.absFilename());
2022 if (use_gui && buf) {
2023 lyx_view_->setBuffer(buf);
2024 if (!lyx_view_->closeBuffer()) {
2025 lyx_view_->message(_("Canceled."));
2030 // if the file exists already, and we didn't do
2031 // -i lyx thefile.lyx, warn
2032 if (lyxfile.exists() && fullname != lyxfile) {
2033 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2035 docstring text = bformat(_("The document %1$s already exists.\n\n"
2036 "Do you want to overwrite that document?"), file);
2037 int const ret = Alert::prompt(_("Overwrite document?"),
2038 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2041 lyx_view_->message(_("Canceled."));
2046 ErrorList errorList;
2047 import(lyx_view_, fullname, format, errorList);
2048 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2052 void LyXFunc::closeBuffer()
2054 // goto bookmark to update bookmark pit.
2055 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2056 gotoBookmark(i+1, false, false);
2058 lyx_view_->closeBuffer();
2062 void LyXFunc::reloadBuffer()
2064 FileName filename = lyx_view_->buffer()->fileName();
2065 // The user has already confirmed that the changes, if any, should
2066 // be discarded. So we just release the Buffer and don't call closeBuffer();
2067 theBufferList().release(lyx_view_->buffer());
2068 Buffer * buf = loadAndViewFile(filename);
2069 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2073 lyx_view_->setBuffer(buf);
2074 buf->errors("Parse");
2075 str = bformat(_("Document %1$s reloaded."), disp_fn);
2077 str = bformat(_("Could not reload document %1$s"), disp_fn);
2079 lyx_view_->message(str);
2082 // Each "lyx_view_" should have it's own message method. lyxview and
2083 // the minibuffer would use the minibuffer, but lyxserver would
2084 // send an ERROR signal to its client. Alejandro 970603
2085 // This function is bit problematic when it comes to NLS, to make the
2086 // lyx servers client be language indepenent we must not translate
2087 // strings sent to this func.
2088 void LyXFunc::setErrorMessage(docstring const & m) const
2090 dispatch_buffer = m;
2095 void LyXFunc::setMessage(docstring const & m) const
2097 dispatch_buffer = m;
2101 docstring const LyXFunc::viewStatusMessage()
2103 // When meta-fake key is pressed, show the key sequence so far + "M-".
2105 return keyseq.print(KeySequence::ForGui) + "M-";
2107 // Else, when a non-complete key sequence is pressed,
2108 // show the available options.
2109 if (keyseq.length() > 0 && !keyseq.deleted())
2110 return keyseq.printOptions(true);
2112 BOOST_ASSERT(lyx_view_);
2113 if (!lyx_view_->buffer())
2114 return _("Welcome to LyX!");
2116 return view()->cursor().currentState();
2120 BufferView * LyXFunc::view() const
2122 BOOST_ASSERT(lyx_view_);
2123 return lyx_view_->view();
2127 bool LyXFunc::wasMetaKey() const
2129 return (meta_fake_bit != NoModifier);
2133 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2136 lyx_view_->message(_("Converting document to new document class..."));
2138 StableDocIterator backcur(view()->cursor());
2139 ErrorList & el = buffer->errorList("Class Switch");
2140 cap::switchBetweenClasses(
2141 oldlayout, buffer->params().getTextClassPtr(),
2142 static_cast<InsetText &>(buffer->inset()), el);
2144 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2146 buffer->errors("Class Switch");
2147 updateLabels(*buffer);
2153 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2155 // Why the switch you might ask. It is a trick to ensure that all
2156 // the elements in the LyXRCTags enum is handled. As you can see
2157 // there are no breaks at all. So it is just a huge fall-through.
2158 // The nice thing is that we will get a warning from the compiler
2159 // if we forget an element.
2160 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2162 case LyXRC::RC_ACCEPT_COMPOUND:
2163 case LyXRC::RC_ALT_LANG:
2164 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2165 case LyXRC::RC_PLAINTEXT_LINELEN:
2166 case LyXRC::RC_AUTOREGIONDELETE:
2167 case LyXRC::RC_AUTORESET_OPTIONS:
2168 case LyXRC::RC_AUTOSAVE:
2169 case LyXRC::RC_AUTO_NUMBER:
2170 case LyXRC::RC_BACKUPDIR_PATH:
2171 case LyXRC::RC_BIBTEX_COMMAND:
2172 case LyXRC::RC_BINDFILE:
2173 case LyXRC::RC_CHECKLASTFILES:
2174 case LyXRC::RC_USELASTFILEPOS:
2175 case LyXRC::RC_LOADSESSION:
2176 case LyXRC::RC_CHKTEX_COMMAND:
2177 case LyXRC::RC_CONVERTER:
2178 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2179 case LyXRC::RC_COPIER:
2180 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2181 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2182 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2183 case LyXRC::RC_DATE_INSERT_FORMAT:
2184 case LyXRC::RC_DEFAULT_LANGUAGE:
2185 case LyXRC::RC_DEFAULT_PAPERSIZE:
2186 case LyXRC::RC_DEFFILE:
2187 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2188 case LyXRC::RC_DISPLAY_GRAPHICS:
2189 case LyXRC::RC_DOCUMENTPATH:
2190 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2191 FileName path(lyxrc_new.document_path);
2192 if (path.exists() && path.isDirectory())
2193 package().document_dir() = FileName(lyxrc.document_path);
2195 case LyXRC::RC_ESC_CHARS:
2196 case LyXRC::RC_EXAMPLEPATH:
2197 case LyXRC::RC_FONT_ENCODING:
2198 case LyXRC::RC_FORMAT:
2199 case LyXRC::RC_INDEX_COMMAND:
2200 case LyXRC::RC_INPUT:
2201 case LyXRC::RC_KBMAP:
2202 case LyXRC::RC_KBMAP_PRIMARY:
2203 case LyXRC::RC_KBMAP_SECONDARY:
2204 case LyXRC::RC_LABEL_INIT_LENGTH:
2205 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2206 case LyXRC::RC_LANGUAGE_AUTO_END:
2207 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2208 case LyXRC::RC_LANGUAGE_COMMAND_END:
2209 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2210 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2211 case LyXRC::RC_LANGUAGE_PACKAGE:
2212 case LyXRC::RC_LANGUAGE_USE_BABEL:
2213 case LyXRC::RC_MAKE_BACKUP:
2214 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2215 case LyXRC::RC_NUMLASTFILES:
2216 case LyXRC::RC_PATH_PREFIX:
2217 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2218 prependEnvPath("PATH", lyxrc.path_prefix);
2220 case LyXRC::RC_PERS_DICT:
2221 case LyXRC::RC_PREVIEW:
2222 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2223 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2224 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2225 case LyXRC::RC_PRINTCOPIESFLAG:
2226 case LyXRC::RC_PRINTER:
2227 case LyXRC::RC_PRINTEVENPAGEFLAG:
2228 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2229 case LyXRC::RC_PRINTFILEEXTENSION:
2230 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2231 case LyXRC::RC_PRINTODDPAGEFLAG:
2232 case LyXRC::RC_PRINTPAGERANGEFLAG:
2233 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2234 case LyXRC::RC_PRINTPAPERFLAG:
2235 case LyXRC::RC_PRINTREVERSEFLAG:
2236 case LyXRC::RC_PRINTSPOOL_COMMAND:
2237 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2238 case LyXRC::RC_PRINTTOFILE:
2239 case LyXRC::RC_PRINTTOPRINTER:
2240 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2241 case LyXRC::RC_PRINT_COMMAND:
2242 case LyXRC::RC_RTL_SUPPORT:
2243 case LyXRC::RC_SCREEN_DPI:
2244 case LyXRC::RC_SCREEN_FONT_ROMAN:
2245 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2246 case LyXRC::RC_SCREEN_FONT_SANS:
2247 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2248 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2249 case LyXRC::RC_SCREEN_FONT_SIZES:
2250 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2251 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2252 case LyXRC::RC_GEOMETRY_SESSION:
2253 case LyXRC::RC_SCREEN_ZOOM:
2254 case LyXRC::RC_SERVERPIPE:
2255 case LyXRC::RC_SET_COLOR:
2256 case LyXRC::RC_SHOW_BANNER:
2257 case LyXRC::RC_SPELL_COMMAND:
2258 case LyXRC::RC_TEMPDIRPATH:
2259 case LyXRC::RC_TEMPLATEPATH:
2260 case LyXRC::RC_TEX_ALLOWS_SPACES:
2261 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2262 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2263 os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2265 case LyXRC::RC_UIFILE:
2266 case LyXRC::RC_USER_EMAIL:
2267 case LyXRC::RC_USER_NAME:
2268 case LyXRC::RC_USETEMPDIR:
2269 case LyXRC::RC_USE_ALT_LANG:
2270 case LyXRC::RC_USE_CONVERTER_CACHE:
2271 case LyXRC::RC_USE_ESC_CHARS:
2272 case LyXRC::RC_USE_INP_ENC:
2273 case LyXRC::RC_USE_PERS_DICT:
2274 case LyXRC::RC_USE_TOOLTIP:
2275 case LyXRC::RC_USE_PIXMAP_CACHE:
2276 case LyXRC::RC_USE_SPELL_LIB:
2277 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2278 case LyXRC::RC_SORT_LAYOUTS:
2279 case LyXRC::RC_VIEWER:
2280 case LyXRC::RC_LAST: