]> git.lyx.org Git - lyx.git/blob - src/LyXFunc.cpp
Get rid of some unneeded use of LyXView in LyXFunc::dispatch().
[lyx.git] / src / LyXFunc.cpp
1 /**
2  * \file LyXFunc.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Allan Rae
13  * \author Dekel Tsur
14  * \author Martin Vermeer
15  * \author Jürgen Vigna
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "LyXFunc.h"
23
24 #include "LayoutFile.h"
25 #include "BranchList.h"
26 #include "buffer_funcs.h"
27 #include "Buffer.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CmdDef.h"
32 #include "Color.h"
33 #include "Converter.h"
34 #include "Cursor.h"
35 #include "CutAndPaste.h"
36 #include "DispatchResult.h"
37 #include "Encoding.h"
38 #include "ErrorList.h"
39 #include "Format.h"
40 #include "FuncRequest.h"
41 #include "FuncStatus.h"
42 #include "InsetIterator.h"
43 #include "Intl.h"
44 #include "KeyMap.h"
45 #include "Language.h"
46 #include "LaTeXFeatures.h"
47 #include "Lexer.h"
48 #include "LyXAction.h"
49 #include "lyxfind.h"
50 #include "LyX.h"
51 #include "LyXRC.h"
52 #include "LyXVC.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "Row.h"
57 #include "Server.h"
58 #include "Session.h"
59 #include "SpellChecker.h"
60
61 #include "frontends/alert.h"
62 #include "frontends/Application.h"
63 #include "frontends/KeySymbol.h"
64 #include "frontends/LyXView.h"
65 #include "frontends/Selection.h"
66
67 #include "support/debug.h"
68 #include "support/environment.h"
69 #include "support/FileName.h"
70 #include "support/filetools.h"
71 #include "support/gettext.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/Path.h"
75 #include "support/Package.h"
76 #include "support/Systemcall.h"
77 #include "support/convert.h"
78 #include "support/os.h"
79
80 #include <sstream>
81 #include <vector>
82
83 using namespace std;
84 using namespace lyx::support;
85
86 namespace lyx {
87
88 using frontend::LyXView;
89
90 namespace Alert = frontend::Alert;
91
92 namespace {
93
94
95 // This function runs "configure" and then rereads lyx.defaults to
96 // reconfigure the automatic settings.
97 void reconfigure(LyXView * lv, string const & option)
98 {
99         // emit message signal.
100         if (lv)
101                 lv->message(_("Running configure..."));
102
103         // Run configure in user lyx directory
104         PathChanger p(package().user_support());
105         string configure_command = package().configure_command();
106         configure_command += option;
107         Systemcall one;
108         int ret = one.startscript(Systemcall::Wait, configure_command);
109         p.pop();
110         // emit message signal.
111         if (lv)
112                 lv->message(_("Reloading configuration..."));
113         lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
114         // Re-read packages.lst
115         LaTeXFeatures::getAvailable();
116
117         if (ret)
118                 Alert::information(_("System reconfiguration failed"),
119                            _("The system reconfiguration has failed.\n"
120                                   "Default textclass is used but LyX may "
121                                   "not be able to work properly.\n"
122                                   "Please reconfigure again if needed."));
123         else
124
125                 Alert::information(_("System reconfigured"),
126                            _("The system has been reconfigured.\n"
127                              "You need to restart LyX to make use of any\n"
128                              "updated document class specifications."));
129 }
130
131 }
132
133
134 LyXFunc::LyXFunc()
135         : encoded_last_key(0), meta_fake_bit(NoModifier)
136 {
137 }
138
139
140 void LyXFunc::initKeySequences(KeyMap * kb)
141 {
142         keyseq = KeySequence(kb, kb);
143         cancel_meta_seq = KeySequence(kb, kb);
144 }
145
146
147 void LyXFunc::handleKeyFunc(FuncCode action)
148 {
149         char_type c = encoded_last_key;
150
151         if (keyseq.length())
152                 c = 0;
153         LyXView * lv = theApp()->currentWindow();
154         LASSERT(lv && lv->currentBufferView(), /**/);
155         BufferView * bv = lv->currentBufferView();
156         bv->getIntl().getTransManager().deadkey(
157                 c, get_accent(action).accent, bv->cursor().innerText(),
158                 bv->cursor());
159         // Need to clear, in case the minibuffer calls these
160         // actions
161         keyseq.clear();
162         // copied verbatim from do_accent_char
163         bv->cursor().resetAnchor();
164         bv->processUpdateFlags(Update::FitCursor);
165 }
166
167 //FIXME: bookmark handling is a frontend issue. This code should be transferred
168 // to GuiView and be GuiView and be window dependent.
169 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
170 {
171         LyXView * lv = theApp()->currentWindow();
172         LASSERT(lv, /**/);
173         if (!theSession().bookmarks().isValid(idx))
174                 return;
175         BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
176         LASSERT(!bm.filename.empty(), /**/);
177         string const file = bm.filename.absFilename();
178         // if the file is not opened, open it.
179         if (!theBufferList().exists(bm.filename)) {
180                 if (openFile)
181                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
182                 else
183                         return;
184         }
185         // open may fail, so we need to test it again
186         if (!theBufferList().exists(bm.filename))
187                 return;
188
189         // bm can be changed when saving
190         BookmarksSection::Bookmark tmp = bm;
191
192         // Special case idx == 0 used for back-from-back jump navigation
193         if (idx == 0)
194                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
195
196         // if the current buffer is not that one, switch to it.
197         if (!lv->documentBufferView()
198                 || lv->documentBufferView()->buffer().fileName() != tmp.filename) {
199                 if (!switchToBuffer)
200                         return;
201                 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
202         }
203
204         // moveToPosition try paragraph id first and then paragraph (pit, pos).
205         if (!lv->documentBufferView()->moveToPosition(
206                 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
207                 return;
208
209         // bm changed
210         if (idx == 0)
211                 return;
212
213         // Cursor jump succeeded!
214         Cursor const & cur = lv->documentBufferView()->cursor();
215         pit_type new_pit = cur.pit();
216         pos_type new_pos = cur.pos();
217         int new_id = cur.paragraph().id();
218
219         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
220         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
221         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos 
222                 || bm.top_id != new_id) {
223                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
224                         new_pit, new_pos, new_id);
225         }
226 }
227
228
229 void LyXFunc::processKeySym(KeySymbol const & keysym, KeyModifier state)
230 {
231         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
232
233         LyXView * lv = theApp()->currentWindow();
234
235         // Do nothing if we have nothing (JMarc)
236         if (!keysym.isOK()) {
237                 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
238                 lv->restartCursor();
239                 return;
240         }
241
242         if (keysym.isModifier()) {
243                 LYXERR(Debug::KEY, "isModifier true");
244                 if (lv)
245                         lv->restartCursor();
246                 return;
247         }
248
249         //Encoding const * encoding = lv->documentBufferView()->cursor().getEncoding();
250         //encoded_last_key = keysym.getISOEncoded(encoding ? encoding->name() : "");
251         // FIXME: encoded_last_key shadows the member variable of the same
252         // name. Is that intended?
253         char_type encoded_last_key = keysym.getUCSEncoded();
254
255         // Do a one-deep top-level lookup for
256         // cancel and meta-fake keys. RVDK_PATCH_5
257         cancel_meta_seq.reset();
258
259         FuncRequest func = cancel_meta_seq.addkey(keysym, state);
260         LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
261
262         // When not cancel or meta-fake, do the normal lookup.
263         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
264         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
265         if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
266                 // remove Caps Lock and Mod2 as a modifiers
267                 func = keyseq.addkey(keysym, (state | meta_fake_bit));
268                 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
269         }
270
271         // Dont remove this unless you know what you are doing.
272         meta_fake_bit = NoModifier;
273
274         // Can this happen now ?
275         if (func.action == LFUN_NOACTION)
276                 func = FuncRequest(LFUN_COMMAND_PREFIX);
277
278         LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
279                 << keyseq.print(KeySequence::Portable) << ']');
280
281         // already here we know if it any point in going further
282         // why not return already here if action == -1 and
283         // num_bytes == 0? (Lgb)
284
285         if (keyseq.length() > 1)
286                 lv->message(keyseq.print(KeySequence::ForGui));
287
288
289         // Maybe user can only reach the key via holding down shift.
290         // Let's see. But only if shift is the only modifier
291         if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
292                 LYXERR(Debug::KEY, "Trying without shift");
293                 func = keyseq.addkey(keysym, NoModifier);
294                 LYXERR(Debug::KEY, "Action now " << func.action);
295         }
296
297         if (func.action == LFUN_UNKNOWN_ACTION) {
298                 // Hmm, we didn't match any of the keysequences. See
299                 // if it's normal insertable text not already covered
300                 // by a binding
301                 if (keysym.isText() && keyseq.length() == 1) {
302                         LYXERR(Debug::KEY, "isText() is true, inserting.");
303                         func = FuncRequest(LFUN_SELF_INSERT,
304                                            FuncRequest::KEYBOARD);
305                 } else {
306                         LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
307                         lv->message(_("Unknown function."));
308                         lv->restartCursor();
309                         return;
310                 }
311         }
312
313         if (func.action == LFUN_SELF_INSERT) {
314                 if (encoded_last_key != 0) {
315                         docstring const arg(1, encoded_last_key);
316                         dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
317                                              FuncRequest::KEYBOARD));
318                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
319                 }
320         } else {
321                 dispatch(func);
322                 if (!lv)
323                         return;
324         }
325 }
326
327
328 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
329 {
330         //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
331         FuncStatus flag;
332
333         if (cmd.action == LFUN_NOACTION) {
334                 flag.message(from_utf8(N_("Nothing to do")));
335                 flag.setEnabled(false);
336                 return flag;
337         }
338
339         switch (cmd.action) {
340         case LFUN_UNKNOWN_ACTION:
341                 flag.unknown(true);
342                 flag.setEnabled(false);
343                 break;
344
345         default:
346                 break;
347         }
348
349         if (flag.unknown()) {
350                 flag.message(from_utf8(N_("Unknown action")));
351                 return flag;
352         }
353
354         if (!flag.enabled()) {
355                 if (flag.message().empty())
356                         flag.message(from_utf8(N_("Command disabled")));
357                 return flag;
358         }
359
360         // I would really like to avoid having this switch and rather try to
361         // encode this in the function itself.
362         // -- And I'd rather let an inset decide which LFUNs it is willing
363         // to handle (Andre')
364         bool enable = true;
365         switch (cmd.action) {
366
367         // This could be used for the no-GUI version. The GUI version is handled in
368         // LyXView::getStatus(). See above.
369         /*
370         case LFUN_BUFFER_WRITE:
371         case LFUN_BUFFER_WRITE_AS: {
372                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
373                 enable = b && (b->isUnnamed() || !b->isClean());
374                 break;
375         }
376         */
377
378         case LFUN_BOOKMARK_GOTO: {
379                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
380                 enable = theSession().bookmarks().isValid(num);
381                 break;
382         }
383
384         case LFUN_BOOKMARK_CLEAR:
385                 enable = theSession().bookmarks().hasValid();
386                 break;
387
388         // this one is difficult to get right. As a half-baked
389         // solution, we consider only the first action of the sequence
390         case LFUN_COMMAND_SEQUENCE: {
391                 // argument contains ';'-terminated commands
392                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
393                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
394                 func.origin = cmd.origin;
395                 flag = getStatus(func);
396                 break;
397         }
398
399         // we want to check if at least one of these is enabled
400         case LFUN_COMMAND_ALTERNATIVES: {
401                 // argument contains ';'-terminated commands
402                 string arg = to_utf8(cmd.argument());
403                 while (!arg.empty()) {
404                         string first;
405                         arg = split(arg, first, ';');
406                         FuncRequest func(lyxaction.lookupFunc(first));
407                         func.origin = cmd.origin;
408                         flag = getStatus(func);
409                         // if this one is enabled, the whole thing is
410                         if (flag.enabled())
411                                 break;
412                 }
413                 break;
414         }
415
416         case LFUN_CALL: {
417                 FuncRequest func;
418                 string name = to_utf8(cmd.argument());
419                 if (theTopLevelCmdDef().lock(name, func)) {
420                         func.origin = cmd.origin;
421                         flag = getStatus(func);
422                         theTopLevelCmdDef().release(name);
423                 } else {
424                         // catch recursion or unknown command
425                         // definition. all operations until the
426                         // recursion or unknown command definition
427                         // occurs are performed, so set the state to
428                         // enabled
429                         enable = true;
430                 }
431                 break;
432         }
433
434         case LFUN_COMMAND_PREFIX:
435         case LFUN_CANCEL:
436         case LFUN_META_PREFIX:
437         case LFUN_RECONFIGURE:
438         case LFUN_DROP_LAYOUTS_CHOICE:
439         case LFUN_SERVER_GET_FILENAME:
440         case LFUN_SERVER_NOTIFY:
441         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
442         case LFUN_REPEAT:
443         case LFUN_PREFERENCES_SAVE:
444         case LFUN_INSET_EDIT:
445         case LFUN_BUFFER_SAVE_AS_DEFAULT:
446         case LFUN_LYXRC_APPLY:
447                 // these are handled in our dispatch()
448                 break;
449
450         default:
451                 if (!theApp()) {
452                         enable = false;
453                         break;
454                 }
455                 if (theApp()->getStatus(cmd, flag))
456                         break;
457
458                 // Does the view know something?
459                 LyXView * lv = theApp()->currentWindow();
460                 if (!lv) {
461                         enable = false;
462                         break;
463                 }
464                 if (lv->getStatus(cmd, flag))
465                         break;
466
467                 BufferView * bv = lv->currentBufferView();
468                 BufferView * doc_bv = lv->documentBufferView();
469                 // If we do not have a BufferView, then other functions are disabled
470                 if (!bv) {
471                         enable = false;
472                         break;
473                 }
474                 // try the BufferView
475                 bool decided = bv->getStatus(cmd, flag);
476                 if (!decided)
477                         // try the Buffer
478                         decided = bv->buffer().getStatus(cmd, flag);
479                 if (!decided && doc_bv)
480                         // try the Document Buffer
481                         decided = doc_bv->buffer().getStatus(cmd, flag);
482         }
483
484         if (!enable)
485                 flag.setEnabled(false);
486
487         // the default error message if we disable the command
488         if (!flag.enabled() && flag.message().empty())
489                 flag.message(from_utf8(N_("Command disabled")));
490
491         return flag;
492 }
493
494
495 namespace {
496
497 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
498
499 } //namespace anon
500
501
502 void LyXFunc::dispatch(FuncRequest const & cmd)
503 {
504         string const argument = to_utf8(cmd.argument());
505         FuncCode const action = cmd.action;
506
507         LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
508         //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
509
510         // we have not done anything wrong yet.
511         errorstat = false;
512         dispatch_buffer.erase();
513
514         // redraw the screen at the end (first of the two drawing steps).
515         //This is done unless explicitely requested otherwise
516         Update::flags updateFlags = Update::FitCursor;
517
518         LyXView * lv = theApp()->currentWindow();
519
520         FuncStatus const flag = getStatus(cmd);
521         if (!flag.enabled()) {
522                 // We cannot use this function here
523                 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
524                        << lyxaction.getActionName(action)
525                        << " [" << action << "] is disabled at this location");
526                 setErrorMessage(flag.message());
527                 if (lv)
528                         lv->restartCursor();
529         } else {
530                 Buffer * buffer = 0;
531                 if (lv && lv->currentBufferView())
532                         buffer = &lv->currentBufferView()->buffer();
533                 switch (action) {
534
535                 case LFUN_COMMAND_PREFIX:
536                         dispatch(FuncRequest(LFUN_MESSAGE, keyseq.printOptions(true)));
537                         break;
538
539                 case LFUN_CANCEL:
540                         keyseq.reset();
541                         meta_fake_bit = NoModifier;
542                         if (buffer)
543                                 // cancel any selection
544                                 dispatch(FuncRequest(LFUN_MARK_OFF));
545                         setMessage(from_ascii(N_("Cancel")));
546                         break;
547
548                 case LFUN_META_PREFIX:
549                         meta_fake_bit = AltModifier;
550                         setMessage(keyseq.print(KeySequence::ForGui));
551                         break;
552
553                 // --- Menus -----------------------------------------------
554                 case LFUN_RECONFIGURE:
555                         // argument is any additional parameter to the configure.py command
556                         reconfigure(lv, argument);
557                         break;
558
559                 // --- lyxserver commands ----------------------------
560                 case LFUN_SERVER_GET_FILENAME:
561                         LASSERT(lv && buffer, /**/);
562                         setMessage(from_utf8(buffer->absFileName()));
563                         LYXERR(Debug::INFO, "FNAME["
564                                 << buffer->absFileName() << ']');
565                         break;
566
567                 case LFUN_SERVER_NOTIFY:
568                         dispatch_buffer = keyseq.print(KeySequence::Portable);
569                         theServer().notifyClient(to_utf8(dispatch_buffer));
570                         break;
571
572                 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
573                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
574                         break;
575
576                 case LFUN_REPEAT: {
577                         // repeat command
578                         string countstr;
579                         string rest = split(argument, countstr, ' ');
580                         istringstream is(countstr);
581                         int count = 0;
582                         is >> count;
583                         //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
584                         for (int i = 0; i < count; ++i)
585                                 dispatch(lyxaction.lookupFunc(rest));
586                         break;
587                 }
588
589                 case LFUN_COMMAND_SEQUENCE: {
590                         // argument contains ';'-terminated commands
591                         string arg = argument;
592                         if (theBufferList().isLoaded(buffer))
593                                 buffer->undo().beginUndoGroup();
594                         while (!arg.empty()) {
595                                 string first;
596                                 arg = split(arg, first, ';');
597                                 FuncRequest func(lyxaction.lookupFunc(first));
598                                 func.origin = cmd.origin;
599                                 dispatch(func);
600                         }
601                         if (theBufferList().isLoaded(buffer))
602                                 buffer->undo().endUndoGroup();
603                         break;
604                 }
605
606                 case LFUN_COMMAND_ALTERNATIVES: {
607                         // argument contains ';'-terminated commands
608                         string arg = argument;
609                         while (!arg.empty()) {
610                                 string first;
611                                 arg = split(arg, first, ';');
612                                 FuncRequest func(lyxaction.lookupFunc(first));
613                                 func.origin = cmd.origin;
614                                 FuncStatus stat = getStatus(func);
615                                 if (stat.enabled()) {
616                                         dispatch(func);
617                                         break;
618                                 }
619                         }
620                         break;
621                 }
622
623                 case LFUN_CALL: {
624                         FuncRequest func;
625                         if (theTopLevelCmdDef().lock(argument, func)) {
626                                 func.origin = cmd.origin;
627                                 dispatch(func);
628                                 theTopLevelCmdDef().release(argument);
629                         } else {
630                                 if (func.action == LFUN_UNKNOWN_ACTION) {
631                                         // unknown command definition
632                                         lyxerr << "Warning: unknown command definition `"
633                                                    << argument << "'"
634                                                    << endl;
635                                 } else {
636                                         // recursion detected
637                                         lyxerr << "Warning: Recursion in the command definition `"
638                                                    << argument << "' detected"
639                                                    << endl;
640                                 }
641                         }
642                         break;
643                 }
644
645                 case LFUN_PREFERENCES_SAVE: {
646                         lyxrc.write(makeAbsPath("preferences",
647                                                 package().user_support().absFilename()),
648                                     false);
649                         break;
650                 }
651
652                 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
653                         string const fname =
654                                 addName(addPath(package().user_support().absFilename(), "templates/"),
655                                         "defaults.lyx");
656                         Buffer defaults(fname);
657
658                         istringstream ss(argument);
659                         Lexer lex;
660                         lex.setStream(ss);
661                         int const unknown_tokens = defaults.readHeader(lex);
662
663                         if (unknown_tokens != 0) {
664                                 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
665                                        << unknown_tokens << " unknown token"
666                                        << (unknown_tokens == 1 ? "" : "s")
667                                        << endl;
668                         }
669
670                         if (defaults.writeFile(FileName(defaults.absFileName())))
671                                 setMessage(bformat(_("Document defaults saved in %1$s"),
672                                                    makeDisplayPath(fname)));
673                         else
674                                 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
675                         break;
676                 }
677
678                 case LFUN_LYXRC_APPLY: {
679                         // reset active key sequences, since the bindings
680                         // are updated (bug 6064)
681                         keyseq.reset();
682                         LyXRC const lyxrc_orig = lyxrc;
683
684                         istringstream ss(argument);
685                         bool const success = lyxrc.read(ss) == 0;
686
687                         if (!success) {
688                                 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
689                                        << "Unable to read lyxrc data"
690                                        << endl;
691                                 break;
692                         }
693
694                         actOnUpdatedPrefs(lyxrc_orig, lyxrc);
695
696                         setSpellChecker();
697
698                         theApp()->resetGui();
699
700                         /// We force the redraw in any case because there might be
701                         /// some screen font changes.
702                         /// FIXME: only the current view will be updated. the Gui
703                         /// class is able to furnish the list of views.
704                         updateFlags = Update::Force;
705                         break;
706                 }
707
708                 case LFUN_BOOKMARK_GOTO:
709                         // go to bookmark, open unopened file and switch to buffer if necessary
710                         gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
711                         updateFlags = Update::FitCursor;
712                         break;
713
714                 case LFUN_BOOKMARK_CLEAR:
715                         theSession().bookmarks().clear();
716                         break;
717
718                 default:
719                         LASSERT(theApp(), /**/);
720                         // Let the frontend dispatch its own actions.
721                         if (theApp()->dispatch(cmd))
722                                 // Nothing more to do.
723                                 return;
724
725                         // Everything below is only for active window
726                         if (lv == 0)
727                                 break;
728
729                         // Start an undo group. This may be needed for
730                         // some stuff like inset-apply on labels.
731                         if (theBufferList().isLoaded(buffer))
732                                 buffer->undo().beginUndoGroup();
733                                 
734                         // Let the current LyXView dispatch its own actions.
735                         if (lv->dispatch(cmd)) {
736                                 BufferView * bv = lv->currentBufferView();
737                                 if (bv) {
738                                         buffer = &(bv->buffer());
739                                         updateFlags = bv->cursor().result().update();
740                                         if (theBufferList().isLoaded(buffer))
741                                                 buffer->undo().endUndoGroup();
742                                 }
743                                 break;
744                         }
745
746                         BufferView * bv = lv->currentBufferView();
747                         LASSERT(bv, /**/);
748
749                         // Let the current BufferView dispatch its own actions.
750                         if (bv->dispatch(cmd)) {
751                                 // The BufferView took care of its own updates if needed.
752                                 buffer = &(bv->buffer());
753                                 updateFlags = Update::None;
754                                 if (theBufferList().isLoaded(buffer))
755                                         buffer->undo().endUndoGroup();
756                                 break;
757                         }
758
759                         BufferView * doc_bv = lv->documentBufferView();
760                         // Try with the document BufferView dispatch if any.
761                         if (doc_bv && doc_bv->dispatch(cmd)) {
762                                 // The BufferView took care of its own updates if needed.
763                                 buffer = &(doc_bv->buffer());
764                                 updateFlags = Update::None;
765                                 if (theBufferList().isLoaded(buffer))
766                                         buffer->undo().endUndoGroup();
767                                 break;
768                         }
769
770                         // OK, so try the current Buffer itself...
771                         DispatchResult dr;
772                         bv->buffer().dispatch(cmd, dr);
773                         if (dr.dispatched()) {
774                                 updateFlags = dr.update();
775                                 break;
776                         }
777                         // and with the document Buffer.
778                         if (doc_bv) {
779                                 doc_bv->buffer().dispatch(cmd, dr);
780                                 if (dr.dispatched()) {
781                                         updateFlags = dr.update();
782                                         break;
783                                 }
784                         }
785
786                         // Is this a function that acts on inset at point?
787                         Inset * inset = bv->cursor().nextInset();
788                         if (lyxaction.funcHasFlag(action, LyXAction::AtPoint)
789                             && inset) {
790                                 bv->cursor().result().dispatched(true);
791                                 bv->cursor().result().update(Update::FitCursor | Update::Force);
792                                 FuncRequest tmpcmd = cmd;
793                                 inset->dispatch(bv->cursor(), tmpcmd);
794                                 if (bv->cursor().result().dispatched()) {
795                                         updateFlags = bv->cursor().result().update();
796                                         break;
797                                 }
798                         }
799
800                         // Let the current Cursor dispatch its own actions.
801                         Cursor old = bv->cursor();
802                         bv->cursor().getPos(cursorPosBeforeDispatchX_,
803                                                 cursorPosBeforeDispatchY_);
804                         bv->cursor().dispatch(cmd);
805
806                         // notify insets we just left
807                         if (bv->cursor() != old) {
808                                 old.fixIfBroken();
809                                 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
810                                 if (badcursor)
811                                         bv->cursor().fixIfBroken();
812                         }
813
814                         if (theBufferList().isLoaded(buffer))
815                                 buffer->undo().endUndoGroup();
816
817                         // update completion. We do it here and not in
818                         // processKeySym to avoid another redraw just for a
819                         // changed inline completion
820                         if (cmd.origin == FuncRequest::KEYBOARD) {
821                                 if (cmd.action == LFUN_SELF_INSERT
822                                     || (cmd.action == LFUN_ERT_INSERT && bv->cursor().inMathed()))
823                                         lv->updateCompletion(bv->cursor(), true, true);
824                                 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
825                                         lv->updateCompletion(bv->cursor(), false, true);
826                                 else
827                                         lv->updateCompletion(bv->cursor(), false, false);
828                         }
829
830                         updateFlags = bv->cursor().result().update();
831                 }
832
833                 // if we executed a mutating lfun, mark the buffer as dirty
834                 if (theBufferList().isLoaded(buffer) && flag.enabled()
835                     && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
836                     && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
837                         buffer->markDirty();                    
838
839                 if (lv && lv->currentBufferView()) {
840                         // BufferView::update() updates the ViewMetricsInfo and
841                         // also initializes the position cache for all insets in
842                         // (at least partially) visible top-level paragraphs.
843                         // We will redraw the screen only if needed.
844                         lv->currentBufferView()->processUpdateFlags(updateFlags);
845
846                         // Do we have a selection?
847                         theSelection().haveSelection(
848                                 lv->currentBufferView()->cursor().selection());
849                         
850                         // update gui
851                         lv->restartCursor();
852                 }
853         }
854         if (lv) {
855                 // Some messages may already be translated, so we cannot use _()
856                 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
857         }
858 }
859
860
861 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
862 {
863         const bool verbose = (cmd.origin == FuncRequest::MENU
864                               || cmd.origin == FuncRequest::TOOLBAR
865                               || cmd.origin == FuncRequest::COMMANDBUFFER);
866
867         LyXView * lv = theApp()->currentWindow();
868         if (cmd.action == LFUN_SELF_INSERT || !verbose) {
869                 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
870                 if (!msg.empty())
871                         lv->message(msg);
872                 return;
873         }
874
875         docstring dispatch_msg = msg;
876         if (!dispatch_msg.empty())
877                 dispatch_msg += ' ';
878
879         docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
880
881         bool argsadded = false;
882
883         if (!cmd.argument().empty()) {
884                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
885                         comname += ' ' + cmd.argument();
886                         argsadded = true;
887                 }
888         }
889
890         docstring const shortcuts = theTopLevelKeymap().printBindings(cmd, KeySequence::ForGui);
891
892         if (!shortcuts.empty())
893                 comname += ": " + shortcuts;
894         else if (!argsadded && !cmd.argument().empty())
895                 comname += ' ' + cmd.argument();
896
897         if (!comname.empty()) {
898                 comname = rtrim(comname);
899                 dispatch_msg += '(' + rtrim(comname) + ')';
900         }
901
902         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
903         if (!dispatch_msg.empty())
904                 lv->message(dispatch_msg);
905 }
906
907
908 // Each LyXView should have it's own message method. lyxview and
909 // the minibuffer would use the minibuffer, but lyxserver would
910 // send an ERROR signal to its client.  Alejandro 970603
911 // This function is bit problematic when it comes to NLS, to make the
912 // lyx servers client be language indepenent we must not translate
913 // strings sent to this func.
914 void LyXFunc::setErrorMessage(docstring const & m) const
915 {
916         dispatch_buffer = m;
917         errorstat = true;
918 }
919
920
921 void LyXFunc::setMessage(docstring const & m) const
922 {
923         dispatch_buffer = m;
924 }
925
926
927 docstring LyXFunc::viewStatusMessage()
928 {
929         // When meta-fake key is pressed, show the key sequence so far + "M-".
930         if (wasMetaKey())
931                 return keyseq.print(KeySequence::ForGui) + "M-";
932
933         // Else, when a non-complete key sequence is pressed,
934         // show the available options.
935         if (keyseq.length() > 0 && !keyseq.deleted())
936                 return keyseq.printOptions(true);
937
938         LyXView * lv = theApp()->currentWindow();
939         LASSERT(lv, /**/);
940         if (!lv->currentBufferView())
941                 return _("Welcome to LyX!");
942
943         return lv->currentBufferView()->cursor().currentState();
944 }
945
946
947 bool LyXFunc::wasMetaKey() const
948 {
949         return (meta_fake_bit != NoModifier);
950 }
951
952
953 namespace {
954
955 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
956 {
957         // Why the switch you might ask. It is a trick to ensure that all
958         // the elements in the LyXRCTags enum is handled. As you can see
959         // there are no breaks at all. So it is just a huge fall-through.
960         // The nice thing is that we will get a warning from the compiler
961         // if we forget an element.
962         LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
963         switch (tag) {
964         case LyXRC::RC_ACCEPT_COMPOUND:
965         case LyXRC::RC_ALT_LANG:
966         case LyXRC::RC_PLAINTEXT_LINELEN:
967         case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
968         case LyXRC::RC_AUTOCORRECTION_MATH:
969         case LyXRC::RC_AUTOREGIONDELETE:
970         case LyXRC::RC_AUTORESET_OPTIONS:
971         case LyXRC::RC_AUTOSAVE:
972         case LyXRC::RC_AUTO_NUMBER:
973         case LyXRC::RC_BACKUPDIR_PATH:
974         case LyXRC::RC_BIBTEX_ALTERNATIVES:
975         case LyXRC::RC_BIBTEX_COMMAND:
976         case LyXRC::RC_BINDFILE:
977         case LyXRC::RC_CHECKLASTFILES:
978         case LyXRC::RC_COMPLETION_CURSOR_TEXT:
979         case LyXRC::RC_COMPLETION_INLINE_DELAY:
980         case LyXRC::RC_COMPLETION_INLINE_DOTS:
981         case LyXRC::RC_COMPLETION_INLINE_MATH:
982         case LyXRC::RC_COMPLETION_INLINE_TEXT:
983         case LyXRC::RC_COMPLETION_POPUP_AFTER_COMPLETE:
984         case LyXRC::RC_COMPLETION_POPUP_DELAY:
985         case LyXRC::RC_COMPLETION_POPUP_MATH:
986         case LyXRC::RC_COMPLETION_POPUP_TEXT:
987         case LyXRC::RC_USELASTFILEPOS:
988         case LyXRC::RC_LOADSESSION:
989         case LyXRC::RC_CHKTEX_COMMAND:
990         case LyXRC::RC_CONVERTER:
991         case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
992         case LyXRC::RC_COPIER:
993         case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
994         case LyXRC::RC_SCROLL_BELOW_DOCUMENT:
995         case LyXRC::RC_DATE_INSERT_FORMAT:
996         case LyXRC::RC_DEFAULT_LANGUAGE:
997         case LyXRC::RC_GUI_LANGUAGE:
998         case LyXRC::RC_DEFAULT_PAPERSIZE:
999         case LyXRC::RC_DEFAULT_VIEW_FORMAT:
1000         case LyXRC::RC_DEFFILE:
1001         case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
1002         case LyXRC::RC_DISPLAY_GRAPHICS:
1003         case LyXRC::RC_DOCUMENTPATH:
1004                 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
1005                         FileName path(lyxrc_new.document_path);
1006                         if (path.exists() && path.isDirectory())
1007                                 package().document_dir() = FileName(lyxrc.document_path);
1008                 }
1009         case LyXRC::RC_EDITOR_ALTERNATIVES:
1010         case LyXRC::RC_ESC_CHARS:
1011         case LyXRC::RC_EXAMPLEPATH:
1012         case LyXRC::RC_FONT_ENCODING:
1013         case LyXRC::RC_FORMAT:
1014         case LyXRC::RC_GROUP_LAYOUTS:
1015         case LyXRC::RC_HUNSPELLDIR_PATH:
1016         case LyXRC::RC_INDEX_ALTERNATIVES:
1017         case LyXRC::RC_INDEX_COMMAND:
1018         case LyXRC::RC_JBIBTEX_COMMAND:
1019         case LyXRC::RC_JINDEX_COMMAND:
1020         case LyXRC::RC_NOMENCL_COMMAND:
1021         case LyXRC::RC_INPUT:
1022         case LyXRC::RC_KBMAP:
1023         case LyXRC::RC_KBMAP_PRIMARY:
1024         case LyXRC::RC_KBMAP_SECONDARY:
1025         case LyXRC::RC_LABEL_INIT_LENGTH:
1026         case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
1027         case LyXRC::RC_LANGUAGE_AUTO_END:
1028         case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
1029         case LyXRC::RC_LANGUAGE_COMMAND_END:
1030         case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
1031         case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
1032         case LyXRC::RC_LANGUAGE_PACKAGE:
1033         case LyXRC::RC_LANGUAGE_USE_BABEL:
1034         case LyXRC::RC_MAC_LIKE_WORD_MOVEMENT:
1035         case LyXRC::RC_MACRO_EDIT_STYLE:
1036         case LyXRC::RC_MAKE_BACKUP:
1037         case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
1038         case LyXRC::RC_MOUSE_WHEEL_SPEED:
1039         case LyXRC::RC_NUMLASTFILES:
1040         case LyXRC::RC_PARAGRAPH_MARKERS:
1041         case LyXRC::RC_PATH_PREFIX:
1042                 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
1043                         prependEnvPath("PATH", lyxrc.path_prefix);
1044                 }
1045         case LyXRC::RC_PERS_DICT:
1046         case LyXRC::RC_PREVIEW:
1047         case LyXRC::RC_PREVIEW_HASHED_LABELS:
1048         case LyXRC::RC_PREVIEW_SCALE_FACTOR:
1049         case LyXRC::RC_PRINTCOLLCOPIESFLAG:
1050         case LyXRC::RC_PRINTCOPIESFLAG:
1051         case LyXRC::RC_PRINTER:
1052         case LyXRC::RC_PRINTEVENPAGEFLAG:
1053         case LyXRC::RC_PRINTEXSTRAOPTIONS:
1054         case LyXRC::RC_PRINTFILEEXTENSION:
1055         case LyXRC::RC_PRINTLANDSCAPEFLAG:
1056         case LyXRC::RC_PRINTODDPAGEFLAG:
1057         case LyXRC::RC_PRINTPAGERANGEFLAG:
1058         case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
1059         case LyXRC::RC_PRINTPAPERFLAG:
1060         case LyXRC::RC_PRINTREVERSEFLAG:
1061         case LyXRC::RC_PRINTSPOOL_COMMAND:
1062         case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
1063         case LyXRC::RC_PRINTTOFILE:
1064         case LyXRC::RC_PRINTTOPRINTER:
1065         case LyXRC::RC_PRINT_ADAPTOUTPUT:
1066         case LyXRC::RC_PRINT_COMMAND:
1067         case LyXRC::RC_RTL_SUPPORT:
1068         case LyXRC::RC_SCREEN_DPI:
1069         case LyXRC::RC_SCREEN_FONT_ROMAN:
1070         case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
1071         case LyXRC::RC_SCREEN_FONT_SANS:
1072         case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
1073         case LyXRC::RC_SCREEN_FONT_SCALABLE:
1074         case LyXRC::RC_SCREEN_FONT_SIZES:
1075         case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
1076         case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
1077         case LyXRC::RC_GEOMETRY_SESSION:
1078         case LyXRC::RC_SCREEN_ZOOM:
1079         case LyXRC::RC_SERVERPIPE:
1080         case LyXRC::RC_SET_COLOR:
1081         case LyXRC::RC_SHOW_BANNER:
1082         case LyXRC::RC_OPEN_BUFFERS_IN_TABS:
1083         case LyXRC::RC_SPELL_COMMAND:
1084         case LyXRC::RC_SPELLCHECKER:
1085         case LyXRC::RC_SPELLCHECK_CONTINUOUSLY:
1086         case LyXRC::RC_SPLITINDEX_COMMAND:
1087         case LyXRC::RC_TEMPDIRPATH:
1088         case LyXRC::RC_TEMPLATEPATH:
1089         case LyXRC::RC_TEX_ALLOWS_SPACES:
1090         case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
1091                 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
1092                         os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
1093                 }
1094         case LyXRC::RC_THESAURUSDIRPATH:
1095         case LyXRC::RC_UIFILE:
1096         case LyXRC::RC_USER_EMAIL:
1097         case LyXRC::RC_USER_NAME:
1098         case LyXRC::RC_USETEMPDIR:
1099         case LyXRC::RC_USE_ALT_LANG:
1100         case LyXRC::RC_USE_CONVERTER_CACHE:
1101         case LyXRC::RC_USE_ESC_CHARS:
1102         case LyXRC::RC_USE_INP_ENC:
1103         case LyXRC::RC_USE_PERS_DICT:
1104         case LyXRC::RC_USE_TOOLTIP:
1105         case LyXRC::RC_USE_PIXMAP_CACHE:
1106         case LyXRC::RC_USE_SPELL_LIB:
1107         case LyXRC::RC_VIEWDVI_PAPEROPTION:
1108         case LyXRC::RC_SORT_LAYOUTS:
1109         case LyXRC::RC_FULL_SCREEN_LIMIT:
1110         case LyXRC::RC_FULL_SCREEN_SCROLLBAR:
1111         case LyXRC::RC_FULL_SCREEN_MENUBAR:
1112         case LyXRC::RC_FULL_SCREEN_TABBAR:
1113         case LyXRC::RC_FULL_SCREEN_TOOLBARS:
1114         case LyXRC::RC_FULL_SCREEN_WIDTH:
1115         case LyXRC::RC_VISUAL_CURSOR:
1116         case LyXRC::RC_VIEWER:
1117         case LyXRC::RC_VIEWER_ALTERNATIVES:
1118         case LyXRC::RC_LAST:
1119                 break;
1120         }
1121 }
1122
1123 } // namespace anon
1124 } // namespace lyx