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"
102 using std::istringstream;
103 using std::ostringstream;
109 using frontend::LyXView;
111 using support::absolutePath;
112 using support::addName;
113 using support::addPath;
114 using support::bformat;
115 using support::changeExtension;
116 using support::contains;
117 using support::FileFilterList;
118 using support::FileName;
119 using support::fileSearch;
120 using support::i18nLibFileSearch;
121 using support::makeDisplayPath;
122 using support::makeAbsPath;
123 using support::package;
124 using support::quoteName;
125 using support::rtrim;
126 using support::split;
127 using support::subst;
128 using support::Systemcall;
129 using support::token;
131 using support::prefixIs;
134 namespace Alert = frontend::Alert;
136 extern bool quitting;
142 bool import(LyXView * lv, FileName const & filename,
143 string const & format, ErrorList & errorList)
145 docstring const displaypath = makeDisplayPath(filename.absFilename());
146 lv->message(bformat(_("Importing %1$s..."), displaypath));
148 FileName const lyxfile(changeExtension(filename.absFilename(), ".lyx"));
150 string loader_format;
151 vector<string> loaders = theConverters().loaders();
152 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
153 for (vector<string>::const_iterator it = loaders.begin();
154 it != loaders.end(); ++it) {
155 if (theConverters().isReachable(format, *it)) {
156 string const tofile =
157 changeExtension(filename.absFilename(),
158 formats.extension(*it));
159 if (!theConverters().convert(0, filename, FileName(tofile),
160 filename, format, *it, errorList))
166 if (loader_format.empty()) {
167 frontend::Alert::error(_("Couldn't import file"),
168 bformat(_("No information for importing the format %1$s."),
169 formats.prettyName(format)));
173 loader_format = format;
177 if (loader_format == "lyx") {
178 Buffer * buf = theLyXFunc().loadAndViewFile(lyxfile);
181 lv->message(_("file not imported!"));
186 buf->errors("Parse");
188 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
193 bool as_paragraphs = loader_format == "textparagraph";
194 string filename2 = (loader_format == format) ? filename.absFilename()
195 : changeExtension(filename.absFilename(),
196 formats.extension(loader_format));
197 lv->view()->insertPlaintextFile(filename2, as_paragraphs);
198 theLyXFunc().setLyXView(lv);
199 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
203 lv->message(_("imported."));
209 // This function runs "configure" and then rereads lyx.defaults to
210 // reconfigure the automatic settings.
211 void reconfigure(LyXView & lv, string const & option)
213 // emit message signal.
214 lv.message(_("Running configure..."));
216 // Run configure in user lyx directory
217 support::PathChanger p(package().user_support());
218 string configure_command = package().configure_command();
219 configure_command += option;
221 int ret = one.startscript(Systemcall::Wait, configure_command);
223 // emit message signal.
224 lv.message(_("Reloading configuration..."));
225 lyxrc.read(support::libFileSearch(string(), "lyxrc.defaults"));
226 // Re-read packages.lst
227 LaTeXFeatures::getAvailable();
230 Alert::information(_("System reconfiguration failed"),
231 _("The system reconfiguration has failed.\n"
232 "Default textclass is used but LyX may "
233 "not be able to work properly.\n"
234 "Please reconfigure again if needed."));
237 Alert::information(_("System reconfigured"),
238 _("The system has been reconfigured.\n"
239 "You need to restart LyX to make use of any\n"
240 "updated document class specifications."));
244 bool getLocalStatus(Cursor cursor, FuncRequest const & cmd, FuncStatus & status)
246 // Try to fix cursor in case it is broken.
247 cursor.fixIfBroken();
249 // This is, of course, a mess. Better create a new doc iterator and use
250 // this in Inset::getStatus. This might require an additional
251 // BufferView * arg, though (which should be avoided)
252 //Cursor safe = *this;
254 for ( ; cursor.depth(); cursor.pop()) {
255 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
256 BOOST_ASSERT(cursor.idx() <= cursor.lastidx());
257 BOOST_ASSERT(cursor.pit() <= cursor.lastpit());
258 BOOST_ASSERT(cursor.pos() <= cursor.lastpos());
260 // The inset's getStatus() will return 'true' if it made
261 // a definitive decision on whether it want to handle the
262 // request or not. The result of this decision is put into
263 // the 'status' parameter.
264 if (cursor.inset().getStatus(cursor, cmd, status)) {
273 /** Return the change status at cursor position, taking in account the
274 * status at each level of the document iterator (a table in a deleted
275 * footnote is deleted).
276 * When \param outer is true, the top slice is not looked at.
278 Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
280 size_t const depth = dit.depth() - (outer ? 1 : 0);
282 for (size_t i = 0 ; i < depth ; ++i) {
283 CursorSlice const & slice = dit[i];
284 if (!slice.inset().inMathed()
285 && slice.pos() < slice.paragraph().size()) {
286 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
287 if (ch != Change::UNCHANGED)
291 return Change::UNCHANGED;
298 : lyx_view_(0), encoded_last_key(0), meta_fake_bit(NoModifier)
303 void LyXFunc::initKeySequences(KeyMap * kb)
305 keyseq = KeySequence(kb, kb);
306 cancel_meta_seq = KeySequence(kb, kb);
310 void LyXFunc::setLyXView(LyXView * lv)
312 if (!quitting && lyx_view_ && lyx_view_->view() && lyx_view_ != lv)
313 // save current selection to the selection buffer to allow
314 // middle-button paste in another window
315 cap::saveSelection(lyx_view_->view()->cursor());
320 void LyXFunc::handleKeyFunc(kb_action action)
322 char_type c = encoded_last_key;
327 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
328 lyx_view_->view()->getIntl().getTransManager().deadkey(
329 c, get_accent(action).accent, view()->cursor().innerText(), view()->cursor());
330 // Need to clear, in case the minibuffer calls these
333 // copied verbatim from do_accent_char
334 view()->cursor().resetAnchor();
335 view()->processUpdateFlags(Update::FitCursor);
339 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
341 BOOST_ASSERT(lyx_view_);
342 if (!LyX::ref().session().bookmarks().isValid(idx))
344 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(idx);
345 BOOST_ASSERT(!bm.filename.empty());
346 string const file = bm.filename.absFilename();
347 // if the file is not opened, open it.
348 if (!theBufferList().exists(file)) {
350 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
354 // open may fail, so we need to test it again
355 if (!theBufferList().exists(file))
358 // if the current buffer is not that one, switch to it.
359 if (lyx_view_->buffer()->absFileName() != file) {
362 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
364 // moveToPosition try paragraph id first and then paragraph (pit, pos).
365 if (!view()->moveToPosition(bm.bottom_pit, bm.bottom_pos,
366 bm.top_id, bm.top_pos))
369 // Cursor jump succeeded!
370 Cursor const & cur = view()->cursor();
371 pit_type new_pit = cur.pit();
372 pos_type new_pos = cur.pos();
373 int new_id = cur.paragraph().id();
375 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
376 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
377 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
378 || bm.top_id != new_id) {
379 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
380 new_pit, new_pos, new_id);
385 void LyXFunc::processKeySym(KeySymbol const & keysym, KeyModifier state)
387 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
389 // Do nothing if we have nothing (JMarc)
390 if (!keysym.isOK()) {
391 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
392 lyx_view_->restartCursor();
396 if (keysym.isModifier()) {
397 LYXERR(Debug::KEY, "isModifier true");
398 lyx_view_->restartCursor();
402 //Encoding const * encoding = view()->cursor().getEncoding();
403 //encoded_last_key = keysym.getISOEncoded(encoding ? encoding->name() : "");
404 // FIXME: encoded_last_key shadows the member variable of the same
405 // name. Is that intended?
406 char_type encoded_last_key = keysym.getUCSEncoded();
408 // Do a one-deep top-level lookup for
409 // cancel and meta-fake keys. RVDK_PATCH_5
410 cancel_meta_seq.reset();
412 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
413 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
415 // When not cancel or meta-fake, do the normal lookup.
416 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
417 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
418 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
419 // remove Caps Lock and Mod2 as a modifiers
420 func = keyseq.addkey(keysym, (state | meta_fake_bit));
421 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
424 // Dont remove this unless you know what you are doing.
425 meta_fake_bit = NoModifier;
427 // Can this happen now ?
428 if (func.action == LFUN_NOACTION)
429 func = FuncRequest(LFUN_COMMAND_PREFIX);
431 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
432 << keyseq.print(KeySequence::Portable) << ']');
434 // already here we know if it any point in going further
435 // why not return already here if action == -1 and
436 // num_bytes == 0? (Lgb)
438 if (keyseq.length() > 1)
439 lyx_view_->message(keyseq.print(KeySequence::ForGui));
442 // Maybe user can only reach the key via holding down shift.
443 // Let's see. But only if shift is the only modifier
444 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
445 LYXERR(Debug::KEY, "Trying without shift");
446 func = keyseq.addkey(keysym, NoModifier);
447 LYXERR(Debug::KEY, "Action now " << func.action);
450 if (func.action == LFUN_UNKNOWN_ACTION) {
451 // Hmm, we didn't match any of the keysequences. See
452 // if it's normal insertable text not already covered
454 if (keysym.isText() && keyseq.length() == 1) {
455 LYXERR(Debug::KEY, "isText() is true, inserting.");
456 func = FuncRequest(LFUN_SELF_INSERT,
457 FuncRequest::KEYBOARD);
459 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
460 lyx_view_->message(_("Unknown function."));
461 lyx_view_->restartCursor();
466 if (func.action == LFUN_SELF_INSERT) {
467 if (encoded_last_key != 0) {
468 docstring const arg(1, encoded_last_key);
469 dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
470 FuncRequest::KEYBOARD));
471 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
477 lyx_view_->restartCursor();
481 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
483 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
486 Buffer * buf = lyx_view_? lyx_view_->buffer() : 0;
488 if (cmd.action == LFUN_NOACTION) {
489 flag.message(from_utf8(N_("Nothing to do")));
494 switch (cmd.action) {
495 case LFUN_UNKNOWN_ACTION:
496 #ifndef HAVE_LIBAIKSAURUS
497 case LFUN_THESAURUS_ENTRY:
507 if (flag.unknown()) {
508 flag.message(from_utf8(N_("Unknown action")));
512 if (!flag.enabled()) {
513 if (flag.message().empty())
514 flag.message(from_utf8(N_("Command disabled")));
518 // Check whether we need a buffer
519 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
521 flag.message(from_utf8(N_("Command not allowed with"
522 "out any document open")));
527 // I would really like to avoid having this switch and rather try to
528 // encode this in the function itself.
529 // -- And I'd rather let an inset decide which LFUNs it is willing
530 // to handle (Andre')
532 switch (cmd.action) {
534 case LFUN_WINDOW_CLOSE:
536 return theApp()->getStatus(cmd);
540 case LFUN_DIALOG_TOGGLE:
541 case LFUN_DIALOG_SHOW:
542 case LFUN_DIALOG_UPDATE:
543 case LFUN_TOOLBAR_TOGGLE:
544 case LFUN_INSET_APPLY:
546 return lyx_view_->getStatus(cmd);
550 case LFUN_BUFFER_TOGGLE_READ_ONLY:
551 flag.setOnOff(buf->isReadonly());
554 case LFUN_BUFFER_SWITCH:
555 // toggle on the current buffer, but do not toggle off
556 // the other ones (is that a good idea?)
557 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
561 case LFUN_BUFFER_EXPORT:
562 enable = cmd.argument() == "custom"
563 || buf->isExportable(to_utf8(cmd.argument()));
566 case LFUN_BUFFER_CHKTEX:
567 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
570 case LFUN_BUILD_PROGRAM:
571 enable = buf->isExportable("program");
574 case LFUN_VC_REGISTER:
575 enable = !buf->lyxvc().inUse();
577 case LFUN_VC_CHECK_IN:
578 enable = buf->lyxvc().inUse() && !buf->isReadonly();
580 case LFUN_VC_CHECK_OUT:
581 enable = buf->lyxvc().inUse() && buf->isReadonly();
584 case LFUN_VC_UNDO_LAST:
585 enable = buf->lyxvc().inUse();
587 case LFUN_BUFFER_RELOAD:
588 enable = !buf->isUnnamed() && buf->fileName().exists()
589 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
592 case LFUN_CITATION_INSERT: {
593 FuncRequest fr(LFUN_INSET_INSERT, "citation");
594 enable = getStatus(fr).enabled();
598 case LFUN_BUFFER_WRITE: {
599 enable = lyx_view_->buffer()->isUnnamed()
600 || !lyx_view_->buffer()->isClean();
605 case LFUN_BUFFER_WRITE_ALL: {
606 // We enable the command only if there are some modified buffers
607 Buffer * first = theBufferList().first();
608 bool modified = false;
612 // We cannot use a for loop as the buffer list is a cycle.
618 b = theBufferList().next(b);
619 } while (b != first);
627 case LFUN_BOOKMARK_GOTO: {
628 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
629 enable = LyX::ref().session().bookmarks().isValid(num);
633 case LFUN_BOOKMARK_CLEAR:
634 enable = LyX::ref().session().bookmarks().size() > 0;
637 // this one is difficult to get right. As a half-baked
638 // solution, we consider only the first action of the sequence
639 case LFUN_COMMAND_SEQUENCE: {
640 // argument contains ';'-terminated commands
641 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
642 FuncRequest func(lyxaction.lookupFunc(firstcmd));
643 func.origin = cmd.origin;
644 flag = getStatus(func);
650 std::string name = to_utf8(cmd.argument());
651 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
652 func.origin = cmd.origin;
653 flag = getStatus(func);
654 LyX::ref().topLevelCmdDef().release(name);
656 // catch recursion or unknown command definiton
657 // all operations until the recursion or unknown command
658 // definiton occures are performed, so set the state to enabled
664 case LFUN_BUFFER_NEW:
665 case LFUN_BUFFER_NEW_TEMPLATE:
666 case LFUN_WORD_FIND_FORWARD:
667 case LFUN_WORD_FIND_BACKWARD:
668 case LFUN_COMMAND_PREFIX:
669 case LFUN_COMMAND_EXECUTE:
671 case LFUN_META_PREFIX:
672 case LFUN_BUFFER_CLOSE:
673 case LFUN_BUFFER_WRITE_AS:
674 case LFUN_BUFFER_UPDATE:
675 case LFUN_BUFFER_VIEW:
676 case LFUN_MASTER_BUFFER_UPDATE:
677 case LFUN_MASTER_BUFFER_VIEW:
678 case LFUN_BUFFER_IMPORT:
679 case LFUN_BUFFER_AUTO_SAVE:
680 case LFUN_RECONFIGURE:
684 case LFUN_DROP_LAYOUTS_CHOICE:
686 case LFUN_SERVER_GET_NAME:
687 case LFUN_SERVER_NOTIFY:
688 case LFUN_SERVER_GOTO_FILE_ROW:
689 case LFUN_DIALOG_HIDE:
690 case LFUN_DIALOG_DISCONNECT_INSET:
691 case LFUN_BUFFER_CHILD_OPEN:
692 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
693 case LFUN_KEYMAP_OFF:
694 case LFUN_KEYMAP_PRIMARY:
695 case LFUN_KEYMAP_SECONDARY:
696 case LFUN_KEYMAP_TOGGLE:
698 case LFUN_BUFFER_EXPORT_CUSTOM:
699 case LFUN_BUFFER_PRINT:
700 case LFUN_PREFERENCES_SAVE:
701 case LFUN_SCREEN_FONT_UPDATE:
704 case LFUN_EXTERNAL_EDIT:
705 case LFUN_GRAPHICS_EDIT:
706 case LFUN_ALL_INSETS_TOGGLE:
707 case LFUN_BUFFER_LANGUAGE:
708 case LFUN_TEXTCLASS_APPLY:
709 case LFUN_TEXTCLASS_LOAD:
710 case LFUN_BUFFER_SAVE_AS_DEFAULT:
711 case LFUN_BUFFER_PARAMS_APPLY:
712 case LFUN_LAYOUT_MODULES_CLEAR:
713 case LFUN_LAYOUT_MODULE_ADD:
714 case LFUN_LAYOUT_RELOAD:
715 case LFUN_LYXRC_APPLY:
716 case LFUN_BUFFER_NEXT:
717 case LFUN_BUFFER_PREVIOUS:
718 case LFUN_WINDOW_NEW:
720 // these are handled in our dispatch()
728 if (!getLocalStatus(view()->cursor(), cmd, flag))
729 flag = view()->getStatus(cmd);
735 // Can we use a readonly buffer?
736 if (buf && buf->isReadonly()
737 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
738 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
739 flag.message(from_utf8(N_("Document is read-only")));
743 // Are we in a DELETED change-tracking region?
745 && lookupChangeType(view()->cursor(), true) == Change::DELETED
746 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
747 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
748 flag.message(from_utf8(N_("This portion of the document is deleted.")));
752 // the default error message if we disable the command
753 if (!flag.enabled() && flag.message().empty())
754 flag.message(from_utf8(N_("Command disabled")));
760 bool LyXFunc::ensureBufferClean(BufferView * bv)
762 Buffer & buf = bv->buffer();
766 docstring const file = buf.fileName().displayName(30);
767 docstring text = bformat(_("The document %1$s has unsaved "
768 "changes.\n\nDo you want to save "
769 "the document?"), file);
770 int const ret = Alert::prompt(_("Save changed document?"),
771 text, 0, 1, _("&Save"),
775 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
777 return buf.isClean();
783 void showPrintError(string const & name)
785 docstring str = bformat(_("Could not print the document %1$s.\n"
786 "Check that your printer is set up correctly."),
787 makeDisplayPath(name, 50));
788 Alert::error(_("Print document failed"), str);
792 void loadTextClass(string const & name)
794 std::pair<bool, textclass_type> const tc_pair =
795 textclasslist.numberOfClass(name);
797 if (!tc_pair.first) {
798 lyxerr << "Document class \"" << name
799 << "\" does not exist."
804 textclass_type const tc = tc_pair.second;
806 if (!textclasslist[tc].load()) {
807 docstring s = bformat(_("The document class %1$s."
808 "could not be loaded."),
809 from_utf8(textclasslist[tc].name()));
810 Alert::error(_("Could not load class"), s);
815 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
820 void LyXFunc::dispatch(FuncRequest const & cmd)
822 string const argument = to_utf8(cmd.argument());
823 kb_action const action = cmd.action;
825 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
826 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
828 // we have not done anything wrong yet.
830 dispatch_buffer.erase();
832 // redraw the screen at the end (first of the two drawing steps).
833 //This is done unless explicitely requested otherwise
834 Update::flags updateFlags = Update::FitCursor;
836 FuncStatus const flag = getStatus(cmd);
837 if (!flag.enabled()) {
838 // We cannot use this function here
839 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
840 << lyxaction.getActionName(action)
841 << " [" << action << "] is disabled at this location");
842 setErrorMessage(flag.message());
846 case LFUN_WORD_FIND_FORWARD:
847 case LFUN_WORD_FIND_BACKWARD: {
848 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
849 static docstring last_search;
850 docstring searched_string;
852 if (!cmd.argument().empty()) {
853 last_search = cmd.argument();
854 searched_string = cmd.argument();
856 searched_string = last_search;
859 if (searched_string.empty())
862 bool const fw = action == LFUN_WORD_FIND_FORWARD;
863 docstring const data =
864 find2string(searched_string, true, false, fw);
865 find(view(), FuncRequest(LFUN_WORD_FIND, data));
869 case LFUN_COMMAND_PREFIX:
870 BOOST_ASSERT(lyx_view_);
871 lyx_view_->message(keyseq.printOptions(true));
875 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
877 meta_fake_bit = NoModifier;
878 if (lyx_view_->buffer())
879 // cancel any selection
880 dispatch(FuncRequest(LFUN_MARK_OFF));
881 setMessage(from_ascii(N_("Cancel")));
884 case LFUN_META_PREFIX:
885 meta_fake_bit = AltModifier;
886 setMessage(keyseq.print(KeySequence::ForGui));
889 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
890 BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
891 Buffer * buf = lyx_view_->buffer();
892 if (buf->lyxvc().inUse())
893 buf->lyxvc().toggleReadOnly();
895 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
899 // --- Menus -----------------------------------------------
900 case LFUN_BUFFER_NEW:
901 menuNew(argument, false);
902 updateFlags = Update::None;
905 case LFUN_BUFFER_NEW_TEMPLATE:
906 menuNew(argument, true);
907 updateFlags = Update::None;
910 case LFUN_BUFFER_CLOSE:
912 updateFlags = Update::None;
915 case LFUN_BUFFER_WRITE:
916 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
917 if (!lyx_view_->buffer()->isUnnamed()) {
918 docstring const str = bformat(_("Saving document %1$s..."),
919 makeDisplayPath(lyx_view_->buffer()->absFileName()));
920 lyx_view_->message(str);
921 lyx_view_->buffer()->menuWrite();
922 lyx_view_->message(str + _(" done."));
924 lyx_view_->buffer()->writeAs();
926 updateFlags = Update::None;
929 case LFUN_BUFFER_WRITE_AS:
930 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
931 lyx_view_->buffer()->writeAs(argument);
932 updateFlags = Update::None;
935 case LFUN_BUFFER_WRITE_ALL: {
936 Buffer * first = theBufferList().first();
939 lyx_view_->message(_("Saving all documents..."));
941 // We cannot use a for loop as the buffer list cycles.
944 if (!b->isUnnamed()) {
946 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
950 b = theBufferList().next(b);
951 } while (b != first);
952 lyx_view_->message(_("All documents saved."));
955 updateFlags = Update::None;
959 case LFUN_BUFFER_RELOAD: {
960 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
961 docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
962 docstring text = bformat(_("Any changes will be lost. Are you sure "
963 "you want to revert to the saved version of the document %1$s?"), file);
964 int const ret = Alert::prompt(_("Revert to saved document?"),
965 text, 1, 1, _("&Revert"), _("&Cancel"));
972 case LFUN_BUFFER_UPDATE:
973 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
974 lyx_view_->buffer()->doExport(argument, true);
977 case LFUN_BUFFER_VIEW:
978 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
979 lyx_view_->buffer()->preview(argument);
982 case LFUN_MASTER_BUFFER_UPDATE:
983 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
984 lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
987 case LFUN_MASTER_BUFFER_VIEW:
988 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
989 lyx_view_->buffer()->masterBuffer()->preview(argument);
992 case LFUN_BUILD_PROGRAM:
993 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
994 lyx_view_->buffer()->doExport("program", true);
997 case LFUN_BUFFER_CHKTEX:
998 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
999 lyx_view_->buffer()->runChktex();
1002 case LFUN_BUFFER_EXPORT:
1003 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1004 if (argument == "custom")
1005 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
1007 lyx_view_->buffer()->doExport(argument, false);
1010 case LFUN_BUFFER_EXPORT_CUSTOM: {
1011 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1013 string command = split(argument, format_name, ' ');
1014 Format const * format = formats.getFormat(format_name);
1016 lyxerr << "Format \"" << format_name
1017 << "\" not recognized!"
1022 Buffer * buffer = lyx_view_->buffer();
1024 // The name of the file created by the conversion process
1027 // Output to filename
1028 if (format->name() == "lyx") {
1029 string const latexname = buffer->latexName(false);
1030 filename = changeExtension(latexname,
1031 format->extension());
1032 filename = addName(buffer->temppath(), filename);
1034 if (!buffer->writeFile(FileName(filename)))
1038 buffer->doExport(format_name, true, filename);
1041 // Substitute $$FName for filename
1042 if (!contains(command, "$$FName"))
1043 command = "( " + command + " ) < $$FName";
1044 command = subst(command, "$$FName", filename);
1046 // Execute the command in the background
1048 call.startscript(Systemcall::DontWait, command);
1052 case LFUN_BUFFER_PRINT: {
1053 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1054 // FIXME: cmd.getArg() might fail if one of the arguments
1055 // contains double quotes
1056 string target = cmd.getArg(0);
1057 string target_name = cmd.getArg(1);
1058 string command = cmd.getArg(2);
1061 || target_name.empty()
1062 || command.empty()) {
1063 lyxerr << "Unable to parse \""
1064 << argument << '"' << endl;
1067 if (target != "printer" && target != "file") {
1068 lyxerr << "Unrecognized target \""
1069 << target << '"' << endl;
1073 Buffer * buffer = lyx_view_->buffer();
1075 if (!buffer->doExport("dvi", true)) {
1076 showPrintError(buffer->absFileName());
1080 // Push directory path.
1081 string const path = buffer->temppath();
1082 // Prevent the compiler from optimizing away p
1084 support::PathChanger p(pp);
1086 // there are three cases here:
1087 // 1. we print to a file
1088 // 2. we print directly to a printer
1089 // 3. we print using a spool command (print to file first)
1092 string const dviname =
1093 changeExtension(buffer->latexName(true), "dvi");
1095 if (target == "printer") {
1096 if (!lyxrc.print_spool_command.empty()) {
1097 // case 3: print using a spool
1098 string const psname =
1099 changeExtension(dviname,".ps");
1100 command += ' ' + lyxrc.print_to_file
1103 + quoteName(dviname);
1106 lyxrc.print_spool_command + ' ';
1107 if (target_name != "default") {
1108 command2 += lyxrc.print_spool_printerprefix
1112 command2 += quoteName(psname);
1114 // If successful, then spool command
1115 res = one.startscript(
1120 res = one.startscript(
1121 Systemcall::DontWait,
1124 // case 2: print directly to a printer
1125 if (target_name != "default")
1126 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1127 res = one.startscript(
1128 Systemcall::DontWait,
1129 command + quoteName(dviname));
1133 // case 1: print to a file
1134 FileName const filename(makeAbsPath(target_name,
1135 lyx_view_->buffer()->filePath()));
1136 FileName const dvifile(makeAbsPath(dviname, path));
1137 if (filename.exists()) {
1138 docstring text = bformat(
1139 _("The file %1$s already exists.\n\n"
1140 "Do you want to overwrite that file?"),
1141 makeDisplayPath(filename.absFilename()));
1142 if (Alert::prompt(_("Overwrite file?"),
1143 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1146 command += ' ' + lyxrc.print_to_file
1147 + quoteName(filename.toFilesystemEncoding())
1149 + quoteName(dvifile.toFilesystemEncoding());
1150 res = one.startscript(Systemcall::DontWait,
1155 showPrintError(buffer->absFileName());
1159 case LFUN_BUFFER_IMPORT:
1163 case LFUN_BUFFER_AUTO_SAVE:
1164 lyx_view_->buffer()->autoSave();
1167 case LFUN_RECONFIGURE:
1168 BOOST_ASSERT(lyx_view_);
1169 // argument is any additional parameter to the configure.py command
1170 reconfigure(*lyx_view_, argument);
1173 case LFUN_HELP_OPEN: {
1174 BOOST_ASSERT(lyx_view_);
1175 string const arg = argument;
1177 setErrorMessage(from_ascii(N_("Missing argument")));
1180 FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1181 if (fname.empty()) {
1182 lyxerr << "LyX: unable to find documentation file `"
1183 << arg << "'. Bad installation?" << endl;
1186 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1187 makeDisplayPath(fname.absFilename())));
1188 Buffer * buf = loadAndViewFile(fname, false);
1191 lyx_view_->setBuffer(buf);
1192 buf->errors("Parse");
1194 updateFlags = Update::None;
1198 // --- version control -------------------------------
1199 case LFUN_VC_REGISTER:
1200 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1201 if (!ensureBufferClean(view()))
1203 if (!lyx_view_->buffer()->lyxvc().inUse()) {
1204 lyx_view_->buffer()->lyxvc().registrer();
1207 updateFlags = Update::Force;
1210 case LFUN_VC_CHECK_IN:
1211 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1212 if (!ensureBufferClean(view()))
1214 if (lyx_view_->buffer()->lyxvc().inUse()
1215 && !lyx_view_->buffer()->isReadonly()) {
1216 lyx_view_->buffer()->lyxvc().checkIn();
1221 case LFUN_VC_CHECK_OUT:
1222 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1223 if (!ensureBufferClean(view()))
1225 if (lyx_view_->buffer()->lyxvc().inUse()
1226 && lyx_view_->buffer()->isReadonly()) {
1227 lyx_view_->buffer()->lyxvc().checkOut();
1232 case LFUN_VC_REVERT:
1233 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1234 lyx_view_->buffer()->lyxvc().revert();
1238 case LFUN_VC_UNDO_LAST:
1239 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1240 lyx_view_->buffer()->lyxvc().undoLast();
1244 // --- buffers ----------------------------------------
1246 case LFUN_FILE_NEW: {
1247 BOOST_ASSERT(lyx_view_);
1249 string tmpname = split(argument, name, ':'); // Split filename
1250 Buffer * const b = newFile(name, tmpname);
1252 lyx_view_->setBuffer(b);
1253 updateFlags = Update::None;
1257 case LFUN_FILE_OPEN:
1258 BOOST_ASSERT(lyx_view_);
1260 updateFlags = Update::None;
1263 // --- lyxserver commands ----------------------------
1264 case LFUN_SERVER_GET_NAME:
1265 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1266 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1267 LYXERR(Debug::INFO, "FNAME["
1268 << lyx_view_->buffer()->absFileName() << ']');
1271 case LFUN_SERVER_NOTIFY:
1272 dispatch_buffer = keyseq.print(KeySequence::Portable);
1273 theServer().notifyClient(to_utf8(dispatch_buffer));
1276 case LFUN_SERVER_GOTO_FILE_ROW: {
1277 BOOST_ASSERT(lyx_view_);
1280 istringstream is(argument);
1281 is >> file_name >> row;
1283 bool loaded = false;
1284 if (prefixIs(file_name, package().temp_dir().absFilename()))
1285 // Needed by inverse dvi search. If it is a file
1286 // in tmpdir, call the apropriated function
1287 buf = theBufferList().getBufferFromTmp(file_name);
1289 // Must replace extension of the file to be .lyx
1290 // and get full path
1291 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1292 // Either change buffer or load the file
1293 if (theBufferList().exists(s.absFilename()))
1294 buf = theBufferList().getBuffer(s.absFilename());
1296 buf = loadAndViewFile(s);
1302 updateFlags = Update::None;
1307 lyx_view_->setBuffer(buf);
1308 view()->setCursorFromRow(row);
1310 buf->errors("Parse");
1311 updateFlags = Update::FitCursor;
1316 case LFUN_DIALOG_SHOW_NEW_INSET: {
1317 BOOST_ASSERT(lyx_view_);
1318 string const name = cmd.getArg(0);
1319 InsetCode code = insetCode(name);
1320 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1321 bool insetCodeOK = true;
1330 case HYPERLINK_CODE: {
1331 InsetCommandParams p(code);
1332 data = InsetCommandMailer::params2string(name, p);
1335 case INCLUDE_CODE: {
1336 // data is the include type: one of "include",
1337 // "input", "verbatiminput" or "verbatiminput*"
1339 // default type is requested
1341 InsetCommandParams p(INCLUDE_CODE, data);
1342 data = InsetCommandMailer::params2string("include", p);
1346 // \c data == "Boxed" || "Frameless" etc
1347 InsetBoxParams p(data);
1348 data = InsetBoxMailer::params2string(p);
1352 InsetBranchParams p;
1353 data = InsetBranchMailer::params2string(p);
1357 InsetCommandParams p(CITE_CODE);
1358 data = InsetCommandMailer::params2string(name, p);
1362 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1365 case EXTERNAL_CODE: {
1366 InsetExternalParams p;
1367 Buffer const & buffer = *lyx_view_->buffer();
1368 data = InsetExternalMailer::params2string(p, buffer);
1373 data = InsetFloatMailer::params2string(p);
1376 case LISTINGS_CODE: {
1377 InsetListingsParams p;
1378 data = InsetListingsMailer::params2string(p);
1381 case GRAPHICS_CODE: {
1382 InsetGraphicsParams p;
1383 Buffer const & buffer = *lyx_view_->buffer();
1384 data = InsetGraphicsMailer::params2string(p, buffer);
1389 data = InsetNoteMailer::params2string(p);
1394 data = InsetVSpaceMailer::params2string(space);
1399 data = InsetWrapMailer::params2string(p);
1403 lyxerr << "Inset type '" << name <<
1404 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << std:: endl;
1405 insetCodeOK = false;
1407 } // end switch(code)
1409 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1413 case LFUN_CITATION_INSERT: {
1414 BOOST_ASSERT(lyx_view_);
1415 if (!argument.empty()) {
1416 // we can have one optional argument, delimited by '|'
1417 // citation-insert <key>|<text_before>
1418 // this should be enhanced to also support text_after
1419 // and citation style
1420 string arg = argument;
1422 if (contains(argument, "|")) {
1423 arg = token(argument, '|', 0);
1424 opt1 = token(argument, '|', 1);
1426 InsetCommandParams icp(CITE_CODE);
1427 icp["key"] = from_utf8(arg);
1429 icp["before"] = from_utf8(opt1);
1430 string icstr = InsetCommandMailer::params2string("citation", icp);
1431 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1434 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1438 case LFUN_BUFFER_CHILD_OPEN: {
1439 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1440 Buffer * parent = lyx_view_->buffer();
1441 FileName filename = makeAbsPath(argument, parent->filePath());
1442 view()->saveBookmark(false);
1444 bool parsed = false;
1445 if (theBufferList().exists(filename.absFilename())) {
1446 child = theBufferList().getBuffer(filename.absFilename());
1448 setMessage(bformat(_("Opening child document %1$s..."),
1449 makeDisplayPath(filename.absFilename())));
1450 child = loadAndViewFile(filename, true);
1454 // Set the parent name of the child document.
1455 // This makes insertion of citations and references in the child work,
1456 // when the target is in the parent or another child document.
1457 child->setParentName(parent->absFileName());
1458 updateLabels(*child->masterBuffer());
1459 lyx_view_->setBuffer(child);
1461 child->errors("Parse");
1464 // If a screen update is required (in case where auto_open is false),
1465 // setBuffer() would have taken care of it already. Otherwise we shall
1466 // reset the update flag because it can cause a circular problem.
1468 updateFlags = Update::None;
1472 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1473 BOOST_ASSERT(lyx_view_);
1474 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1477 case LFUN_KEYMAP_OFF:
1478 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1479 lyx_view_->view()->getIntl().keyMapOn(false);
1482 case LFUN_KEYMAP_PRIMARY:
1483 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1484 lyx_view_->view()->getIntl().keyMapPrim();
1487 case LFUN_KEYMAP_SECONDARY:
1488 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1489 lyx_view_->view()->getIntl().keyMapSec();
1492 case LFUN_KEYMAP_TOGGLE:
1493 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1494 lyx_view_->view()->getIntl().toggleKeyMap();
1500 string rest = split(argument, countstr, ' ');
1501 istringstream is(countstr);
1504 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1505 for (int i = 0; i < count; ++i)
1506 dispatch(lyxaction.lookupFunc(rest));
1510 case LFUN_COMMAND_SEQUENCE: {
1511 // argument contains ';'-terminated commands
1512 string arg = argument;
1513 while (!arg.empty()) {
1515 arg = split(arg, first, ';');
1516 FuncRequest func(lyxaction.lookupFunc(first));
1517 func.origin = cmd.origin;
1525 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1526 func.origin = cmd.origin;
1528 LyX::ref().topLevelCmdDef().release(argument);
1530 if (func.action == LFUN_UNKNOWN_ACTION) {
1531 // unknown command definition
1532 lyxerr << "Warning: unknown command definition `"
1536 // recursion detected
1537 lyxerr << "Warning: Recursion in the command definition `"
1538 << argument << "' detected"
1545 case LFUN_PREFERENCES_SAVE: {
1546 lyxrc.write(makeAbsPath("preferences",
1547 package().user_support().absFilename()),
1552 case LFUN_SET_COLOR: {
1554 string const x11_name = split(argument, lyx_name, ' ');
1555 if (lyx_name.empty() || x11_name.empty()) {
1556 setErrorMessage(from_ascii(N_(
1557 "Syntax: set-color <lyx_name>"
1562 bool const graphicsbg_changed =
1563 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1564 x11_name != lcolor.getX11Name(Color_graphicsbg));
1566 if (!lcolor.setColor(lyx_name, x11_name)) {
1568 bformat(_("Set-color \"%1$s\" failed "
1569 "- color is undefined or "
1570 "may not be redefined"),
1571 from_utf8(lyx_name)));
1575 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1577 if (graphicsbg_changed) {
1578 // FIXME: The graphics cache no longer has a changeDisplay method.
1580 graphics::GCache::get().changeDisplay(true);
1587 BOOST_ASSERT(lyx_view_);
1588 lyx_view_->message(from_utf8(argument));
1591 case LFUN_EXTERNAL_EDIT: {
1592 BOOST_ASSERT(lyx_view_);
1593 FuncRequest fr(action, argument);
1594 InsetExternal().dispatch(view()->cursor(), fr);
1598 case LFUN_GRAPHICS_EDIT: {
1599 FuncRequest fr(action, argument);
1600 InsetGraphics().dispatch(view()->cursor(), fr);
1604 case LFUN_ALL_INSETS_TOGGLE: {
1605 BOOST_ASSERT(lyx_view_);
1607 string const name = split(argument, action, ' ');
1608 InsetCode const inset_code = insetCode(name);
1610 Cursor & cur = view()->cursor();
1611 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1613 Inset & inset = lyx_view_->buffer()->inset();
1614 InsetIterator it = inset_iterator_begin(inset);
1615 InsetIterator const end = inset_iterator_end(inset);
1616 for (; it != end; ++it) {
1617 if (!it->asInsetMath()
1618 && (inset_code == NO_CODE
1619 || inset_code == it->lyxCode())) {
1620 Cursor tmpcur = cur;
1621 tmpcur.pushBackward(*it);
1622 it->dispatch(tmpcur, fr);
1625 updateFlags = Update::Force | Update::FitCursor;
1629 case LFUN_BUFFER_LANGUAGE: {
1630 BOOST_ASSERT(lyx_view_);
1631 Buffer & buffer = *lyx_view_->buffer();
1632 Language const * oldL = buffer.params().language;
1633 Language const * newL = languages.getLanguage(argument);
1634 if (!newL || oldL == newL)
1637 if (oldL->rightToLeft() == newL->rightToLeft()
1638 && !buffer.isMultiLingual())
1639 buffer.changeLanguage(oldL, newL);
1643 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1644 string const fname =
1645 addName(addPath(package().user_support().absFilename(), "templates/"),
1647 Buffer defaults(fname);
1649 istringstream ss(argument);
1652 int const unknown_tokens = defaults.readHeader(lex);
1654 if (unknown_tokens != 0) {
1655 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1656 << unknown_tokens << " unknown token"
1657 << (unknown_tokens == 1 ? "" : "s")
1661 if (defaults.writeFile(FileName(defaults.absFileName())))
1662 setMessage(bformat(_("Document defaults saved in %1$s"),
1663 makeDisplayPath(fname)));
1665 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1669 case LFUN_BUFFER_PARAMS_APPLY: {
1670 BOOST_ASSERT(lyx_view_);
1671 biblio::CiteEngine const oldEngine =
1672 lyx_view_->buffer()->params().getEngine();
1674 Buffer * buffer = lyx_view_->buffer();
1676 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1678 Cursor & cur = view()->cursor();
1679 cur.recordUndoFullDocument();
1681 istringstream ss(argument);
1684 int const unknown_tokens = buffer->readHeader(lex);
1686 if (unknown_tokens != 0) {
1687 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1688 << unknown_tokens << " unknown token"
1689 << (unknown_tokens == 1 ? "" : "s")
1693 updateLayout(oldClass, buffer);
1695 biblio::CiteEngine const newEngine =
1696 lyx_view_->buffer()->params().getEngine();
1698 if (oldEngine != newEngine) {
1699 FuncRequest fr(LFUN_INSET_REFRESH);
1701 Inset & inset = lyx_view_->buffer()->inset();
1702 InsetIterator it = inset_iterator_begin(inset);
1703 InsetIterator const end = inset_iterator_end(inset);
1704 for (; it != end; ++it)
1705 if (it->lyxCode() == CITE_CODE)
1706 it->dispatch(cur, fr);
1709 updateFlags = Update::Force | Update::FitCursor;
1713 case LFUN_LAYOUT_MODULES_CLEAR: {
1714 BOOST_ASSERT(lyx_view_);
1715 Buffer * buffer = lyx_view_->buffer();
1716 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1717 view()->cursor().recordUndoFullDocument();
1718 buffer->params().clearLayoutModules();
1719 updateLayout(oldClass, buffer);
1720 updateFlags = Update::Force | Update::FitCursor;
1724 case LFUN_LAYOUT_MODULE_ADD: {
1725 BOOST_ASSERT(lyx_view_);
1726 Buffer * buffer = lyx_view_->buffer();
1727 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1728 view()->cursor().recordUndoFullDocument();
1729 buffer->params().addLayoutModule(argument);
1730 updateLayout(oldClass, buffer);
1731 updateFlags = Update::Force | Update::FitCursor;
1735 case LFUN_TEXTCLASS_APPLY: {
1736 BOOST_ASSERT(lyx_view_);
1737 Buffer * buffer = lyx_view_->buffer();
1739 loadTextClass(argument);
1741 std::pair<bool, textclass_type> const tc_pair =
1742 textclasslist.numberOfClass(argument);
1747 textclass_type const old_class = buffer->params().getBaseClass();
1748 textclass_type const new_class = tc_pair.second;
1750 if (old_class == new_class)
1754 //Save the old, possibly modular, layout for use in conversion.
1755 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1756 view()->cursor().recordUndoFullDocument();
1757 buffer->params().setBaseClass(new_class);
1758 updateLayout(oldClass, buffer);
1759 updateFlags = Update::Force | Update::FitCursor;
1763 case LFUN_LAYOUT_RELOAD: {
1764 BOOST_ASSERT(lyx_view_);
1765 Buffer * buffer = lyx_view_->buffer();
1766 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1767 textclass_type const tc = buffer->params().getBaseClass();
1768 textclasslist.reset(tc);
1769 buffer->params().setBaseClass(tc);
1770 updateLayout(oldClass, buffer);
1771 updateFlags = Update::Force | Update::FitCursor;
1775 case LFUN_TEXTCLASS_LOAD:
1776 loadTextClass(argument);
1779 case LFUN_LYXRC_APPLY: {
1780 LyXRC const lyxrc_orig = lyxrc;
1782 istringstream ss(argument);
1783 bool const success = lyxrc.read(ss) == 0;
1786 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1787 << "Unable to read lyxrc data"
1792 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1794 theApp()->resetGui();
1796 /// We force the redraw in any case because there might be
1797 /// some screen font changes.
1798 /// FIXME: only the current view will be updated. the Gui
1799 /// class is able to furnish the list of views.
1800 updateFlags = Update::Force;
1804 case LFUN_BOOKMARK_GOTO:
1805 // go to bookmark, open unopened file and switch to buffer if necessary
1806 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1809 case LFUN_BOOKMARK_CLEAR:
1810 LyX::ref().session().bookmarks().clear();
1814 BOOST_ASSERT(theApp());
1815 // Let the frontend dispatch its own actions.
1816 if (theApp()->dispatch(cmd))
1817 // Nothing more to do.
1820 // Let the current LyXView dispatch its own actions.
1821 BOOST_ASSERT(lyx_view_);
1822 if (lyx_view_->dispatch(cmd)) {
1823 if (lyx_view_->view())
1824 updateFlags = lyx_view_->view()->cursor().result().update();
1828 // FIXME: Probably a good idea to inverse the Cursor and BufferView
1831 // Let the current Cursor dispatch its own actions.
1832 BOOST_ASSERT(lyx_view_->view());
1833 view()->cursor().dispatch(cmd);
1834 updateFlags = view()->cursor().result().update();
1835 if (!view()->cursor().result().dispatched())
1836 // Let the current BufferView dispatch its own actions.
1837 updateFlags = view()->dispatch(cmd);
1842 if (lyx_view_ && lyx_view_->buffer()) {
1843 // BufferView::update() updates the ViewMetricsInfo and
1844 // also initializes the position cache for all insets in
1845 // (at least partially) visible top-level paragraphs.
1846 // We will redraw the screen only if needed.
1847 view()->processUpdateFlags(updateFlags);
1849 // if we executed a mutating lfun, mark the buffer as dirty
1851 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1852 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1853 lyx_view_->buffer()->markDirty();
1855 //Do we have a selection?
1856 theSelection().haveSelection(view()->cursor().selection());
1859 if (!quitting && lyx_view_) {
1860 // Some messages may already be translated, so we cannot use _()
1861 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1866 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1868 const bool verbose = (cmd.origin == FuncRequest::MENU
1869 || cmd.origin == FuncRequest::TOOLBAR
1870 || cmd.origin == FuncRequest::COMMANDBUFFER);
1872 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1873 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1875 lyx_view_->message(msg);
1879 docstring dispatch_msg = msg;
1880 if (!dispatch_msg.empty())
1881 dispatch_msg += ' ';
1883 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1885 bool argsadded = false;
1887 if (!cmd.argument().empty()) {
1888 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1889 comname += ' ' + cmd.argument();
1894 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1896 if (!shortcuts.empty())
1897 comname += ": " + shortcuts;
1898 else if (!argsadded && !cmd.argument().empty())
1899 comname += ' ' + cmd.argument();
1901 if (!comname.empty()) {
1902 comname = rtrim(comname);
1903 dispatch_msg += '(' + rtrim(comname) + ')';
1906 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1907 if (!dispatch_msg.empty())
1908 lyx_view_->message(dispatch_msg);
1912 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1914 // FIXME: initpath is not used. What to do?
1915 string initpath = lyxrc.document_path;
1916 string filename(name);
1918 if (lyx_view_->buffer()) {
1919 string const trypath = lyx_view_->buffer()->filePath();
1920 // If directory is writeable, use this as default.
1921 if (FileName(trypath).isDirWritable())
1925 static int newfile_number;
1927 if (filename.empty()) {
1928 filename = addName(lyxrc.document_path,
1929 "newfile" + convert<string>(++newfile_number) + ".lyx");
1930 while (theBufferList().exists(filename) ||
1931 FileName(filename).isReadableFile()) {
1933 filename = addName(lyxrc.document_path,
1934 "newfile" + convert<string>(newfile_number) +
1939 // The template stuff
1942 FileDialog dlg(_("Select template file"));
1943 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1944 dlg.setButton1(_("Templates|#T#t"), from_utf8(lyxrc.template_path));
1946 FileDialog::Result result =
1947 dlg.open(from_utf8(lyxrc.template_path),
1948 FileFilterList(_("LyX Documents (*.lyx)")),
1951 if (result.first == FileDialog::Later)
1953 if (result.second.empty())
1955 templname = to_utf8(result.second);
1958 Buffer * const b = newFile(filename, templname, !name.empty());
1960 lyx_view_->setBuffer(b);
1964 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1966 lyx_view_->setBusy(true);
1968 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1971 lyx_view_->message(_("Document not loaded."));
1972 lyx_view_->setBusy(false);
1976 lyx_view_->setBuffer(newBuffer);
1978 // scroll to the position when the file was last closed
1979 if (lyxrc.use_lastfilepos) {
1980 LastFilePosSection::FilePos filepos =
1981 LyX::ref().session().lastFilePos().load(filename);
1982 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1986 LyX::ref().session().lastFiles().add(filename);
1988 lyx_view_->setBusy(false);
1993 void LyXFunc::open(string const & fname)
1995 string initpath = lyxrc.document_path;
1997 if (lyx_view_->buffer()) {
1998 string const trypath = lyx_view_->buffer()->filePath();
1999 // If directory is writeable, use this as default.
2000 if (FileName(trypath).isDirWritable())
2006 if (fname.empty()) {
2007 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
2008 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2009 dlg.setButton2(_("Examples|#E#e"),
2010 from_utf8(addPath(package().system_support().absFilename(), "examples")));
2012 FileDialog::Result result =
2013 dlg.open(from_utf8(initpath),
2014 FileFilterList(_("LyX Documents (*.lyx)")),
2017 if (result.first == FileDialog::Later)
2020 filename = to_utf8(result.second);
2022 // check selected filename
2023 if (filename.empty()) {
2024 lyx_view_->message(_("Canceled."));
2030 // get absolute path of file and add ".lyx" to the filename if
2032 FileName const fullname = fileSearch(string(), filename, "lyx");
2033 if (!fullname.empty())
2034 filename = fullname.absFilename();
2036 // if the file doesn't exist, let the user create one
2037 if (!fullname.exists()) {
2038 // the user specifically chose this name. Believe him.
2039 Buffer * const b = newFile(filename, string(), true);
2041 lyx_view_->setBuffer(b);
2045 docstring const disp_fn = makeDisplayPath(filename);
2046 lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
2049 Buffer * buf = loadAndViewFile(fullname);
2052 lyx_view_->setBuffer(buf);
2053 buf->errors("Parse");
2054 str2 = bformat(_("Document %1$s opened."), disp_fn);
2056 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2058 lyx_view_->message(str2);
2062 void LyXFunc::doImport(string const & argument)
2065 string filename = split(argument, format, ' ');
2067 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
2068 << " file: " << filename);
2070 // need user interaction
2071 if (filename.empty()) {
2072 string initpath = lyxrc.document_path;
2074 if (lyx_view_->buffer()) {
2075 string const trypath = lyx_view_->buffer()->filePath();
2076 // If directory is writeable, use this as default.
2077 if (FileName(trypath).isDirWritable())
2081 docstring const text = bformat(_("Select %1$s file to import"),
2082 formats.prettyName(format));
2084 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
2085 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2086 dlg.setButton2(_("Examples|#E#e"),
2087 from_utf8(addPath(package().system_support().absFilename(), "examples")));
2089 docstring filter = formats.prettyName(format);
2092 filter += from_utf8(formats.extension(format));
2095 FileDialog::Result result =
2096 dlg.open(from_utf8(initpath),
2097 FileFilterList(filter),
2100 if (result.first == FileDialog::Later)
2103 filename = to_utf8(result.second);
2105 // check selected filename
2106 if (filename.empty())
2107 lyx_view_->message(_("Canceled."));
2110 if (filename.empty())
2113 // get absolute path of file
2114 FileName const fullname(makeAbsPath(filename));
2116 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2118 // Check if the document already is open
2119 if (use_gui && theBufferList().exists(lyxfile.absFilename())) {
2120 if (!theBufferList().close(theBufferList().getBuffer(lyxfile.absFilename()), true)) {
2121 lyx_view_->message(_("Canceled."));
2126 // if the file exists already, and we didn't do
2127 // -i lyx thefile.lyx, warn
2128 if (lyxfile.exists() && fullname != lyxfile) {
2129 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2131 docstring text = bformat(_("The document %1$s already exists.\n\n"
2132 "Do you want to overwrite that document?"), file);
2133 int const ret = Alert::prompt(_("Overwrite document?"),
2134 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2137 lyx_view_->message(_("Canceled."));
2142 ErrorList errorList;
2143 import(lyx_view_, fullname, format, errorList);
2144 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2148 void LyXFunc::closeBuffer()
2150 // goto bookmark to update bookmark pit.
2151 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2152 gotoBookmark(i+1, false, false);
2154 theBufferList().close(lyx_view_->buffer(), true);
2158 void LyXFunc::reloadBuffer()
2160 FileName filename(lyx_view_->buffer()->absFileName());
2161 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2164 Buffer * buf = loadAndViewFile(filename);
2167 lyx_view_->setBuffer(buf);
2168 buf->errors("Parse");
2169 str = bformat(_("Document %1$s reloaded."), disp_fn);
2171 str = bformat(_("Could not reload document %1$s"), disp_fn);
2173 lyx_view_->message(str);
2176 // Each "lyx_view_" should have it's own message method. lyxview and
2177 // the minibuffer would use the minibuffer, but lyxserver would
2178 // send an ERROR signal to its client. Alejandro 970603
2179 // This function is bit problematic when it comes to NLS, to make the
2180 // lyx servers client be language indepenent we must not translate
2181 // strings sent to this func.
2182 void LyXFunc::setErrorMessage(docstring const & m) const
2184 dispatch_buffer = m;
2189 void LyXFunc::setMessage(docstring const & m) const
2191 dispatch_buffer = m;
2195 docstring const LyXFunc::viewStatusMessage()
2197 // When meta-fake key is pressed, show the key sequence so far + "M-".
2199 return keyseq.print(KeySequence::ForGui) + "M-";
2201 // Else, when a non-complete key sequence is pressed,
2202 // show the available options.
2203 if (keyseq.length() > 0 && !keyseq.deleted())
2204 return keyseq.printOptions(true);
2206 BOOST_ASSERT(lyx_view_);
2207 if (!lyx_view_->buffer())
2208 return _("Welcome to LyX!");
2210 return view()->cursor().currentState();
2214 BufferView * LyXFunc::view() const
2216 BOOST_ASSERT(lyx_view_);
2217 return lyx_view_->view();
2221 bool LyXFunc::wasMetaKey() const
2223 return (meta_fake_bit != NoModifier);
2227 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2230 lyx_view_->message(_("Converting document to new document class..."));
2232 StableDocIterator backcur(view()->cursor());
2233 ErrorList & el = buffer->errorList("Class Switch");
2234 cap::switchBetweenClasses(
2235 oldlayout, buffer->params().getTextClassPtr(),
2236 static_cast<InsetText &>(buffer->inset()), el);
2238 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2240 buffer->errors("Class Switch");
2241 updateLabels(*buffer);
2247 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2249 // Why the switch you might ask. It is a trick to ensure that all
2250 // the elements in the LyXRCTags enum is handled. As you can see
2251 // there are no breaks at all. So it is just a huge fall-through.
2252 // The nice thing is that we will get a warning from the compiler
2253 // if we forget an element.
2254 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2256 case LyXRC::RC_ACCEPT_COMPOUND:
2257 case LyXRC::RC_ALT_LANG:
2258 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2259 case LyXRC::RC_PLAINTEXT_LINELEN:
2260 case LyXRC::RC_AUTOREGIONDELETE:
2261 case LyXRC::RC_AUTORESET_OPTIONS:
2262 case LyXRC::RC_AUTOSAVE:
2263 case LyXRC::RC_AUTO_NUMBER:
2264 case LyXRC::RC_BACKUPDIR_PATH:
2265 case LyXRC::RC_BIBTEX_COMMAND:
2266 case LyXRC::RC_BINDFILE:
2267 case LyXRC::RC_CHECKLASTFILES:
2268 case LyXRC::RC_USELASTFILEPOS:
2269 case LyXRC::RC_LOADSESSION:
2270 case LyXRC::RC_CHKTEX_COMMAND:
2271 case LyXRC::RC_CONVERTER:
2272 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2273 case LyXRC::RC_COPIER:
2274 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2275 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2276 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2277 case LyXRC::RC_DATE_INSERT_FORMAT:
2278 case LyXRC::RC_DEFAULT_LANGUAGE:
2279 case LyXRC::RC_DEFAULT_PAPERSIZE:
2280 case LyXRC::RC_DEFFILE:
2281 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2282 case LyXRC::RC_DISPLAY_GRAPHICS:
2283 case LyXRC::RC_DOCUMENTPATH:
2284 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2285 FileName path(lyxrc_new.document_path);
2286 if (path.exists() && path.isDirectory())
2287 support::package().document_dir() = FileName(lyxrc.document_path);
2289 case LyXRC::RC_ESC_CHARS:
2290 case LyXRC::RC_EXAMPLEPATH:
2291 case LyXRC::RC_FONT_ENCODING:
2292 case LyXRC::RC_FORMAT:
2293 case LyXRC::RC_INDEX_COMMAND:
2294 case LyXRC::RC_INPUT:
2295 case LyXRC::RC_KBMAP:
2296 case LyXRC::RC_KBMAP_PRIMARY:
2297 case LyXRC::RC_KBMAP_SECONDARY:
2298 case LyXRC::RC_LABEL_INIT_LENGTH:
2299 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2300 case LyXRC::RC_LANGUAGE_AUTO_END:
2301 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2302 case LyXRC::RC_LANGUAGE_COMMAND_END:
2303 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2304 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2305 case LyXRC::RC_LANGUAGE_PACKAGE:
2306 case LyXRC::RC_LANGUAGE_USE_BABEL:
2307 case LyXRC::RC_MAKE_BACKUP:
2308 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2309 case LyXRC::RC_NUMLASTFILES:
2310 case LyXRC::RC_PATH_PREFIX:
2311 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2312 support::prependEnvPath("PATH", lyxrc.path_prefix);
2314 case LyXRC::RC_PERS_DICT:
2315 case LyXRC::RC_PREVIEW:
2316 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2317 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2318 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2319 case LyXRC::RC_PRINTCOPIESFLAG:
2320 case LyXRC::RC_PRINTER:
2321 case LyXRC::RC_PRINTEVENPAGEFLAG:
2322 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2323 case LyXRC::RC_PRINTFILEEXTENSION:
2324 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2325 case LyXRC::RC_PRINTODDPAGEFLAG:
2326 case LyXRC::RC_PRINTPAGERANGEFLAG:
2327 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2328 case LyXRC::RC_PRINTPAPERFLAG:
2329 case LyXRC::RC_PRINTREVERSEFLAG:
2330 case LyXRC::RC_PRINTSPOOL_COMMAND:
2331 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2332 case LyXRC::RC_PRINTTOFILE:
2333 case LyXRC::RC_PRINTTOPRINTER:
2334 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2335 case LyXRC::RC_PRINT_COMMAND:
2336 case LyXRC::RC_RTL_SUPPORT:
2337 case LyXRC::RC_SCREEN_DPI:
2338 case LyXRC::RC_SCREEN_FONT_ROMAN:
2339 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2340 case LyXRC::RC_SCREEN_FONT_SANS:
2341 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2342 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2343 case LyXRC::RC_SCREEN_FONT_SIZES:
2344 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2345 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2346 case LyXRC::RC_GEOMETRY_SESSION:
2347 case LyXRC::RC_SCREEN_ZOOM:
2348 case LyXRC::RC_SERVERPIPE:
2349 case LyXRC::RC_SET_COLOR:
2350 case LyXRC::RC_SHOW_BANNER:
2351 case LyXRC::RC_SPELL_COMMAND:
2352 case LyXRC::RC_TEMPDIRPATH:
2353 case LyXRC::RC_TEMPLATEPATH:
2354 case LyXRC::RC_TEX_ALLOWS_SPACES:
2355 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2356 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2357 support::os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2359 case LyXRC::RC_UIFILE:
2360 case LyXRC::RC_USER_EMAIL:
2361 case LyXRC::RC_USER_NAME:
2362 case LyXRC::RC_USETEMPDIR:
2363 case LyXRC::RC_USE_ALT_LANG:
2364 case LyXRC::RC_USE_CONVERTER_CACHE:
2365 case LyXRC::RC_USE_ESC_CHARS:
2366 case LyXRC::RC_USE_INP_ENC:
2367 case LyXRC::RC_USE_PERS_DICT:
2368 case LyXRC::RC_USE_PIXMAP_CACHE:
2369 case LyXRC::RC_USE_SPELL_LIB:
2370 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2371 case LyXRC::RC_SORT_LAYOUTS:
2372 case LyXRC::RC_VIEWER:
2373 case LyXRC::RC_LAST: