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.
24 #include "LayoutFile.h"
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 "DispatchResult.h"
38 #include "ErrorList.h"
40 #include "FuncRequest.h"
41 #include "FuncStatus.h"
42 #include "InsetIterator.h"
46 #include "LyXAction.h"
51 #include "Paragraph.h"
52 #include "ParagraphParameters.h"
53 #include "ParIterator.h"
56 #include "SpellChecker.h"
58 #include "frontends/alert.h"
59 #include "frontends/Application.h"
60 #include "frontends/KeySymbol.h"
61 #include "frontends/LyXView.h"
62 #include "frontends/Selection.h"
64 #include "support/debug.h"
65 #include "support/environment.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/gettext.h"
69 #include "support/lassert.h"
70 #include "support/lstrings.h"
71 #include "support/Package.h"
72 #include "support/convert.h"
73 #include "support/os.h"
79 using namespace lyx::support;
83 using frontend::LyXView;
85 namespace Alert = frontend::Alert;
92 //FIXME: bookmark handling is a frontend issue. This code should be transferred
93 // to GuiView and be GuiView and be window dependent.
94 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
96 LyXView * lv = theApp()->currentWindow();
98 if (!theSession().bookmarks().isValid(idx))
100 BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
101 LASSERT(!bm.filename.empty(), /**/);
102 string const file = bm.filename.absFilename();
103 // if the file is not opened, open it.
104 if (!theBufferList().exists(bm.filename)) {
106 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
110 // open may fail, so we need to test it again
111 if (!theBufferList().exists(bm.filename))
114 // bm can be changed when saving
115 BookmarksSection::Bookmark tmp = bm;
117 // Special case idx == 0 used for back-from-back jump navigation
119 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
121 // if the current buffer is not that one, switch to it.
122 if (!lv->documentBufferView()
123 || lv->documentBufferView()->buffer().fileName() != tmp.filename) {
126 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
129 // moveToPosition try paragraph id first and then paragraph (pit, pos).
130 if (!lv->documentBufferView()->moveToPosition(
131 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
138 // Cursor jump succeeded!
139 Cursor const & cur = lv->documentBufferView()->cursor();
140 pit_type new_pit = cur.pit();
141 pos_type new_pos = cur.pos();
142 int new_id = cur.paragraph().id();
144 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
145 // see http://www.lyx.org/trac/ticket/3092
146 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
147 || bm.top_id != new_id) {
148 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
149 new_pit, new_pos, new_id);
154 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
156 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
159 if (cmd.action == LFUN_NOACTION) {
160 flag.message(from_utf8(N_("Nothing to do")));
161 flag.setEnabled(false);
165 if (cmd.action == LFUN_UNKNOWN_ACTION) {
167 flag.setEnabled(false);
168 flag.message(from_utf8(N_("Unknown action")));
172 // I would really like to avoid having this switch and rather try to
173 // encode this in the function itself.
174 // -- And I'd rather let an inset decide which LFUNs it is willing
175 // to handle (Andre')
177 switch (cmd.action) {
179 // This could be used for the no-GUI version. The GUI version is handled in
180 // LyXView::getStatus(). See above.
182 case LFUN_BUFFER_WRITE:
183 case LFUN_BUFFER_WRITE_AS: {
184 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
185 enable = b && (b->isUnnamed() || !b->isClean());
190 case LFUN_BOOKMARK_GOTO: {
191 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
192 enable = theSession().bookmarks().isValid(num);
196 case LFUN_BOOKMARK_CLEAR:
197 enable = theSession().bookmarks().hasValid();
200 // this one is difficult to get right. As a half-baked
201 // solution, we consider only the first action of the sequence
202 case LFUN_COMMAND_SEQUENCE: {
203 // argument contains ';'-terminated commands
204 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
205 FuncRequest func(lyxaction.lookupFunc(firstcmd));
206 func.origin = cmd.origin;
207 flag = getStatus(func);
211 // we want to check if at least one of these is enabled
212 case LFUN_COMMAND_ALTERNATIVES: {
213 // argument contains ';'-terminated commands
214 string arg = to_utf8(cmd.argument());
215 while (!arg.empty()) {
217 arg = split(arg, first, ';');
218 FuncRequest func(lyxaction.lookupFunc(first));
219 func.origin = cmd.origin;
220 flag = getStatus(func);
221 // if this one is enabled, the whole thing is
230 string name = to_utf8(cmd.argument());
231 if (theTopLevelCmdDef().lock(name, func)) {
232 func.origin = cmd.origin;
233 flag = getStatus(func);
234 theTopLevelCmdDef().release(name);
236 // catch recursion or unknown command
237 // definition. all operations until the
238 // recursion or unknown command definition
239 // occurs are performed, so set the state to
246 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
248 case LFUN_PREFERENCES_SAVE:
249 case LFUN_BUFFER_SAVE_AS_DEFAULT:
250 case LFUN_DEBUG_LEVEL_SET:
251 // these are handled in our dispatch()
259 if (theApp()->getStatus(cmd, flag))
262 // Does the view know something?
263 LyXView * lv = theApp()->currentWindow();
268 if (lv->getStatus(cmd, flag))
271 BufferView * bv = lv->currentBufferView();
272 BufferView * doc_bv = lv->documentBufferView();
273 // If we do not have a BufferView, then other functions are disabled
278 // try the BufferView
279 bool decided = bv->getStatus(cmd, flag);
282 decided = bv->buffer().getStatus(cmd, flag);
283 if (!decided && doc_bv)
284 // try the Document Buffer
285 decided = doc_bv->buffer().getStatus(cmd, flag);
289 flag.setEnabled(false);
291 // the default error message if we disable the command
292 if (!flag.enabled() && flag.message().empty())
293 flag.message(from_utf8(N_("Command disabled")));
298 /// send a post-dispatch status message
299 static docstring sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
301 const bool verbose = (cmd.origin == FuncRequest::MENU
302 || cmd.origin == FuncRequest::TOOLBAR
303 || cmd.origin == FuncRequest::COMMANDBUFFER);
305 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
306 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
310 docstring dispatch_msg = msg;
311 if (!dispatch_msg.empty())
314 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
316 bool argsadded = false;
318 if (!cmd.argument().empty()) {
319 if (cmd.action != LFUN_UNKNOWN_ACTION) {
320 comname += ' ' + cmd.argument();
324 docstring const shortcuts = theTopLevelKeymap().
325 printBindings(cmd, KeySequence::ForGui);
327 if (!shortcuts.empty())
328 comname += ": " + shortcuts;
329 else if (!argsadded && !cmd.argument().empty())
330 comname += ' ' + cmd.argument();
332 if (!comname.empty()) {
333 comname = rtrim(comname);
334 dispatch_msg += '(' + rtrim(comname) + ')';
336 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
341 void LyXFunc::dispatch(FuncRequest const & cmd)
344 // redraw the screen at the end (first of the two drawing steps).
345 //This is done unless explicitely requested otherwise
346 dr.update(Update::FitCursor);
349 LyXView * lv = theApp()->currentWindow();
350 if (lv && lv->currentBufferView()) {
351 // BufferView::update() updates the ViewMetricsInfo and
352 // also initializes the position cache for all insets in
353 // (at least partially) visible top-level paragraphs.
354 // We will redraw the screen only if needed.
355 lv->currentBufferView()->processUpdateFlags(dr.update());
357 // Do we have a selection?
358 theSelection().haveSelection(
359 lv->currentBufferView()->cursor().selection());
367 void LyXFunc::dispatch(FuncRequest const & cmd, DispatchResult & dr)
369 string const argument = to_utf8(cmd.argument());
370 FuncCode const action = cmd.action;
372 LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
373 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
375 // we have not done anything wrong yet.
377 dispatch_buffer.erase();
379 LyXView * lv = theApp()->currentWindow();
381 FuncStatus const flag = getStatus(cmd);
382 if (!flag.enabled()) {
383 // We cannot use this function here
384 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
385 << lyxaction.getActionName(action)
386 << " [" << action << "] is disabled at this location");
387 //FIXME: pass this using the DispatchResult object
388 setErrorMessage(flag.message());
391 dr.dispatched(false);
392 dr.update(Update::None);
396 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
397 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
403 string rest = split(argument, countstr, ' ');
404 istringstream is(countstr);
407 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
408 for (int i = 0; i < count; ++i)
409 dispatch(lyxaction.lookupFunc(rest));
413 case LFUN_COMMAND_SEQUENCE: {
414 // argument contains ';'-terminated commands
415 string arg = argument;
416 // FIXME: this LFUN should also work without any view.
417 Buffer * buffer = (lv && lv->documentBufferView())
418 ? &(lv->documentBufferView()->buffer()) : 0;
420 buffer->undo().beginUndoGroup();
421 while (!arg.empty()) {
423 arg = split(arg, first, ';');
424 FuncRequest func(lyxaction.lookupFunc(first));
425 func.origin = cmd.origin;
428 // the buffer may have been closed by one action
429 if (theBufferList().isLoaded(buffer))
430 buffer->undo().endUndoGroup();
434 case LFUN_COMMAND_ALTERNATIVES: {
435 // argument contains ';'-terminated commands
436 string arg = argument;
437 while (!arg.empty()) {
439 arg = split(arg, first, ';');
440 FuncRequest func(lyxaction.lookupFunc(first));
441 func.origin = cmd.origin;
442 FuncStatus stat = getStatus(func);
443 if (stat.enabled()) {
453 if (theTopLevelCmdDef().lock(argument, func)) {
454 func.origin = cmd.origin;
456 theTopLevelCmdDef().release(argument);
458 if (func.action == LFUN_UNKNOWN_ACTION) {
459 // unknown command definition
460 lyxerr << "Warning: unknown command definition `"
464 // recursion detected
465 lyxerr << "Warning: Recursion in the command definition `"
466 << argument << "' detected"
473 case LFUN_PREFERENCES_SAVE: {
474 lyxrc.write(makeAbsPath("preferences",
475 package().user_support().absFilename()),
480 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
482 addName(addPath(package().user_support().absFilename(), "templates/"),
484 Buffer defaults(fname);
486 istringstream ss(argument);
489 int const unknown_tokens = defaults.readHeader(lex);
491 if (unknown_tokens != 0) {
492 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
493 << unknown_tokens << " unknown token"
494 << (unknown_tokens == 1 ? "" : "s")
498 if (defaults.writeFile(FileName(defaults.absFileName())))
499 setMessage(bformat(_("Document defaults saved in %1$s"),
500 makeDisplayPath(fname)));
502 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
506 case LFUN_BOOKMARK_GOTO:
507 // go to bookmark, open unopened file and switch to buffer if necessary
508 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
509 dr.update(Update::FitCursor);
512 case LFUN_BOOKMARK_CLEAR:
513 theSession().bookmarks().clear();
516 case LFUN_DEBUG_LEVEL_SET:
517 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
521 LASSERT(theApp(), /**/);
522 // Let the frontend dispatch its own actions.
523 theApp()->dispatch(cmd, dr);
525 // Nothing more to do.
528 // Everything below is only for active window
532 // Let the current LyXView dispatch its own actions.
533 //FIXME: pass dr to LyXView::dispatch
534 if (lv->dispatch(cmd)) {
535 BufferView * bv = lv->currentBufferView();
537 dr = bv->cursor().result();
541 BufferView * bv = lv->currentBufferView();
544 // Let the current BufferView dispatch its own actions.
545 bv->dispatch(cmd, dr);
549 BufferView * doc_bv = lv->documentBufferView();
550 // Try with the document BufferView dispatch if any.
552 doc_bv->dispatch(cmd, dr);
557 // OK, so try the current Buffer itself...
558 bv->buffer().dispatch(cmd, dr);
562 // and with the document Buffer.
564 doc_bv->buffer().dispatch(cmd, dr);
569 // Let the current Cursor dispatch its own actions.
570 Cursor old = bv->cursor();
571 bv->cursor().getPos(cursorPosBeforeDispatchX_,
572 cursorPosBeforeDispatchY_);
573 bv->cursor().dispatch(cmd);
575 // notify insets we just left
576 if (bv->cursor() != old) {
578 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
580 bv->cursor().fixIfBroken();
583 // update completion. We do it here and not in
584 // processKeySym to avoid another redraw just for a
585 // changed inline completion
586 if (cmd.origin == FuncRequest::KEYBOARD) {
587 if (cmd.action == LFUN_SELF_INSERT
588 || (cmd.action == LFUN_ERT_INSERT && bv->cursor().inMathed()))
589 lv->updateCompletion(bv->cursor(), true, true);
590 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
591 lv->updateCompletion(bv->cursor(), false, true);
593 lv->updateCompletion(bv->cursor(), false, false);
596 dr = bv->cursor().result();
599 // if we executed a mutating lfun, mark the buffer as dirty
600 Buffer * doc_buffer = (lv && lv->documentBufferView())
601 ? &(lv->documentBufferView()->buffer()) : 0;
602 if (doc_buffer && theBufferList().isLoaded(doc_buffer)
604 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
605 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
606 lv->currentBufferView()->buffer().markDirty();
609 // Some messages may already be translated, so we cannot use _()
610 lv->message(sendDispatchMessage(
611 translateIfPossible(getMessage()), cmd));
616 // Each LyXView should have it's own message method. lyxview and
617 // the minibuffer would use the minibuffer, but lyxserver would
618 // send an ERROR signal to its client. Alejandro 970603
619 // This function is bit problematic when it comes to NLS, to make the
620 // lyx servers client be language indepenent we must not translate
621 // strings sent to this func.
622 void LyXFunc::setErrorMessage(docstring const & m) const
629 void LyXFunc::setMessage(docstring const & m) const