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(FileName(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 // FIXME: these cases should be hidden in GuiApplication::getStatus().
535 case LFUN_WINDOW_CLOSE:
537 return theApp()->getStatus(cmd);
541 // FIXME: these cases should be hidden in GuiView::getStatus().
542 case LFUN_DIALOG_TOGGLE:
543 case LFUN_DIALOG_SHOW:
544 case LFUN_DIALOG_UPDATE:
545 case LFUN_TOOLBAR_TOGGLE:
546 case LFUN_INSET_APPLY:
547 case LFUN_BUFFER_WRITE:
548 case LFUN_BUFFER_WRITE_AS:
550 return lyx_view_->getStatus(cmd);
554 case LFUN_BUFFER_TOGGLE_READ_ONLY:
555 flag.setOnOff(buf->isReadonly());
558 case LFUN_BUFFER_SWITCH:
559 // toggle on the current buffer, but do not toggle off
560 // the other ones (is that a good idea?)
561 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
565 case LFUN_BUFFER_EXPORT:
566 enable = cmd.argument() == "custom"
567 || buf->isExportable(to_utf8(cmd.argument()));
570 case LFUN_BUFFER_CHKTEX:
571 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
574 case LFUN_BUILD_PROGRAM:
575 enable = buf->isExportable("program");
578 case LFUN_VC_REGISTER:
579 enable = !buf->lyxvc().inUse();
581 case LFUN_VC_CHECK_IN:
582 enable = buf->lyxvc().inUse() && !buf->isReadonly();
584 case LFUN_VC_CHECK_OUT:
585 enable = buf->lyxvc().inUse() && buf->isReadonly();
588 case LFUN_VC_UNDO_LAST:
589 enable = buf->lyxvc().inUse();
591 case LFUN_BUFFER_RELOAD:
592 enable = !buf->isUnnamed() && buf->fileName().exists()
593 && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
596 case LFUN_CITATION_INSERT: {
597 FuncRequest fr(LFUN_INSET_INSERT, "citation");
598 enable = getStatus(fr).enabled();
602 // This could be used for the no-GUI version. The GUI version is handled in
603 // LyXView::getStatus().
605 case LFUN_BUFFER_WRITE:
606 case LFUN_BUFFER_WRITE_AS: {
607 Buffer * b = theBufferList().getBuffer(cmd.getArg(0));
608 enable = b && (b->isUnnamed() || !b->isClean());
613 case LFUN_BUFFER_WRITE_ALL: {
614 // We enable the command only if there are some modified buffers
615 Buffer * first = theBufferList().first();
620 // We cannot use a for loop as the buffer list is a cycle.
626 b = theBufferList().next(b);
627 } while (b != first);
631 case LFUN_BOOKMARK_GOTO: {
632 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
633 enable = LyX::ref().session().bookmarks().isValid(num);
637 case LFUN_BOOKMARK_CLEAR:
638 enable = LyX::ref().session().bookmarks().size() > 0;
641 // this one is difficult to get right. As a half-baked
642 // solution, we consider only the first action of the sequence
643 case LFUN_COMMAND_SEQUENCE: {
644 // argument contains ';'-terminated commands
645 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
646 FuncRequest func(lyxaction.lookupFunc(firstcmd));
647 func.origin = cmd.origin;
648 flag = getStatus(func);
654 std::string name = to_utf8(cmd.argument());
655 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
656 func.origin = cmd.origin;
657 flag = getStatus(func);
658 LyX::ref().topLevelCmdDef().release(name);
660 // catch recursion or unknown command definiton
661 // all operations until the recursion or unknown command
662 // definiton occures are performed, so set the state to enabled
668 case LFUN_BUFFER_NEW:
669 case LFUN_BUFFER_NEW_TEMPLATE:
670 case LFUN_WORD_FIND_FORWARD:
671 case LFUN_WORD_FIND_BACKWARD:
672 case LFUN_COMMAND_PREFIX:
673 case LFUN_COMMAND_EXECUTE:
675 case LFUN_META_PREFIX:
676 case LFUN_BUFFER_CLOSE:
677 case LFUN_BUFFER_UPDATE:
678 case LFUN_BUFFER_VIEW:
679 case LFUN_MASTER_BUFFER_UPDATE:
680 case LFUN_MASTER_BUFFER_VIEW:
681 case LFUN_BUFFER_IMPORT:
682 case LFUN_BUFFER_AUTO_SAVE:
683 case LFUN_RECONFIGURE:
687 case LFUN_DROP_LAYOUTS_CHOICE:
689 case LFUN_SERVER_GET_NAME:
690 case LFUN_SERVER_NOTIFY:
691 case LFUN_SERVER_GOTO_FILE_ROW:
692 case LFUN_DIALOG_HIDE:
693 case LFUN_DIALOG_DISCONNECT_INSET:
694 case LFUN_BUFFER_CHILD_OPEN:
695 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
696 case LFUN_KEYMAP_OFF:
697 case LFUN_KEYMAP_PRIMARY:
698 case LFUN_KEYMAP_SECONDARY:
699 case LFUN_KEYMAP_TOGGLE:
701 case LFUN_BUFFER_EXPORT_CUSTOM:
702 case LFUN_BUFFER_PRINT:
703 case LFUN_PREFERENCES_SAVE:
704 case LFUN_SCREEN_FONT_UPDATE:
707 case LFUN_EXTERNAL_EDIT:
708 case LFUN_GRAPHICS_EDIT:
709 case LFUN_ALL_INSETS_TOGGLE:
710 case LFUN_BUFFER_LANGUAGE:
711 case LFUN_TEXTCLASS_APPLY:
712 case LFUN_TEXTCLASS_LOAD:
713 case LFUN_BUFFER_SAVE_AS_DEFAULT:
714 case LFUN_BUFFER_PARAMS_APPLY:
715 case LFUN_LAYOUT_MODULES_CLEAR:
716 case LFUN_LAYOUT_MODULE_ADD:
717 case LFUN_LAYOUT_RELOAD:
718 case LFUN_LYXRC_APPLY:
719 case LFUN_BUFFER_NEXT:
720 case LFUN_BUFFER_PREVIOUS:
721 case LFUN_WINDOW_NEW:
723 // these are handled in our dispatch()
731 if (!getLocalStatus(view()->cursor(), cmd, flag))
732 flag = view()->getStatus(cmd);
738 // Can we use a readonly buffer?
739 if (buf && buf->isReadonly()
740 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
741 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
742 flag.message(from_utf8(N_("Document is read-only")));
746 // Are we in a DELETED change-tracking region?
748 && lookupChangeType(view()->cursor(), true) == Change::DELETED
749 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
750 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
751 flag.message(from_utf8(N_("This portion of the document is deleted.")));
755 // the default error message if we disable the command
756 if (!flag.enabled() && flag.message().empty())
757 flag.message(from_utf8(N_("Command disabled")));
763 bool LyXFunc::ensureBufferClean(BufferView * bv)
765 Buffer & buf = bv->buffer();
769 docstring const file = buf.fileName().displayName(30);
770 docstring text = bformat(_("The document %1$s has unsaved "
771 "changes.\n\nDo you want to save "
772 "the document?"), file);
773 int const ret = Alert::prompt(_("Save changed document?"),
774 text, 0, 1, _("&Save"),
778 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
780 return buf.isClean();
786 void showPrintError(string const & name)
788 docstring str = bformat(_("Could not print the document %1$s.\n"
789 "Check that your printer is set up correctly."),
790 makeDisplayPath(name, 50));
791 Alert::error(_("Print document failed"), str);
795 void loadTextClass(string const & name)
797 std::pair<bool, textclass_type> const tc_pair =
798 textclasslist.numberOfClass(name);
800 if (!tc_pair.first) {
801 lyxerr << "Document class \"" << name
802 << "\" does not exist."
807 textclass_type const tc = tc_pair.second;
809 if (!textclasslist[tc].load()) {
810 docstring s = bformat(_("The document class %1$s."
811 "could not be loaded."),
812 from_utf8(textclasslist[tc].name()));
813 Alert::error(_("Could not load class"), s);
818 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
823 void LyXFunc::dispatch(FuncRequest const & cmd)
825 string const argument = to_utf8(cmd.argument());
826 kb_action const action = cmd.action;
828 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
829 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
831 // we have not done anything wrong yet.
833 dispatch_buffer.erase();
835 // redraw the screen at the end (first of the two drawing steps).
836 //This is done unless explicitely requested otherwise
837 Update::flags updateFlags = Update::FitCursor;
839 FuncStatus const flag = getStatus(cmd);
840 if (!flag.enabled()) {
841 // We cannot use this function here
842 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
843 << lyxaction.getActionName(action)
844 << " [" << action << "] is disabled at this location");
845 setErrorMessage(flag.message());
849 case LFUN_WORD_FIND_FORWARD:
850 case LFUN_WORD_FIND_BACKWARD: {
851 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
852 static docstring last_search;
853 docstring searched_string;
855 if (!cmd.argument().empty()) {
856 last_search = cmd.argument();
857 searched_string = cmd.argument();
859 searched_string = last_search;
862 if (searched_string.empty())
865 bool const fw = action == LFUN_WORD_FIND_FORWARD;
866 docstring const data =
867 find2string(searched_string, true, false, fw);
868 find(view(), FuncRequest(LFUN_WORD_FIND, data));
872 case LFUN_COMMAND_PREFIX:
873 BOOST_ASSERT(lyx_view_);
874 lyx_view_->message(keyseq.printOptions(true));
878 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
880 meta_fake_bit = NoModifier;
881 if (lyx_view_->buffer())
882 // cancel any selection
883 dispatch(FuncRequest(LFUN_MARK_OFF));
884 setMessage(from_ascii(N_("Cancel")));
887 case LFUN_META_PREFIX:
888 meta_fake_bit = AltModifier;
889 setMessage(keyseq.print(KeySequence::ForGui));
892 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
893 BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
894 Buffer * buf = lyx_view_->buffer();
895 if (buf->lyxvc().inUse())
896 buf->lyxvc().toggleReadOnly();
898 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
902 // --- Menus -----------------------------------------------
903 case LFUN_BUFFER_NEW:
904 menuNew(argument, false);
905 updateFlags = Update::None;
908 case LFUN_BUFFER_NEW_TEMPLATE:
909 menuNew(argument, true);
910 updateFlags = Update::None;
913 case LFUN_BUFFER_CLOSE:
915 updateFlags = Update::None;
918 case LFUN_BUFFER_RELOAD: {
919 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
920 docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
921 docstring text = bformat(_("Any changes will be lost. Are you sure "
922 "you want to revert to the saved version of the document %1$s?"), file);
923 int const ret = Alert::prompt(_("Revert to saved document?"),
924 text, 1, 1, _("&Revert"), _("&Cancel"));
931 case LFUN_BUFFER_UPDATE:
932 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
933 lyx_view_->buffer()->doExport(argument, true);
936 case LFUN_BUFFER_VIEW:
937 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
938 lyx_view_->buffer()->preview(argument);
941 case LFUN_MASTER_BUFFER_UPDATE:
942 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
943 lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
946 case LFUN_MASTER_BUFFER_VIEW:
947 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
948 lyx_view_->buffer()->masterBuffer()->preview(argument);
951 case LFUN_BUILD_PROGRAM:
952 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
953 lyx_view_->buffer()->doExport("program", true);
956 case LFUN_BUFFER_CHKTEX:
957 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
958 lyx_view_->buffer()->runChktex();
961 case LFUN_BUFFER_EXPORT:
962 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
963 if (argument == "custom")
964 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
966 lyx_view_->buffer()->doExport(argument, false);
969 case LFUN_BUFFER_EXPORT_CUSTOM: {
970 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
972 string command = split(argument, format_name, ' ');
973 Format const * format = formats.getFormat(format_name);
975 lyxerr << "Format \"" << format_name
976 << "\" not recognized!"
981 Buffer * buffer = lyx_view_->buffer();
983 // The name of the file created by the conversion process
986 // Output to filename
987 if (format->name() == "lyx") {
988 string const latexname = buffer->latexName(false);
989 filename = changeExtension(latexname,
990 format->extension());
991 filename = addName(buffer->temppath(), filename);
993 if (!buffer->writeFile(FileName(filename)))
997 buffer->doExport(format_name, true, filename);
1000 // Substitute $$FName for filename
1001 if (!contains(command, "$$FName"))
1002 command = "( " + command + " ) < $$FName";
1003 command = subst(command, "$$FName", filename);
1005 // Execute the command in the background
1007 call.startscript(Systemcall::DontWait, command);
1011 case LFUN_BUFFER_PRINT: {
1012 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1013 // FIXME: cmd.getArg() might fail if one of the arguments
1014 // contains double quotes
1015 string target = cmd.getArg(0);
1016 string target_name = cmd.getArg(1);
1017 string command = cmd.getArg(2);
1020 || target_name.empty()
1021 || command.empty()) {
1022 lyxerr << "Unable to parse \""
1023 << argument << '"' << endl;
1026 if (target != "printer" && target != "file") {
1027 lyxerr << "Unrecognized target \""
1028 << target << '"' << endl;
1032 Buffer * buffer = lyx_view_->buffer();
1034 if (!buffer->doExport("dvi", true)) {
1035 showPrintError(buffer->absFileName());
1039 // Push directory path.
1040 string const path = buffer->temppath();
1041 // Prevent the compiler from optimizing away p
1043 support::PathChanger p(pp);
1045 // there are three cases here:
1046 // 1. we print to a file
1047 // 2. we print directly to a printer
1048 // 3. we print using a spool command (print to file first)
1051 string const dviname =
1052 changeExtension(buffer->latexName(true), "dvi");
1054 if (target == "printer") {
1055 if (!lyxrc.print_spool_command.empty()) {
1056 // case 3: print using a spool
1057 string const psname =
1058 changeExtension(dviname,".ps");
1059 command += ' ' + lyxrc.print_to_file
1062 + quoteName(dviname);
1065 lyxrc.print_spool_command + ' ';
1066 if (target_name != "default") {
1067 command2 += lyxrc.print_spool_printerprefix
1071 command2 += quoteName(psname);
1073 // If successful, then spool command
1074 res = one.startscript(
1079 res = one.startscript(
1080 Systemcall::DontWait,
1083 // case 2: print directly to a printer
1084 if (target_name != "default")
1085 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1086 res = one.startscript(
1087 Systemcall::DontWait,
1088 command + quoteName(dviname));
1092 // case 1: print to a file
1093 FileName const filename(makeAbsPath(target_name,
1094 lyx_view_->buffer()->filePath()));
1095 FileName const dvifile(makeAbsPath(dviname, path));
1096 if (filename.exists()) {
1097 docstring text = bformat(
1098 _("The file %1$s already exists.\n\n"
1099 "Do you want to overwrite that file?"),
1100 makeDisplayPath(filename.absFilename()));
1101 if (Alert::prompt(_("Overwrite file?"),
1102 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1105 command += ' ' + lyxrc.print_to_file
1106 + quoteName(filename.toFilesystemEncoding())
1108 + quoteName(dvifile.toFilesystemEncoding());
1109 res = one.startscript(Systemcall::DontWait,
1114 showPrintError(buffer->absFileName());
1118 case LFUN_BUFFER_IMPORT:
1122 case LFUN_BUFFER_AUTO_SAVE:
1123 lyx_view_->buffer()->autoSave();
1126 case LFUN_RECONFIGURE:
1127 BOOST_ASSERT(lyx_view_);
1128 // argument is any additional parameter to the configure.py command
1129 reconfigure(*lyx_view_, argument);
1132 case LFUN_HELP_OPEN: {
1133 BOOST_ASSERT(lyx_view_);
1134 string const arg = argument;
1136 setErrorMessage(from_ascii(N_("Missing argument")));
1139 FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1140 if (fname.empty()) {
1141 lyxerr << "LyX: unable to find documentation file `"
1142 << arg << "'. Bad installation?" << endl;
1145 lyx_view_->message(bformat(_("Opening help file %1$s..."),
1146 makeDisplayPath(fname.absFilename())));
1147 Buffer * buf = loadAndViewFile(fname, false);
1150 lyx_view_->setBuffer(buf);
1151 buf->errors("Parse");
1153 updateFlags = Update::None;
1157 // --- version control -------------------------------
1158 case LFUN_VC_REGISTER:
1159 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1160 if (!ensureBufferClean(view()))
1162 if (!lyx_view_->buffer()->lyxvc().inUse()) {
1163 lyx_view_->buffer()->lyxvc().registrer();
1166 updateFlags = Update::Force;
1169 case LFUN_VC_CHECK_IN:
1170 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1171 if (!ensureBufferClean(view()))
1173 if (lyx_view_->buffer()->lyxvc().inUse()
1174 && !lyx_view_->buffer()->isReadonly()) {
1175 lyx_view_->buffer()->lyxvc().checkIn();
1180 case LFUN_VC_CHECK_OUT:
1181 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1182 if (!ensureBufferClean(view()))
1184 if (lyx_view_->buffer()->lyxvc().inUse()
1185 && lyx_view_->buffer()->isReadonly()) {
1186 lyx_view_->buffer()->lyxvc().checkOut();
1191 case LFUN_VC_REVERT:
1192 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1193 lyx_view_->buffer()->lyxvc().revert();
1197 case LFUN_VC_UNDO_LAST:
1198 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1199 lyx_view_->buffer()->lyxvc().undoLast();
1203 // --- buffers ----------------------------------------
1205 case LFUN_FILE_NEW: {
1206 BOOST_ASSERT(lyx_view_);
1208 string tmpname = split(argument, name, ':'); // Split filename
1209 Buffer * const b = newFile(name, tmpname);
1211 lyx_view_->setBuffer(b);
1212 updateFlags = Update::None;
1216 case LFUN_FILE_OPEN:
1217 BOOST_ASSERT(lyx_view_);
1219 updateFlags = Update::None;
1222 // --- lyxserver commands ----------------------------
1223 case LFUN_SERVER_GET_NAME:
1224 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1225 setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1226 LYXERR(Debug::INFO, "FNAME["
1227 << lyx_view_->buffer()->absFileName() << ']');
1230 case LFUN_SERVER_NOTIFY:
1231 dispatch_buffer = keyseq.print(KeySequence::Portable);
1232 theServer().notifyClient(to_utf8(dispatch_buffer));
1235 case LFUN_SERVER_GOTO_FILE_ROW: {
1236 BOOST_ASSERT(lyx_view_);
1239 istringstream is(argument);
1240 is >> file_name >> row;
1242 bool loaded = false;
1243 if (prefixIs(file_name, package().temp_dir().absFilename()))
1244 // Needed by inverse dvi search. If it is a file
1245 // in tmpdir, call the apropriated function
1246 buf = theBufferList().getBufferFromTmp(file_name);
1248 // Must replace extension of the file to be .lyx
1249 // and get full path
1250 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1251 // Either change buffer or load the file
1252 if (theBufferList().exists(s.absFilename()))
1253 buf = theBufferList().getBuffer(s.absFilename());
1255 buf = loadAndViewFile(s);
1261 updateFlags = Update::None;
1266 lyx_view_->setBuffer(buf);
1267 view()->setCursorFromRow(row);
1269 buf->errors("Parse");
1270 updateFlags = Update::FitCursor;
1275 case LFUN_DIALOG_SHOW_NEW_INSET: {
1276 BOOST_ASSERT(lyx_view_);
1277 string const name = cmd.getArg(0);
1278 InsetCode code = insetCode(name);
1279 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1280 bool insetCodeOK = true;
1289 case HYPERLINK_CODE: {
1290 InsetCommandParams p(code);
1291 data = InsetCommandMailer::params2string(name, p);
1294 case INCLUDE_CODE: {
1295 // data is the include type: one of "include",
1296 // "input", "verbatiminput" or "verbatiminput*"
1298 // default type is requested
1300 InsetCommandParams p(INCLUDE_CODE, data);
1301 data = InsetCommandMailer::params2string("include", p);
1305 // \c data == "Boxed" || "Frameless" etc
1306 InsetBoxParams p(data);
1307 data = InsetBoxMailer::params2string(p);
1311 InsetBranchParams p;
1312 data = InsetBranchMailer::params2string(p);
1316 InsetCommandParams p(CITE_CODE);
1317 data = InsetCommandMailer::params2string(name, p);
1321 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1324 case EXTERNAL_CODE: {
1325 InsetExternalParams p;
1326 Buffer const & buffer = *lyx_view_->buffer();
1327 data = InsetExternalMailer::params2string(p, buffer);
1332 data = InsetFloatMailer::params2string(p);
1335 case LISTINGS_CODE: {
1336 InsetListingsParams p;
1337 data = InsetListingsMailer::params2string(p);
1340 case GRAPHICS_CODE: {
1341 InsetGraphicsParams p;
1342 Buffer const & buffer = *lyx_view_->buffer();
1343 data = InsetGraphicsMailer::params2string(p, buffer);
1348 data = InsetNoteMailer::params2string(p);
1353 data = InsetVSpaceMailer::params2string(space);
1358 data = InsetWrapMailer::params2string(p);
1362 lyxerr << "Inset type '" << name <<
1363 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << std:: endl;
1364 insetCodeOK = false;
1366 } // end switch(code)
1368 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1372 case LFUN_CITATION_INSERT: {
1373 BOOST_ASSERT(lyx_view_);
1374 if (!argument.empty()) {
1375 // we can have one optional argument, delimited by '|'
1376 // citation-insert <key>|<text_before>
1377 // this should be enhanced to also support text_after
1378 // and citation style
1379 string arg = argument;
1381 if (contains(argument, "|")) {
1382 arg = token(argument, '|', 0);
1383 opt1 = token(argument, '|', 1);
1385 InsetCommandParams icp(CITE_CODE);
1386 icp["key"] = from_utf8(arg);
1388 icp["before"] = from_utf8(opt1);
1389 string icstr = InsetCommandMailer::params2string("citation", icp);
1390 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1393 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1397 case LFUN_BUFFER_CHILD_OPEN: {
1398 BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1399 Buffer * parent = lyx_view_->buffer();
1400 FileName filename = makeAbsPath(argument, parent->filePath());
1401 view()->saveBookmark(false);
1403 bool parsed = false;
1404 if (theBufferList().exists(filename.absFilename())) {
1405 child = theBufferList().getBuffer(filename.absFilename());
1407 setMessage(bformat(_("Opening child document %1$s..."),
1408 makeDisplayPath(filename.absFilename())));
1409 child = loadAndViewFile(filename, true);
1413 // Set the parent name of the child document.
1414 // This makes insertion of citations and references in the child work,
1415 // when the target is in the parent or another child document.
1416 child->setParent(parent);
1417 updateLabels(*child->masterBuffer());
1418 lyx_view_->setBuffer(child);
1420 child->errors("Parse");
1423 // If a screen update is required (in case where auto_open is false),
1424 // setBuffer() would have taken care of it already. Otherwise we shall
1425 // reset the update flag because it can cause a circular problem.
1427 updateFlags = Update::None;
1431 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1432 BOOST_ASSERT(lyx_view_);
1433 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1436 case LFUN_KEYMAP_OFF:
1437 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1438 lyx_view_->view()->getIntl().keyMapOn(false);
1441 case LFUN_KEYMAP_PRIMARY:
1442 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1443 lyx_view_->view()->getIntl().keyMapPrim();
1446 case LFUN_KEYMAP_SECONDARY:
1447 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1448 lyx_view_->view()->getIntl().keyMapSec();
1451 case LFUN_KEYMAP_TOGGLE:
1452 BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1453 lyx_view_->view()->getIntl().toggleKeyMap();
1459 string rest = split(argument, countstr, ' ');
1460 istringstream is(countstr);
1463 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1464 for (int i = 0; i < count; ++i)
1465 dispatch(lyxaction.lookupFunc(rest));
1469 case LFUN_COMMAND_SEQUENCE: {
1470 // argument contains ';'-terminated commands
1471 string arg = argument;
1472 while (!arg.empty()) {
1474 arg = split(arg, first, ';');
1475 FuncRequest func(lyxaction.lookupFunc(first));
1476 func.origin = cmd.origin;
1484 if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1485 func.origin = cmd.origin;
1487 LyX::ref().topLevelCmdDef().release(argument);
1489 if (func.action == LFUN_UNKNOWN_ACTION) {
1490 // unknown command definition
1491 lyxerr << "Warning: unknown command definition `"
1495 // recursion detected
1496 lyxerr << "Warning: Recursion in the command definition `"
1497 << argument << "' detected"
1504 case LFUN_PREFERENCES_SAVE: {
1505 lyxrc.write(makeAbsPath("preferences",
1506 package().user_support().absFilename()),
1511 case LFUN_SET_COLOR: {
1513 string const x11_name = split(argument, lyx_name, ' ');
1514 if (lyx_name.empty() || x11_name.empty()) {
1515 setErrorMessage(from_ascii(N_(
1516 "Syntax: set-color <lyx_name>"
1521 bool const graphicsbg_changed =
1522 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1523 x11_name != lcolor.getX11Name(Color_graphicsbg));
1525 if (!lcolor.setColor(lyx_name, x11_name)) {
1527 bformat(_("Set-color \"%1$s\" failed "
1528 "- color is undefined or "
1529 "may not be redefined"),
1530 from_utf8(lyx_name)));
1534 theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1536 if (graphicsbg_changed) {
1537 // FIXME: The graphics cache no longer has a changeDisplay method.
1539 graphics::GCache::get().changeDisplay(true);
1546 BOOST_ASSERT(lyx_view_);
1547 lyx_view_->message(from_utf8(argument));
1550 case LFUN_EXTERNAL_EDIT: {
1551 BOOST_ASSERT(lyx_view_);
1552 FuncRequest fr(action, argument);
1553 InsetExternal().dispatch(view()->cursor(), fr);
1557 case LFUN_GRAPHICS_EDIT: {
1558 FuncRequest fr(action, argument);
1559 InsetGraphics().dispatch(view()->cursor(), fr);
1563 case LFUN_ALL_INSETS_TOGGLE: {
1564 BOOST_ASSERT(lyx_view_);
1566 string const name = split(argument, action, ' ');
1567 InsetCode const inset_code = insetCode(name);
1569 Cursor & cur = view()->cursor();
1570 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1572 Inset & inset = lyx_view_->buffer()->inset();
1573 InsetIterator it = inset_iterator_begin(inset);
1574 InsetIterator const end = inset_iterator_end(inset);
1575 for (; it != end; ++it) {
1576 if (!it->asInsetMath()
1577 && (inset_code == NO_CODE
1578 || inset_code == it->lyxCode())) {
1579 Cursor tmpcur = cur;
1580 tmpcur.pushBackward(*it);
1581 it->dispatch(tmpcur, fr);
1584 updateFlags = Update::Force | Update::FitCursor;
1588 case LFUN_BUFFER_LANGUAGE: {
1589 BOOST_ASSERT(lyx_view_);
1590 Buffer & buffer = *lyx_view_->buffer();
1591 Language const * oldL = buffer.params().language;
1592 Language const * newL = languages.getLanguage(argument);
1593 if (!newL || oldL == newL)
1596 if (oldL->rightToLeft() == newL->rightToLeft()
1597 && !buffer.isMultiLingual())
1598 buffer.changeLanguage(oldL, newL);
1602 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1603 string const fname =
1604 addName(addPath(package().user_support().absFilename(), "templates/"),
1606 Buffer defaults(fname);
1608 istringstream ss(argument);
1611 int const unknown_tokens = defaults.readHeader(lex);
1613 if (unknown_tokens != 0) {
1614 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1615 << unknown_tokens << " unknown token"
1616 << (unknown_tokens == 1 ? "" : "s")
1620 if (defaults.writeFile(FileName(defaults.absFileName())))
1621 setMessage(bformat(_("Document defaults saved in %1$s"),
1622 makeDisplayPath(fname)));
1624 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1628 case LFUN_BUFFER_PARAMS_APPLY: {
1629 BOOST_ASSERT(lyx_view_);
1630 biblio::CiteEngine const oldEngine =
1631 lyx_view_->buffer()->params().getEngine();
1633 Buffer * buffer = lyx_view_->buffer();
1635 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1637 Cursor & cur = view()->cursor();
1638 cur.recordUndoFullDocument();
1640 istringstream ss(argument);
1643 int const unknown_tokens = buffer->readHeader(lex);
1645 if (unknown_tokens != 0) {
1646 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1647 << unknown_tokens << " unknown token"
1648 << (unknown_tokens == 1 ? "" : "s")
1652 updateLayout(oldClass, buffer);
1654 biblio::CiteEngine const newEngine =
1655 lyx_view_->buffer()->params().getEngine();
1657 if (oldEngine != newEngine) {
1658 FuncRequest fr(LFUN_INSET_REFRESH);
1660 Inset & inset = lyx_view_->buffer()->inset();
1661 InsetIterator it = inset_iterator_begin(inset);
1662 InsetIterator const end = inset_iterator_end(inset);
1663 for (; it != end; ++it)
1664 if (it->lyxCode() == CITE_CODE)
1665 it->dispatch(cur, fr);
1668 updateFlags = Update::Force | Update::FitCursor;
1672 case LFUN_LAYOUT_MODULES_CLEAR: {
1673 BOOST_ASSERT(lyx_view_);
1674 Buffer * buffer = lyx_view_->buffer();
1675 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1676 view()->cursor().recordUndoFullDocument();
1677 buffer->params().clearLayoutModules();
1678 updateLayout(oldClass, buffer);
1679 updateFlags = Update::Force | Update::FitCursor;
1683 case LFUN_LAYOUT_MODULE_ADD: {
1684 BOOST_ASSERT(lyx_view_);
1685 Buffer * buffer = lyx_view_->buffer();
1686 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1687 view()->cursor().recordUndoFullDocument();
1688 buffer->params().addLayoutModule(argument);
1689 updateLayout(oldClass, buffer);
1690 updateFlags = Update::Force | Update::FitCursor;
1694 case LFUN_TEXTCLASS_APPLY: {
1695 BOOST_ASSERT(lyx_view_);
1696 Buffer * buffer = lyx_view_->buffer();
1698 loadTextClass(argument);
1700 std::pair<bool, textclass_type> const tc_pair =
1701 textclasslist.numberOfClass(argument);
1706 textclass_type const old_class = buffer->params().getBaseClass();
1707 textclass_type const new_class = tc_pair.second;
1709 if (old_class == new_class)
1713 //Save the old, possibly modular, layout for use in conversion.
1714 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1715 view()->cursor().recordUndoFullDocument();
1716 buffer->params().setBaseClass(new_class);
1717 updateLayout(oldClass, buffer);
1718 updateFlags = Update::Force | Update::FitCursor;
1722 case LFUN_LAYOUT_RELOAD: {
1723 BOOST_ASSERT(lyx_view_);
1724 Buffer * buffer = lyx_view_->buffer();
1725 TextClassPtr oldClass = buffer->params().getTextClassPtr();
1726 textclass_type const tc = buffer->params().getBaseClass();
1727 textclasslist.reset(tc);
1728 buffer->params().setBaseClass(tc);
1729 updateLayout(oldClass, buffer);
1730 updateFlags = Update::Force | Update::FitCursor;
1734 case LFUN_TEXTCLASS_LOAD:
1735 loadTextClass(argument);
1738 case LFUN_LYXRC_APPLY: {
1739 LyXRC const lyxrc_orig = lyxrc;
1741 istringstream ss(argument);
1742 bool const success = lyxrc.read(ss) == 0;
1745 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1746 << "Unable to read lyxrc data"
1751 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1753 theApp()->resetGui();
1755 /// We force the redraw in any case because there might be
1756 /// some screen font changes.
1757 /// FIXME: only the current view will be updated. the Gui
1758 /// class is able to furnish the list of views.
1759 updateFlags = Update::Force;
1763 case LFUN_BOOKMARK_GOTO:
1764 // go to bookmark, open unopened file and switch to buffer if necessary
1765 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1768 case LFUN_BOOKMARK_CLEAR:
1769 LyX::ref().session().bookmarks().clear();
1773 BOOST_ASSERT(theApp());
1774 // Let the frontend dispatch its own actions.
1775 if (theApp()->dispatch(cmd))
1776 // Nothing more to do.
1779 // Let the current LyXView dispatch its own actions.
1780 BOOST_ASSERT(lyx_view_);
1781 if (lyx_view_->dispatch(cmd)) {
1782 if (lyx_view_->view())
1783 updateFlags = lyx_view_->view()->cursor().result().update();
1787 // FIXME: Probably a good idea to inverse the Cursor and BufferView
1790 // Let the current Cursor dispatch its own actions.
1791 BOOST_ASSERT(lyx_view_->view());
1792 view()->cursor().dispatch(cmd);
1793 updateFlags = view()->cursor().result().update();
1794 if (!view()->cursor().result().dispatched())
1795 // Let the current BufferView dispatch its own actions.
1796 updateFlags = view()->dispatch(cmd);
1801 if (lyx_view_ && lyx_view_->buffer()) {
1802 // BufferView::update() updates the ViewMetricsInfo and
1803 // also initializes the position cache for all insets in
1804 // (at least partially) visible top-level paragraphs.
1805 // We will redraw the screen only if needed.
1806 view()->processUpdateFlags(updateFlags);
1808 // if we executed a mutating lfun, mark the buffer as dirty
1810 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1811 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1812 lyx_view_->buffer()->markDirty();
1814 //Do we have a selection?
1815 theSelection().haveSelection(view()->cursor().selection());
1818 if (!quitting && lyx_view_) {
1819 // Some messages may already be translated, so we cannot use _()
1820 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1825 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1827 const bool verbose = (cmd.origin == FuncRequest::MENU
1828 || cmd.origin == FuncRequest::TOOLBAR
1829 || cmd.origin == FuncRequest::COMMANDBUFFER);
1831 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1832 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1834 lyx_view_->message(msg);
1838 docstring dispatch_msg = msg;
1839 if (!dispatch_msg.empty())
1840 dispatch_msg += ' ';
1842 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1844 bool argsadded = false;
1846 if (!cmd.argument().empty()) {
1847 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1848 comname += ' ' + cmd.argument();
1853 docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1855 if (!shortcuts.empty())
1856 comname += ": " + shortcuts;
1857 else if (!argsadded && !cmd.argument().empty())
1858 comname += ' ' + cmd.argument();
1860 if (!comname.empty()) {
1861 comname = rtrim(comname);
1862 dispatch_msg += '(' + rtrim(comname) + ')';
1865 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1866 if (!dispatch_msg.empty())
1867 lyx_view_->message(dispatch_msg);
1871 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1873 // FIXME: initpath is not used. What to do?
1874 string initpath = lyxrc.document_path;
1875 string filename(name);
1877 if (lyx_view_->buffer()) {
1878 string const trypath = lyx_view_->buffer()->filePath();
1879 // If directory is writeable, use this as default.
1880 if (FileName(trypath).isDirWritable())
1884 static int newfile_number;
1886 if (filename.empty()) {
1887 filename = addName(lyxrc.document_path,
1888 "newfile" + convert<string>(++newfile_number) + ".lyx");
1889 while (theBufferList().exists(filename) ||
1890 FileName(filename).isReadableFile()) {
1892 filename = addName(lyxrc.document_path,
1893 "newfile" + convert<string>(newfile_number) +
1898 // The template stuff
1901 FileDialog dlg(_("Select template file"));
1902 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1903 dlg.setButton1(_("Templates|#T#t"), from_utf8(lyxrc.template_path));
1905 FileDialog::Result result =
1906 dlg.open(from_utf8(lyxrc.template_path),
1907 FileFilterList(_("LyX Documents (*.lyx)")),
1910 if (result.first == FileDialog::Later)
1912 if (result.second.empty())
1914 templname = to_utf8(result.second);
1917 Buffer * const b = newFile(filename, templname, !name.empty());
1919 lyx_view_->setBuffer(b);
1923 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1925 lyx_view_->setBusy(true);
1927 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1930 lyx_view_->message(_("Document not loaded."));
1931 lyx_view_->setBusy(false);
1935 lyx_view_->setBuffer(newBuffer);
1937 // scroll to the position when the file was last closed
1938 if (lyxrc.use_lastfilepos) {
1939 LastFilePosSection::FilePos filepos =
1940 LyX::ref().session().lastFilePos().load(filename);
1941 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1945 LyX::ref().session().lastFiles().add(filename);
1947 lyx_view_->setBusy(false);
1952 void LyXFunc::open(string const & fname)
1954 string initpath = lyxrc.document_path;
1956 if (lyx_view_->buffer()) {
1957 string const trypath = lyx_view_->buffer()->filePath();
1958 // If directory is writeable, use this as default.
1959 if (FileName(trypath).isDirWritable())
1965 if (fname.empty()) {
1966 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
1967 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1968 dlg.setButton2(_("Examples|#E#e"),
1969 from_utf8(addPath(package().system_support().absFilename(), "examples")));
1971 FileDialog::Result result =
1972 dlg.open(from_utf8(initpath),
1973 FileFilterList(_("LyX Documents (*.lyx)")),
1976 if (result.first == FileDialog::Later)
1979 filename = to_utf8(result.second);
1981 // check selected filename
1982 if (filename.empty()) {
1983 lyx_view_->message(_("Canceled."));
1989 // get absolute path of file and add ".lyx" to the filename if
1991 FileName const fullname = fileSearch(string(), filename, "lyx");
1992 if (!fullname.empty())
1993 filename = fullname.absFilename();
1995 // if the file doesn't exist, let the user create one
1996 if (!fullname.exists()) {
1997 // the user specifically chose this name. Believe him.
1998 Buffer * const b = newFile(filename, string(), true);
2000 lyx_view_->setBuffer(b);
2004 docstring const disp_fn = makeDisplayPath(filename);
2005 lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
2008 Buffer * buf = loadAndViewFile(fullname);
2011 lyx_view_->setBuffer(buf);
2012 buf->errors("Parse");
2013 str2 = bformat(_("Document %1$s opened."), disp_fn);
2015 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2017 lyx_view_->message(str2);
2021 void LyXFunc::doImport(string const & argument)
2024 string filename = split(argument, format, ' ');
2026 LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
2027 << " file: " << filename);
2029 // need user interaction
2030 if (filename.empty()) {
2031 string initpath = lyxrc.document_path;
2033 if (lyx_view_->buffer()) {
2034 string const trypath = lyx_view_->buffer()->filePath();
2035 // If directory is writeable, use this as default.
2036 if (FileName(trypath).isDirWritable())
2040 docstring const text = bformat(_("Select %1$s file to import"),
2041 formats.prettyName(format));
2043 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
2044 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2045 dlg.setButton2(_("Examples|#E#e"),
2046 from_utf8(addPath(package().system_support().absFilename(), "examples")));
2048 docstring filter = formats.prettyName(format);
2051 filter += from_utf8(formats.extension(format));
2054 FileDialog::Result result =
2055 dlg.open(from_utf8(initpath),
2056 FileFilterList(filter),
2059 if (result.first == FileDialog::Later)
2062 filename = to_utf8(result.second);
2064 // check selected filename
2065 if (filename.empty())
2066 lyx_view_->message(_("Canceled."));
2069 if (filename.empty())
2072 // get absolute path of file
2073 FileName const fullname(makeAbsPath(filename));
2075 FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2077 // Check if the document already is open
2078 Buffer * buf = theBufferList().getBuffer(lyxfile.absFilename());
2079 if (use_gui && buf) {
2080 lyx_view_->setBuffer(buf);
2081 if (!lyx_view_->closeBuffer()) {
2082 lyx_view_->message(_("Canceled."));
2087 // if the file exists already, and we didn't do
2088 // -i lyx thefile.lyx, warn
2089 if (lyxfile.exists() && fullname != lyxfile) {
2090 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2092 docstring text = bformat(_("The document %1$s already exists.\n\n"
2093 "Do you want to overwrite that document?"), file);
2094 int const ret = Alert::prompt(_("Overwrite document?"),
2095 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2098 lyx_view_->message(_("Canceled."));
2103 ErrorList errorList;
2104 import(lyx_view_, fullname, format, errorList);
2105 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2109 void LyXFunc::closeBuffer()
2111 // goto bookmark to update bookmark pit.
2112 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2113 gotoBookmark(i+1, false, false);
2115 lyx_view_->closeBuffer();
2119 void LyXFunc::reloadBuffer()
2121 FileName filename(lyx_view_->buffer()->absFileName());
2122 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2125 Buffer * buf = loadAndViewFile(filename);
2128 lyx_view_->setBuffer(buf);
2129 buf->errors("Parse");
2130 str = bformat(_("Document %1$s reloaded."), disp_fn);
2132 str = bformat(_("Could not reload document %1$s"), disp_fn);
2134 lyx_view_->message(str);
2137 // Each "lyx_view_" should have it's own message method. lyxview and
2138 // the minibuffer would use the minibuffer, but lyxserver would
2139 // send an ERROR signal to its client. Alejandro 970603
2140 // This function is bit problematic when it comes to NLS, to make the
2141 // lyx servers client be language indepenent we must not translate
2142 // strings sent to this func.
2143 void LyXFunc::setErrorMessage(docstring const & m) const
2145 dispatch_buffer = m;
2150 void LyXFunc::setMessage(docstring const & m) const
2152 dispatch_buffer = m;
2156 docstring const LyXFunc::viewStatusMessage()
2158 // When meta-fake key is pressed, show the key sequence so far + "M-".
2160 return keyseq.print(KeySequence::ForGui) + "M-";
2162 // Else, when a non-complete key sequence is pressed,
2163 // show the available options.
2164 if (keyseq.length() > 0 && !keyseq.deleted())
2165 return keyseq.printOptions(true);
2167 BOOST_ASSERT(lyx_view_);
2168 if (!lyx_view_->buffer())
2169 return _("Welcome to LyX!");
2171 return view()->cursor().currentState();
2175 BufferView * LyXFunc::view() const
2177 BOOST_ASSERT(lyx_view_);
2178 return lyx_view_->view();
2182 bool LyXFunc::wasMetaKey() const
2184 return (meta_fake_bit != NoModifier);
2188 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2191 lyx_view_->message(_("Converting document to new document class..."));
2193 StableDocIterator backcur(view()->cursor());
2194 ErrorList & el = buffer->errorList("Class Switch");
2195 cap::switchBetweenClasses(
2196 oldlayout, buffer->params().getTextClassPtr(),
2197 static_cast<InsetText &>(buffer->inset()), el);
2199 view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2201 buffer->errors("Class Switch");
2202 updateLabels(*buffer);
2208 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2210 // Why the switch you might ask. It is a trick to ensure that all
2211 // the elements in the LyXRCTags enum is handled. As you can see
2212 // there are no breaks at all. So it is just a huge fall-through.
2213 // The nice thing is that we will get a warning from the compiler
2214 // if we forget an element.
2215 LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2217 case LyXRC::RC_ACCEPT_COMPOUND:
2218 case LyXRC::RC_ALT_LANG:
2219 case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2220 case LyXRC::RC_PLAINTEXT_LINELEN:
2221 case LyXRC::RC_AUTOREGIONDELETE:
2222 case LyXRC::RC_AUTORESET_OPTIONS:
2223 case LyXRC::RC_AUTOSAVE:
2224 case LyXRC::RC_AUTO_NUMBER:
2225 case LyXRC::RC_BACKUPDIR_PATH:
2226 case LyXRC::RC_BIBTEX_COMMAND:
2227 case LyXRC::RC_BINDFILE:
2228 case LyXRC::RC_CHECKLASTFILES:
2229 case LyXRC::RC_USELASTFILEPOS:
2230 case LyXRC::RC_LOADSESSION:
2231 case LyXRC::RC_CHKTEX_COMMAND:
2232 case LyXRC::RC_CONVERTER:
2233 case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2234 case LyXRC::RC_COPIER:
2235 case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2236 case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2237 case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2238 case LyXRC::RC_DATE_INSERT_FORMAT:
2239 case LyXRC::RC_DEFAULT_LANGUAGE:
2240 case LyXRC::RC_DEFAULT_PAPERSIZE:
2241 case LyXRC::RC_DEFFILE:
2242 case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2243 case LyXRC::RC_DISPLAY_GRAPHICS:
2244 case LyXRC::RC_DOCUMENTPATH:
2245 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2246 FileName path(lyxrc_new.document_path);
2247 if (path.exists() && path.isDirectory())
2248 support::package().document_dir() = FileName(lyxrc.document_path);
2250 case LyXRC::RC_ESC_CHARS:
2251 case LyXRC::RC_EXAMPLEPATH:
2252 case LyXRC::RC_FONT_ENCODING:
2253 case LyXRC::RC_FORMAT:
2254 case LyXRC::RC_INDEX_COMMAND:
2255 case LyXRC::RC_INPUT:
2256 case LyXRC::RC_KBMAP:
2257 case LyXRC::RC_KBMAP_PRIMARY:
2258 case LyXRC::RC_KBMAP_SECONDARY:
2259 case LyXRC::RC_LABEL_INIT_LENGTH:
2260 case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2261 case LyXRC::RC_LANGUAGE_AUTO_END:
2262 case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2263 case LyXRC::RC_LANGUAGE_COMMAND_END:
2264 case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2265 case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2266 case LyXRC::RC_LANGUAGE_PACKAGE:
2267 case LyXRC::RC_LANGUAGE_USE_BABEL:
2268 case LyXRC::RC_MAKE_BACKUP:
2269 case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2270 case LyXRC::RC_NUMLASTFILES:
2271 case LyXRC::RC_PATH_PREFIX:
2272 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2273 support::prependEnvPath("PATH", lyxrc.path_prefix);
2275 case LyXRC::RC_PERS_DICT:
2276 case LyXRC::RC_PREVIEW:
2277 case LyXRC::RC_PREVIEW_HASHED_LABELS:
2278 case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2279 case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2280 case LyXRC::RC_PRINTCOPIESFLAG:
2281 case LyXRC::RC_PRINTER:
2282 case LyXRC::RC_PRINTEVENPAGEFLAG:
2283 case LyXRC::RC_PRINTEXSTRAOPTIONS:
2284 case LyXRC::RC_PRINTFILEEXTENSION:
2285 case LyXRC::RC_PRINTLANDSCAPEFLAG:
2286 case LyXRC::RC_PRINTODDPAGEFLAG:
2287 case LyXRC::RC_PRINTPAGERANGEFLAG:
2288 case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2289 case LyXRC::RC_PRINTPAPERFLAG:
2290 case LyXRC::RC_PRINTREVERSEFLAG:
2291 case LyXRC::RC_PRINTSPOOL_COMMAND:
2292 case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2293 case LyXRC::RC_PRINTTOFILE:
2294 case LyXRC::RC_PRINTTOPRINTER:
2295 case LyXRC::RC_PRINT_ADAPTOUTPUT:
2296 case LyXRC::RC_PRINT_COMMAND:
2297 case LyXRC::RC_RTL_SUPPORT:
2298 case LyXRC::RC_SCREEN_DPI:
2299 case LyXRC::RC_SCREEN_FONT_ROMAN:
2300 case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2301 case LyXRC::RC_SCREEN_FONT_SANS:
2302 case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2303 case LyXRC::RC_SCREEN_FONT_SCALABLE:
2304 case LyXRC::RC_SCREEN_FONT_SIZES:
2305 case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2306 case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2307 case LyXRC::RC_GEOMETRY_SESSION:
2308 case LyXRC::RC_SCREEN_ZOOM:
2309 case LyXRC::RC_SERVERPIPE:
2310 case LyXRC::RC_SET_COLOR:
2311 case LyXRC::RC_SHOW_BANNER:
2312 case LyXRC::RC_SPELL_COMMAND:
2313 case LyXRC::RC_TEMPDIRPATH:
2314 case LyXRC::RC_TEMPLATEPATH:
2315 case LyXRC::RC_TEX_ALLOWS_SPACES:
2316 case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2317 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2318 support::os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2320 case LyXRC::RC_UIFILE:
2321 case LyXRC::RC_USER_EMAIL:
2322 case LyXRC::RC_USER_NAME:
2323 case LyXRC::RC_USETEMPDIR:
2324 case LyXRC::RC_USE_ALT_LANG:
2325 case LyXRC::RC_USE_CONVERTER_CACHE:
2326 case LyXRC::RC_USE_ESC_CHARS:
2327 case LyXRC::RC_USE_INP_ENC:
2328 case LyXRC::RC_USE_PERS_DICT:
2329 case LyXRC::RC_USE_PIXMAP_CACHE:
2330 case LyXRC::RC_USE_SPELL_LIB:
2331 case LyXRC::RC_VIEWDVI_PAPEROPTION:
2332 case LyXRC::RC_SORT_LAYOUTS:
2333 case LyXRC::RC_VIEWER:
2334 case LyXRC::RC_LAST: