]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
remove show_banner + keyboard_shortcuts as discussed
[lyx.git] / src / lyxfunc.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *          Copyright 1995 Matthias Ettrich
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation
15 #endif
16
17 #include "lyxfunc.h"
18 #include "version.h"
19 #include "kbmap.h"
20 #include "lyxrow.h"
21 #include "bufferlist.h"
22 #include "BufferView.h"
23 #include "frontends/xforms/ColorHandler.h"
24 #include "lyxserver.h"
25 #include "intl.h"
26 #include "lyx_main.h"
27 #include "lyx_cb.h"
28 #include "LyXAction.h"
29 #include "debug.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "gettext.h"
33 #include "Lsstream.h"
34 #include "trans_mgr.h"
35 #include "layout.h"
36 #include "bufferview_funcs.h"
37 #include "minibuffer.h"
38 #include "vspace.h"
39 #include "frontends/LyXView.h"
40 #include "FloatList.h"
41 #include "converter.h"
42 #include "exporter.h"
43 #include "importer.h"
44 #include "frontends/font_loader.h"
45 #include "TextCache.h"
46 #include "lyxfind.h"
47 #include "undo_funcs.h"
48 #include "ParagraphParameters.h"
49
50 #include "insets/inseturl.h"
51 #include "insets/insetlatexaccent.h"
52 #include "insets/insettoc.h"
53 #include "insets/insetref.h"
54 #include "insets/insetparent.h"
55 #include "insets/insetindex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insetbib.h"
58 #include "insets/insetcite.h"
59 #include "insets/insettext.h"
60 #include "insets/insetert.h"
61 #include "insets/insetexternal.h"
62 #include "insets/insetgraphics.h"
63 #include "insets/insetfoot.h"
64 #include "insets/insetmarginal.h"
65 #include "insets/insetminipage.h"
66 #include "insets/insetfloat.h"
67 #if 0
68 #include "insets/insetlist.h"
69 #include "insets/insettheorem.h"
70 #endif
71 #include "insets/insettabular.h"
72 #include "insets/insetcaption.h"
73
74 #include "mathed/formulamacro.h"
75 #include "mathed/math_cursor.h"
76 #include "mathed/math_inset.h"
77
78 #include "frontends/FileDialog.h"
79 #include "frontends/Dialogs.h"
80 #include "frontends/Toolbar.h"
81 #include "frontends/Menubar.h"
82 #include "frontends/Alert.h"
83
84 #include "graphics/GraphicsCache.h"
85
86 #include "support/lyxalgo.h"
87 #include "support/LAssert.h"
88 #include "support/filetools.h"
89 #include "support/FileInfo.h"
90 #include "support/forkedcontr.h"
91 #include "support/lstrings.h"
92 #include "support/path.h"
93 #include "support/lyxfunctional.h"
94
95 #include <ctime>
96 #include <clocale>
97 #include <cstdlib>
98 #include <cctype>
99
100 #include <utility>
101 #include <algorithm>
102
103
104 using std::pair;
105 using std::make_pair;
106 using std::endl;
107 using std::find_if;
108 using std::vector;
109 using std::transform;
110 using std::back_inserter;
111
112 extern BufferList bufferlist;
113 extern LyXServer * lyxserver;
114 extern bool selection_possible;
115
116 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
117
118 extern void show_symbols_form(LyXFunc *);
119
120 extern LyXAction lyxaction;
121 // (alkis)
122 extern tex_accent_struct get_accent(kb_action action);
123
124 extern void ShowLatexLog();
125
126
127 #if 0
128
129 ///
130 class MiniBufferController : public SigC::Object {
131 public:
132         ///
133         MiniBufferController() {
134                 minibuffer
135                         .cmdReady
136                         .connect(slot(this,
137                                       &MiniBufferController::receiveCommand));
138                 minibuffer
139                         .argReady
140                         .connect(slot(this,
141                                       &MiniBufferController::receiveArg));
142         }
143         ///
144         void receiveCmd(string const & cmd) {}
145         ///
146         void receiveArg(string const & arg) {}
147
148
149 private:
150 };
151
152 namespace {
153
154 MiniBufferController mb_ctrl;
155
156 }
157 #endif
158
159
160 /* === globals =========================================================== */
161
162
163 LyXFunc::LyXFunc(LyXView * o)
164         : owner(o),
165         keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
166         cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get())
167 {
168         meta_fake_bit = key_modifier::none;
169         lyx_dead_action = LFUN_NOACTION;
170         lyx_calling_dead_action = LFUN_NOACTION;
171 }
172
173
174 inline
175 LyXText * LyXFunc::TEXT(bool flag = true) const
176 {
177         if (flag)
178                 return owner->view()->text;
179         return owner->view()->getLyXText();
180 }
181
182
183 // I changed this func slightly. I commented out the ...FinishUndo(),
184 // this means that all places that used to have a moveCursorUpdate, now
185 // have a ...FinishUndo() as the preceeding statement. I have also added
186 // a moveCursorUpdate to some of the functions that updated the cursor, but
187 // that did not show its new position.
188 inline
189 void LyXFunc::moveCursorUpdate(bool flag, bool selecting)
190 {
191         if (selecting || TEXT(flag)->selection.mark()) {
192                 TEXT(flag)->setSelection(owner->view());
193                 if (TEXT(flag)->bv_owner)
194                     owner->view()->toggleToggle();
195         }
196         owner->view()->update(TEXT(flag), BufferView::SELECT|BufferView::FITCUR);
197         owner->view()->showCursor();
198
199         /* ---> Everytime the cursor is moved, show the current font state. */
200         // should this too me moved out of this func?
201         owner->view()->setState();
202 }
203
204
205 void LyXFunc::handleKeyFunc(kb_action action)
206 {
207         char c = keyseq.getLastKeyEncoded();
208
209         if (keyseq.length() > 1) {
210                 c = 0;
211         }
212
213         owner->getIntl()->getTransManager()
214                 .deadkey(c, get_accent(action).accent, TEXT(false));
215         // Need to clear, in case the minibuffer calls these
216         // actions
217         keyseq.clear();
218         // copied verbatim from do_accent_char
219         owner->view()->update(TEXT(false),
220                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
221         TEXT(false)->selection.cursor = TEXT(false)->cursor;
222 }
223
224
225 void LyXFunc::processKeySym(LyXKeySymPtr keysym,
226                             key_modifier::state state)
227 {
228         string argument;
229
230         if (lyxerr.debugging(Debug::KEY)) {
231                 lyxerr << "KeySym is "
232                        << keysym->getSymbolName()
233                        << endl;
234         }
235         // Do nothing if we have nothing (JMarc)
236         if ( ! keysym->isOK() ) {
237                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
238                                    << endl;
239                 return;
240         }
241
242         if (keysym->isModifier()) {
243                 return;
244         }
245
246         // Do a one-deep top-level lookup for
247         // cancel and meta-fake keys. RVDK_PATCH_5
248         cancel_meta_seq.reset();
249
250         int action = cancel_meta_seq.addkey(keysym, state);
251         if (lyxerr.debugging(Debug::KEY)) {
252                 lyxerr << "action first set to [" << action << "]" << endl;
253         }
254
255         // When not cancel or meta-fake, do the normal lookup.
256         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
257         // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
258         if ((action != LFUN_CANCEL) && (action != LFUN_META_FAKE)) {
259                 // remove Caps Lock and Mod2 as a modifiers
260                 action = keyseq.addkey(keysym, (state | meta_fake_bit));
261                 if (lyxerr.debugging(Debug::KEY)) {
262                         lyxerr << "action now set to ["
263                                << action << "]" << endl;
264                 }
265         }
266         // Dont remove this unless you know what you are doing.
267         meta_fake_bit = key_modifier::none;
268
269         // can this happen now ?
270         if (action == LFUN_NOACTION) {
271                 action = LFUN_PREFIX;
272         }
273
274         if (lyxerr.debugging(Debug::KEY)) {
275                 lyxerr << "Key [action="
276                        << action << "]["
277                        << keyseq.print() << "]"
278                        << endl;
279         }
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                 owner->message(keyseq.print());
287         }
288
289         if (action == LFUN_UNKNOWN_ACTION) {
290                 // It is unknown, but what if we remove all
291                 // the modifiers? (Lgb)
292                 action = keyseq.addkey(keysym, key_modifier::none);
293
294                 if (lyxerr.debugging(Debug::KEY)) {
295                         lyxerr << "Removing modifiers...\n"
296                                << "Action now set to ["
297                                << action << "]" << endl;
298                 }
299                 if (action == LFUN_UNKNOWN_ACTION) {
300                         owner->message(_("Unknown function."));
301                         return;
302                 }
303         }
304
305         if (action == LFUN_SELFINSERT) {
306                 // This is very X dependent.
307                 char c = keysym->getISOEncoded();
308                 string argument;
309
310                 if (c != 0)
311                         argument = c;
312
313                 dispatch(LFUN_SELFINSERT, argument);
314                 lyxerr[Debug::KEY] << "SelfInsert arg[`"
315                                    << argument << "']" << endl;
316         } else {
317                 verboseDispatch(action, false);
318         }
319 }
320
321
322 FuncStatus LyXFunc::getStatus(int ac) const
323 {
324         kb_action action;
325         string argument;
326         action = lyxaction.retrieveActionArg(ac, argument);
327         return getStatus(action, argument);
328 }
329
330
331 FuncStatus LyXFunc::getStatus(kb_action action,
332                               string const & argument) const
333 {
334         FuncStatus flag;
335         Buffer * buf = owner->buffer();
336
337         if (action == LFUN_NOACTION) {
338                 setStatusMessage(N_("Nothing to do"));
339                 return flag.disabled(true);
340         }
341
342         if (action == LFUN_UNKNOWN_ACTION) {
343                 setStatusMessage(N_("Unknown action"));
344                 return flag.unknown(true);
345         }
346
347         // the default error message if we disable the command
348         setStatusMessage(N_("Command disabled"));
349
350         // Check whether we need a buffer
351         if (!lyxaction.funcHasFlag(action, LyXAction::NoBuffer)) {
352                 // Yes we need a buffer, do we have one?
353                 if (buf) {
354                         // yes
355                         // Can we use a readonly buffer?
356                         if (buf->isReadonly() &&
357                             !lyxaction.funcHasFlag(action,
358                                                    LyXAction::ReadOnly)) {
359                                 // no
360                                 setStatusMessage(N_("Document is read-only"));
361                                 flag.disabled(true);
362                         }
363                 } else {
364                         // no
365                         setStatusMessage(N_("Command not allowed with"
366                                            "out any document open"));
367                         return flag.disabled(true);
368                 }
369         }
370
371         UpdatableInset * tli = owner->view()->theLockingInset();
372
373         // I would really like to avoid having this switch and rather try to
374         // encode this in the function itself.
375         bool disable = false;
376         switch (action) {
377         case LFUN_MENUPRINT:
378                 disable = !Exporter::IsExportable(buf, "dvi")
379                         || lyxrc.print_command == "none";
380                 break;
381         case LFUN_EXPORT:
382                 disable = argument == "fax" &&
383                         !Exporter::IsExportable(buf, argument);
384                 break;
385         case LFUN_UNDO:
386                 disable = buf->undostack.empty();
387                 break;
388         case LFUN_REDO:
389                 disable = buf->redostack.empty();
390                 break;
391         case LFUN_SPELLCHECK:
392                 disable = lyxrc.isp_command == "none";
393                 break;
394 #ifndef HAVE_LIBAIKSAURUS
395         case LFUN_THESAURUS_ENTRY:
396                 disable = true;
397                 break;
398 #endif
399         case LFUN_RUNCHKTEX:
400                 disable = lyxrc.chktex_command == "none";
401                 break;
402         case LFUN_BUILDPROG:
403                 disable = !Exporter::IsExportable(buf, "program");
404                 break;
405
406         case LFUN_LAYOUT_TABULAR:
407                 disable = !tli
408                         || (tli->lyxCode() != Inset::TABULAR_CODE
409                             && !tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
410                 break;
411
412         case LFUN_LAYOUT:
413         case LFUN_LAYOUT_PARAGRAPH: {
414                 Inset * inset = TEXT(false)->cursor.par()->inInset();
415                 disable = inset && inset->forceDefaultParagraphs(inset);
416                 break;
417         }
418
419         case LFUN_TABULAR_FEATURE:
420                 disable = true;
421                 if (tli) {
422                         FuncStatus ret;
423                         //ret.disabled(true);
424                         if (tli->lyxCode() == Inset::TABULAR_CODE) {
425                                 ret = static_cast<InsetTabular *>(tli)
426                                         ->getStatus(argument);
427                         } else if (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE)) {
428                                 ret = static_cast<InsetTabular *>
429                                         (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE))
430                                         ->getStatus(argument);
431                         }
432                         flag |= ret;
433                         disable = false;
434                 } else {
435                         static InsetTabular inset(*owner->buffer(), 1, 1);
436                         FuncStatus ret;
437
438                         disable = true;
439                         ret = inset.getStatus(argument);
440                         if (ret.onoff(true) || ret.onoff(false))
441                                 flag.setOnOff(false);
442                 }
443                 break;
444
445         case LFUN_VC_REGISTER:
446                 disable = buf->lyxvc.inUse();
447                 break;
448         case LFUN_VC_CHECKIN:
449                 disable = !buf->lyxvc.inUse() || buf->isReadonly();
450                 break;
451         case LFUN_VC_CHECKOUT:
452                 disable = !buf->lyxvc.inUse() || !buf->isReadonly();
453                 break;
454         case LFUN_VC_REVERT:
455         case LFUN_VC_UNDO:
456         case LFUN_VC_HISTORY:
457                 disable = !buf->lyxvc.inUse();
458                 break;
459         case LFUN_BOOKMARK_GOTO:
460                 disable =  !owner->view()->
461                         isSavedPosition(strToUnsignedInt(argument));
462                 break;
463
464
465         case LFUN_INSET_TOGGLE: {
466                 LyXText * lt = owner->view()->getLyXText();
467                 disable = !(isEditableInset(lt->getInset())
468                             || (lt->inset_owner
469                                 && lt->inset_owner->owner()
470                                 && lt->inset_owner->owner()->isOpen()));
471                 break;
472         }
473         case LFUN_MATH_VALIGN:
474                 if (mathcursor && mathcursor->formula()->getType() != LM_OT_SIMPLE) {
475                         char align = mathcursor->valign();
476                         if (align == '\0') {
477                                 disable = true;
478                                 break;
479                         }
480                         if (argument.empty()) {
481                                 flag.clear();
482                                 break;
483                         }
484                         if (!contains("tcb", argument[0])) {
485                                 disable = true;
486                                 break;
487                         }
488                         flag.setOnOff(argument[0] == align);
489                 } else
490                         disable = true;
491                 break;
492
493         case LFUN_MATH_HALIGN:
494                 if (mathcursor && mathcursor->formula()->getType() != LM_OT_SIMPLE) {
495                         char align = mathcursor->halign();
496                         if (align == '\0') {
497                                 disable = true;
498                                 break;
499                         }
500                         if (argument.empty()) {
501                                 flag.clear();
502                                 break;
503                         }
504                         if (!contains("lcr", argument[0])) {
505                                 disable = true;
506                                 break;
507                         }
508                         flag.setOnOff(argument[0] == align);
509                 } else
510                         disable = true;
511                 break;
512
513         case LFUN_MATH_MUTATE:
514                 if (tli && (tli->lyxCode() == Inset::MATH_CODE)) {
515                         MathInsetTypes type = mathcursor->formula()->getType();
516                         if (argument == "inline") {
517                                 flag.setOnOff(type == LM_OT_SIMPLE);
518                         } else if (argument == "display") {
519                                 flag.setOnOff(type == LM_OT_EQUATION);
520                         } else if (argument == "eqnarray") {
521                                 flag.setOnOff(type == LM_OT_EQNARRAY);
522                         } else if (argument == "align") {
523                                 flag.setOnOff(type == LM_OT_ALIGN);
524                         } else if (argument == "none") {
525                                 flag.setOnOff(type == LM_OT_NONE);
526                         } else {
527                                 disable = true;
528                         }
529                 } else
530                         disable = true;
531                 break;
532
533         // we just need to be in math mode to enable that
534         case LFUN_MATH_SIZE:
535         case LFUN_MATH_SPACE:
536         case LFUN_MATH_LIMITS:
537         case LFUN_MATH_NONUMBER:
538         case LFUN_MATH_NUMBER:
539                 disable = !mathcursor;
540                 break;
541
542         // we need to be math mode and a math array for that
543         // Hack: halign produces non-zero result iff we are in a math array
544         case LFUN_MATH_ROW_INSERT:
545         case LFUN_MATH_ROW_DELETE:
546         case LFUN_MATH_COLUMN_INSERT:
547         case LFUN_MATH_COLUMN_DELETE:
548                 disable = !mathcursor || !mathcursor->halign() ||
549                         mathcursor->formula()->getType() == LM_OT_SIMPLE;
550                 break;
551
552         default:
553                 break;
554         }
555
556         // the functions which insert insets
557         Inset::Code code = Inset::NO_CODE;
558         switch (action) {
559         case LFUN_INSET_ERT:
560                 code = Inset::ERT_CODE;
561                 break;
562         case LFUN_INSET_GRAPHICS:
563                 code = Inset::GRAPHICS_CODE;
564                 break;
565         case LFUN_INSET_FOOTNOTE:
566                 code = Inset::FOOT_CODE;
567                 break;
568         case LFUN_DIALOG_TABULAR_INSERT:
569         case LFUN_INSET_TABULAR:
570                 code = Inset::TABULAR_CODE;
571                 break;
572         case LFUN_INSET_EXTERNAL:
573                 code = Inset::EXTERNAL_CODE;
574                 break;
575         case LFUN_INSET_MARGINAL:
576                 code = Inset::MARGIN_CODE;
577                 break;
578         case LFUN_INSET_MINIPAGE:
579                 code = Inset::MINIPAGE_CODE;
580                 break;
581         case LFUN_INSET_FLOAT:
582         case LFUN_INSET_WIDE_FLOAT:
583                 code = Inset::FLOAT_CODE;
584                 break;
585         case LFUN_FLOAT_LIST:
586                 code = Inset::FLOAT_LIST_CODE;
587                 break;
588 #if 0
589         case LFUN_INSET_LIST:
590                 code = Inset::LIST_CODE;
591                 break;
592         case LFUN_INSET_THEOREM:
593                 code = Inset::THEOREM_CODE;
594                 break;
595 #endif
596         case LFUN_INSET_CAPTION:
597                 code = Inset::CAPTION_CODE;
598                 break;
599         case LFUN_INSERT_NOTE:
600                 code = Inset::IGNORE_CODE;
601                 break;
602         case LFUN_INSERT_LABEL:
603                 code = Inset::LABEL_CODE;
604                 break;
605         case LFUN_REF_INSERT:
606                 code = Inset::REF_CODE;
607                 break;
608         case LFUN_CITATION_CREATE:
609         case LFUN_CITATION_INSERT:
610                 code = Inset::CITE_CODE;
611                 break;
612         case LFUN_INSERT_BIBTEX:
613                 code = Inset::BIBTEX_CODE;
614                 break;
615         case LFUN_INDEX_INSERT:
616                 code = Inset::INDEX_CODE;
617                 break;
618         case LFUN_INDEX_PRINT:
619                 code = Inset::INDEX_PRINT_CODE;
620                 break;
621         case LFUN_CHILD_INSERT:
622                 code = Inset::INCLUDE_CODE;
623                 break;
624         case LFUN_TOC_INSERT:
625                 code = Inset::TOC_CODE;
626                 break;
627         case LFUN_PARENTINSERT:
628                 code = Inset::PARENT_CODE;
629                 break;
630         case LFUN_HTMLURL:
631         case LFUN_URL:
632         case LFUN_INSERT_URL:
633                 code = Inset::URL_CODE;
634                 break;
635         case LFUN_QUOTE:
636                 // always allow this, since we will inset a raw quote
637                 // if an inset is not allowed.
638                 break;
639         case LFUN_HYPHENATION:
640         case LFUN_LIGATURE_BREAK:
641         case LFUN_HFILL:
642         case LFUN_MENU_SEPARATOR:
643         case LFUN_LDOTS:
644         case LFUN_END_OF_SENTENCE:
645                 code = Inset::SPECIALCHAR_CODE;
646                 break;
647         case LFUN_PROTECTEDSPACE:
648                 // slight hack: we know this is allowed in math mode
649                 if (!mathcursor)
650                         code = Inset::SPECIALCHAR_CODE;
651                 break;
652         default:
653                 break;
654         }
655         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code)) {
656                 disable = true;
657         }
658
659         if (disable)
660                         flag.disabled(true);
661
662         // A few general toggles
663         switch (action) {
664         case LFUN_TOOLTIPS_TOGGLE:
665                 flag.setOnOff(owner->getDialogs()->tooltipsEnabled());
666                 break;
667
668         case LFUN_READ_ONLY_TOGGLE:
669                 flag.setOnOff(buf->isReadonly());
670                 break;
671         case LFUN_APPENDIX:
672                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
673                 break;
674         case LFUN_SWITCHBUFFER:
675                 // toggle on the current buffer, but do not toggle off
676                 // the other ones (is that a good idea?)
677                 if (argument == buf->fileName())
678                         flag.setOnOff(true);
679                 break;
680         default:
681                 break;
682         }
683
684         // the font related toggles
685         if (!mathcursor) {
686                 LyXFont const & font = TEXT(false)->real_current_font;
687                 switch (action) {
688                 case LFUN_EMPH:
689                         flag.setOnOff(font.emph() == LyXFont::ON);
690                         break;
691                 case LFUN_NOUN:
692                         flag.setOnOff(font.noun() == LyXFont::ON);
693                         break;
694                 case LFUN_BOLD:
695                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
696                         break;
697                 case LFUN_SANS:
698                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
699                         break;
700                 case LFUN_ROMAN:
701                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
702                         break;
703                 case LFUN_CODE:
704                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
705                         break;
706                 default:
707                         break;
708                 }
709         }
710         else {
711                 string tc = mathcursor->getLastCode();
712                 switch (action) {
713                 case LFUN_BOLD:
714                         flag.setOnOff(tc == "mathbf");
715                         break;
716                 case LFUN_SANS:
717                         flag.setOnOff(tc == "mathsf");
718                         break;
719                 case LFUN_EMPH:
720                         flag.setOnOff(tc == "mathcal");
721                         break;
722                 case LFUN_ROMAN:
723                         flag.setOnOff(tc == "mathrm");
724                         break;
725                 case LFUN_CODE:
726                         flag.setOnOff(tc == "mathtt");
727                         break;
728                 case LFUN_NOUN:
729                         flag.setOnOff(tc == "mathbb");
730                         break;
731                 case LFUN_DEFAULT:
732                         flag.setOnOff(tc == "mathnormal");
733                         break;
734                 default:
735                         break;
736                 }
737         }
738
739         return flag;
740 }
741
742
743 // temporary dispatch method
744 void LyXFunc::miniDispatch(string const & s)
745 {
746         string s2(frontStrip(strip(s)));
747
748         if (!s2.empty()) {
749                 verboseDispatch(s2, true);
750         }
751 }
752
753
754 void LyXFunc::verboseDispatch(string const & s, bool show_sc)
755 {
756         int action = lyxaction.LookupFunc(frontStrip(s));
757
758         if (action == LFUN_UNKNOWN_ACTION) {
759                 string const msg = string(_("Unknown function ("))
760                         + s + ")";
761                 owner->message(msg);
762         } else {
763                 verboseDispatch(action, show_sc);
764         }
765 }
766
767
768 void LyXFunc::verboseDispatch(int ac, bool show_sc)
769 {
770         string argument;
771         kb_action action;
772
773         // get the real action and argument
774         action = lyxaction.retrieveActionArg(ac, argument);
775
776         verboseDispatch(action, argument, show_sc);
777 }
778
779
780
781 void LyXFunc::verboseDispatch(kb_action action,
782                               string const & argument, bool show_sc)
783 {
784         string res = dispatch(action, argument);
785
786         commandshortcut.erase();
787
788         if (show_sc && action != LFUN_SELFINSERT) {
789                 // Put name of command and list of shortcuts
790                 // for it in minibuffer
791                 string comname = lyxaction.getActionName(action);
792
793                 int pseudoaction = action;
794                 bool argsadded = false;
795
796                 if (!argument.empty()) {
797                         // the pseudoaction is useful for the bindings
798                         pseudoaction =
799                                 lyxaction.searchActionArg(action,
800                                                           argument);
801
802                         if (pseudoaction == LFUN_UNKNOWN_ACTION) {
803                                 pseudoaction = action;
804                         } else {
805                                 comname += " " + argument;
806                                 argsadded = true;
807                         }
808                 }
809
810                 string const shortcuts =
811                         toplevel_keymap->findbinding(pseudoaction);
812
813                 if (!shortcuts.empty()) {
814                         comname += ": " + shortcuts;
815                 } else if (!argsadded && !argument.empty()) {
816                         comname += " " + argument;
817                 }
818
819                 if (!comname.empty()) {
820                         comname = strip(comname);
821                         commandshortcut = "(" + comname + ')';
822                 }
823         }
824
825         if (res.empty()) {
826                 if (!commandshortcut.empty()) {
827                         owner->getMiniBuffer()->addSet(commandshortcut);
828                 }
829         } else {
830                 owner->getMiniBuffer()->addSet(' ' + commandshortcut);
831         }
832 }
833
834
835 string const LyXFunc::dispatch(kb_action action, string argument)
836 {
837         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << action
838                               <<"] arg[" << argument << "]" << endl;
839
840         // we have not done anything wrong yet.
841         errorstat = false;
842         dispatch_buffer.erase();
843
844 #ifdef NEW_DISPATCHER
845         // We try do call the most specific dispatcher first:
846         //  1. the lockinginset's dispatch
847         //  2. the bufferview's dispatch
848         //  3. the lyxview's dispatch
849 #endif
850
851         selection_possible = false;
852
853         if (owner->view()->available())
854                 owner->view()->hideCursor();
855
856         // We cannot use this function here
857         if (getStatus(action, argument).disabled()) {
858                 lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: "
859                        << lyxaction.getActionName(action)
860                        << " [" << action << "] is disabled at this location"
861                        << endl;
862                 setErrorMessage(getStatusMessage());
863                 goto exit_with_message;
864         }
865
866         if (owner->view()->available() && owner->view()->theLockingInset()) {
867                 UpdatableInset::RESULT result;
868                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
869                                      (!keyseq.deleted())))
870                 {
871                         UpdatableInset * inset = owner->view()->theLockingInset();
872 #if 1
873                         int inset_x;
874                         int dummy_y;
875                         inset->getCursorPos(owner->view(), inset_x, dummy_y);
876 #endif
877                         if ((action == LFUN_UNKNOWN_ACTION)
878                             && argument.empty()) {
879                                 argument = keyseq.getLastKeyEncoded();
880                         }
881                         // Undo/Redo is a bit tricky for insets.
882                         if (action == LFUN_UNDO) {
883                                 owner->view()->menuUndo();
884                                 goto exit_with_message;
885                         } else if (action == LFUN_REDO) {
886                                 owner->view()->menuRedo();
887                                 goto exit_with_message;
888                         } else if (((result=inset->
889                                      // Hand-over to inset's own dispatch:
890                                      localDispatch(owner->view(), action, argument)) ==
891                                     UpdatableInset::DISPATCHED) ||
892                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
893                                 goto exit_with_message;
894                                         // If UNDISPATCHED, just soldier on
895                         else if (result == UpdatableInset::FINISHED) {
896                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
897                                                 TEXT()->cursorRight(owner->view());
898                                                 moveCursorUpdate(true, false);
899                                                 owner->showState();
900                                         }
901                                         goto exit_with_message;
902                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
903                                 if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
904                                         TEXT()->cursorRight(owner->view());
905                                         moveCursorUpdate(true, false);
906                                         owner->showState();
907                                 }
908                                 goto exit_with_message;
909                         } else if (result == UpdatableInset::FINISHED_UP) {
910                                 if (TEXT()->cursor.irow()->previous()) {
911 #if 1
912                                         TEXT()->setCursorFromCoordinates(
913                                                 owner->view(), TEXT()->cursor.ix() + inset_x,
914                                                 TEXT()->cursor.iy() -
915                                                 TEXT()->cursor.irow()->baseline() - 1);
916                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
917 #else
918                                         TEXT()->cursorUp(owner->view());
919 #endif
920                                         moveCursorUpdate(true, false);
921                                         owner->showState();
922                                 } else {
923                                         owner->view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
924                                 }
925                                 goto exit_with_message;
926                         } else if (result == UpdatableInset::FINISHED_DOWN) {
927                                 if (TEXT()->cursor.irow()->next()) {
928 #if 1
929                                         TEXT()->setCursorFromCoordinates(
930                                                 owner->view(), TEXT()->cursor.ix() + inset_x,
931                                                 TEXT()->cursor.iy() -
932                                                 TEXT()->cursor.irow()->baseline() +
933                                                 TEXT()->cursor.irow()->height() + 1);
934                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
935 #else
936                                         TEXT()->cursorDown(owner->view());
937 #endif
938                                 } else {
939                                         TEXT()->cursorRight(owner->view());
940                                 }
941                                 moveCursorUpdate(true, false);
942                                 owner->showState();
943                                 goto exit_with_message;
944                         }
945 #warning I am not sure this is still right, please have a look! (Jug 20020417)
946                         else { // result == UNDISPATCHED
947                                 //setMessage(N_("Text mode"));
948                                 switch (action) {
949                                 case LFUN_UNKNOWN_ACTION:
950                                 case LFUN_BREAKPARAGRAPH:
951                                 case LFUN_BREAKLINE:
952                                         TEXT()->cursorRight(owner->view());
953                                         owner->view()->setState();
954                                         owner->showState();
955                                         break;
956                                 case LFUN_RIGHT:
957                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
958                                                 TEXT()->cursorRight(owner->view());
959                                                 moveCursorUpdate(true, false);
960                                                 owner->showState();
961                                         }
962                                         goto exit_with_message;
963                                 case LFUN_LEFT:
964                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
965                                                 TEXT()->cursorRight(owner->view());
966                                                 moveCursorUpdate(true, false);
967                                                 owner->showState();
968                                         }
969                                         goto exit_with_message;
970                                 case LFUN_DOWN:
971                                         if (TEXT()->cursor.row()->next())
972                                                 TEXT()->cursorDown(owner->view());
973                                         else
974                                                 TEXT()->cursorRight(owner->view());
975                                         moveCursorUpdate(true, false);
976                                         owner->showState();
977                                         goto exit_with_message;
978                                 default:
979                                         break;
980                                 }
981                         }
982                 }
983         }
984
985         switch (action) {
986
987         case LFUN_ESCAPE:
988         {
989                 if (!owner->view()->available()) break;
990                 // this function should be used always [asierra060396]
991                 UpdatableInset * tli =
992                         owner->view()->theLockingInset();
993                 if (tli) {
994                         UpdatableInset * lock = tli->getLockingInset();
995
996                         if (tli == lock) {
997                                 owner->view()->unlockInset(tli);
998                                 TEXT()->cursorRight(owner->view());
999                                 moveCursorUpdate(true, false);
1000                                 owner->showState();
1001                         } else {
1002                                 tli->unlockInsetInInset(owner->view(),
1003                                                         lock,
1004                                                         true);
1005                         }
1006                         finishUndo();
1007                         // Tell the paragraph dialog that we changed paragraph
1008                         owner->getDialogs()->updateParagraph();
1009                 }
1010         }
1011         break;
1012
1013                 // --- Misc -------------------------------------------
1014         case LFUN_WORDFINDFORWARD  :
1015         case LFUN_WORDFINDBACKWARD : {
1016                 static string last_search;
1017                 string searched_string;
1018
1019                 if (!argument.empty()) {
1020                         last_search = argument;
1021                         searched_string = argument;
1022                 } else {
1023                         searched_string = last_search;
1024                 }
1025                 bool fw = (action == LFUN_WORDFINDBACKWARD);
1026                 if (!searched_string.empty()) {
1027                         lyxfind::LyXFind(owner->view(), searched_string, fw);
1028                 }
1029 //              owner->view()->showCursor();
1030         }
1031         break;
1032
1033         case LFUN_PREFIX:
1034         {
1035                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
1036                         owner->view()->update(TEXT(),
1037                                               BufferView::SELECT|BufferView::FITCUR);
1038                 }
1039                 owner->message(keyseq.printOptions());
1040         }
1041         break;
1042
1043         // --- Misc -------------------------------------------
1044         case LFUN_EXEC_COMMAND:
1045         {
1046                 vector<string> allCmds;
1047                 transform(lyxaction.func_begin(), lyxaction.func_end(),
1048                           back_inserter(allCmds), lyx::firster());
1049                 static vector<string> hist;
1050                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
1051                                                   allCmds, hist);
1052         }
1053         break;
1054
1055         case LFUN_CANCEL:                   // RVDK_PATCH_5
1056                 keyseq.reset();
1057                 meta_fake_bit = key_modifier::none;
1058                 if (owner->view()->available())
1059                         // cancel any selection
1060                         dispatch(LFUN_MARK_OFF);
1061                 setMessage(N_("Cancel"));
1062                 break;
1063
1064         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1065         {
1066                 meta_fake_bit = key_modifier::alt;
1067                 setMessage(keyseq.print());
1068         }
1069         break;
1070
1071         case LFUN_READ_ONLY_TOGGLE:
1072                 if (owner->buffer()->lyxvc.inUse()) {
1073                         owner->buffer()->lyxvc.toggleReadOnly();
1074                 } else {
1075                         owner->buffer()->setReadonly(
1076                                 !owner->buffer()->isReadonly());
1077                 }
1078                 break;
1079
1080         case LFUN_CENTER: // this is center and redraw.
1081                 owner->view()->center();
1082                 break;
1083
1084                 // --- Menus -----------------------------------------------
1085         case LFUN_MENUNEW:
1086                 menuNew(false);
1087                 break;
1088
1089         case LFUN_MENUNEWTMPLT:
1090                 menuNew(true);
1091                 break;
1092
1093         case LFUN_CLOSEBUFFER:
1094                 closeBuffer();
1095                 break;
1096
1097         case LFUN_MENUWRITE:
1098                 if (!owner->buffer()->isUnnamed()) {
1099                         ostringstream s1;
1100                         s1 << _("Saving document") << ' '
1101                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1102                         owner->message(s1.str().c_str());
1103                         MenuWrite(owner->view(), owner->buffer());
1104                 } else
1105                         WriteAs(owner->view(), owner->buffer());
1106                 break;
1107
1108         case LFUN_WRITEAS:
1109                 WriteAs(owner->view(), owner->buffer(), argument);
1110                 break;
1111
1112         case LFUN_MENURELOAD:
1113                 reloadBuffer();
1114                 break;
1115
1116         case LFUN_UPDATE:
1117                 Exporter::Export(owner->buffer(), argument, true);
1118                 break;
1119
1120         case LFUN_PREVIEW:
1121                 Exporter::Preview(owner->buffer(), argument);
1122                 break;
1123
1124         case LFUN_BUILDPROG:
1125                 Exporter::Export(owner->buffer(), "program", true);
1126                 break;
1127
1128         case LFUN_RUNCHKTEX:
1129                 MenuRunChktex(owner->buffer());
1130                 break;
1131
1132         case LFUN_MENUPRINT:
1133                 owner->getDialogs()->showPrint();
1134                 break;
1135
1136         case LFUN_EXPORT:
1137                 if (argument == "custom")
1138                         owner->getDialogs()->showSendto();
1139                 else
1140                         Exporter::Export(owner->buffer(), argument, false);
1141                 break;
1142
1143         case LFUN_IMPORT:
1144                 doImport(argument);
1145                 break;
1146
1147         case LFUN_QUIT:
1148                 QuitLyX();
1149                 break;
1150
1151         case LFUN_TOCVIEW:
1152 #if 0
1153         case LFUN_LOFVIEW:
1154         case LFUN_LOTVIEW:
1155         case LFUN_LOAVIEW:
1156 #endif
1157         {
1158                 InsetCommandParams p;
1159
1160 #if 0
1161                 if (action == LFUN_TOCVIEW)
1162 #endif
1163                         p.setCmdName("tableofcontents");
1164 #if 0
1165                 else if (action == LFUN_LOAVIEW)
1166                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1167                 else if (action == LFUN_LOFVIEW)
1168                         p.setCmdName("listoffigures");
1169                 else
1170                         p.setCmdName("listoftables");
1171 #endif
1172                 owner->getDialogs()->createTOC(p.getAsString());
1173                 break;
1174         }
1175
1176         case LFUN_DIALOG_TABULAR_INSERT:
1177                 owner->getDialogs()->showTabularCreate();
1178                 break;
1179
1180         case LFUN_AUTOSAVE:
1181                 AutoSave(owner->view());
1182                 break;
1183
1184         case LFUN_UNDO:
1185                 owner->view()->menuUndo();
1186                 break;
1187
1188         case LFUN_REDO:
1189                 owner->view()->menuRedo();
1190                 break;
1191
1192         case LFUN_MENUSEARCH:
1193                 owner->getDialogs()->showSearch();
1194                 break;
1195
1196         case LFUN_REMOVEERRORS:
1197                 if (owner->view()->removeAutoInsets()) {
1198 #warning repaint() or update() or nothing ?
1199                         owner->view()->repaint();
1200                         owner->view()->fitCursor();
1201                 }
1202                 break;
1203
1204         case LFUN_DEPTH_MIN:
1205                 changeDepth(owner->view(), TEXT(false), -1);
1206                 break;
1207
1208         case LFUN_DEPTH_PLUS:
1209                 changeDepth(owner->view(), TEXT(false), 1);
1210                 break;
1211
1212         case LFUN_FREE:
1213                 owner->getDialogs()->setUserFreeFont();
1214                 break;
1215
1216         case LFUN_RECONFIGURE:
1217                 Reconfigure(owner->view());
1218                 break;
1219
1220 #if 0
1221         case LFUN_FLOATSOPERATE:
1222                 if (argument == "openfoot")
1223                         owner->view()->allFloats(1,0);
1224                 else if (argument == "closefoot")
1225                         owner->view()->allFloats(0,0);
1226                 else if (argument == "openfig")
1227                         owner->view()->allFloats(1,1);
1228                 else if (argument == "closefig")
1229                         owner->view()->allFloats(0,1);
1230                 break;
1231 #else
1232 #ifdef WITH_WARNINGS
1233 //#warning Find another implementation here (or another lyxfunc)!
1234 #endif
1235 #endif
1236         case LFUN_HELP_ABOUTLYX:
1237                 owner->getDialogs()->showAboutlyx();
1238                 break;
1239
1240         case LFUN_HELP_TEXINFO:
1241                 owner->getDialogs()->showTexinfo();
1242                 break;
1243
1244         case LFUN_HELP_OPEN:
1245         {
1246                 string const arg = argument;
1247                 if (arg.empty()) {
1248                         setErrorMessage(N_("Missing argument"));
1249                         break;
1250                 }
1251                 owner->prohibitInput();
1252                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1253                 if (fname.empty()) {
1254                         lyxerr << "LyX: unable to find documentation file `"
1255                                << arg << "'. Bad installation?" << endl;
1256                         owner->allowInput();
1257                         break;
1258                 }
1259                 ostringstream str;
1260                 str << _("Opening help file") << ' '
1261                     << MakeDisplayPath(fname) << "...";
1262                 owner->message(str.str().c_str());
1263                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1264                 owner->allowInput();
1265                 break;
1266         }
1267
1268                 // --- version control -------------------------------
1269         case LFUN_VC_REGISTER:
1270         {
1271                 if (!owner->buffer()->lyxvc.inUse())
1272                         owner->buffer()->lyxvc.registrer();
1273         }
1274         break;
1275
1276         case LFUN_VC_CHECKIN:
1277         {
1278                 if (owner->buffer()->lyxvc.inUse()
1279                     && !owner->buffer()->isReadonly())
1280                         owner->buffer()->lyxvc.checkIn();
1281         }
1282         break;
1283
1284         case LFUN_VC_CHECKOUT:
1285         {
1286                 if (owner->buffer()->lyxvc.inUse()
1287                     && owner->buffer()->isReadonly())
1288                         owner->buffer()->lyxvc.checkOut();
1289         }
1290         break;
1291
1292         case LFUN_VC_REVERT:
1293         {
1294                 owner->buffer()->lyxvc.revert();
1295         }
1296         break;
1297
1298         case LFUN_VC_UNDO:
1299         {
1300                 owner->buffer()->lyxvc.undoLast();
1301         }
1302         break;
1303
1304         case LFUN_VC_HISTORY:
1305         {
1306                 owner->getDialogs()->showVCLogFile();
1307                 break;
1308         }
1309
1310         // --- buffers ----------------------------------------
1311
1312         case LFUN_SWITCHBUFFER:
1313                 owner->view()->buffer(bufferlist.getBuffer(argument));
1314                 break;
1315
1316         case LFUN_FILE_NEW:
1317         {
1318                 // servercmd: argument must be <file>:<template>
1319                 Buffer * tmpbuf = NewLyxFile(argument);
1320                 if (tmpbuf)
1321                         owner->view()->buffer(tmpbuf);
1322         }
1323         break;
1324
1325         case LFUN_FILE_OPEN:
1326                 open(argument);
1327                 break;
1328
1329         case LFUN_LATEX_LOG:
1330                 owner->getDialogs()->showLogFile();
1331                 break;
1332
1333         case LFUN_LAYOUT_DOCUMENT:
1334                 owner->getDialogs()->showDocument();
1335                 break;
1336
1337         case LFUN_LAYOUT_PARAGRAPH:
1338                 owner->getDialogs()->showParagraph();
1339                 break;
1340
1341         case LFUN_LAYOUT_CHARACTER:
1342                 owner->getDialogs()->showCharacter();
1343                 break;
1344
1345         case LFUN_LAYOUT_TABULAR:
1346             if (owner->view()->theLockingInset()) {
1347                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1348                     InsetTabular * inset = static_cast<InsetTabular *>
1349                         (owner->view()->theLockingInset());
1350                     inset->openLayoutDialog(owner->view());
1351                 } else if (owner->view()->theLockingInset()->
1352                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1353                     InsetTabular * inset = static_cast<InsetTabular *>(
1354                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1355                     inset->openLayoutDialog(owner->view());
1356                 }
1357             }
1358             break;
1359
1360         case LFUN_LAYOUT_PREAMBLE:
1361                 owner->getDialogs()->showPreamble();
1362                 break;
1363
1364         case LFUN_DROP_LAYOUTS_CHOICE:
1365                 owner->getToolbar()->openLayoutList();
1366                 break;
1367
1368         case LFUN_MENU_OPEN_BY_NAME:
1369                 owner->getMenubar()->openByName(argument);
1370                 break; // RVDK_PATCH_5
1371
1372         case LFUN_SPELLCHECK:
1373                 if (lyxrc.isp_command != "none")
1374                         owner->getDialogs()->showSpellchecker();
1375                 break;
1376
1377         // --- lyxserver commands ----------------------------
1378
1379
1380         case LFUN_GETNAME:
1381                 setMessage(owner->buffer()->fileName());
1382                 lyxerr[Debug::INFO] << "FNAME["
1383                                << owner->buffer()->fileName()
1384                                << "] " << endl;
1385                 break;
1386
1387         case LFUN_NOTIFY:
1388         {
1389                 dispatch_buffer = keyseq.print();
1390                 lyxserver->notifyClient(dispatch_buffer);
1391         }
1392         break;
1393
1394         case LFUN_GOTOFILEROW:
1395         {
1396                 string file_name;
1397                 int row;
1398                 istringstream istr(argument.c_str());
1399                 istr >> file_name >> row;
1400                 // Must replace extension of the file to be .lyx and get full path
1401                 string const s(ChangeExtension(file_name, ".lyx"));
1402
1403                 // Either change buffer or load the file
1404                 if (bufferlist.exists(s)) {
1405                         owner->view()->buffer(bufferlist.getBuffer(s));
1406                 } else {
1407                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1408                 }
1409
1410                 // Set the cursor
1411                 owner->view()->setCursorFromRow(row);
1412
1413                 // Recenter screen
1414                 owner->view()->center();
1415         }
1416         break;
1417
1418         case LFUN_GOTO_PARAGRAPH:
1419         {
1420                 istringstream istr(argument.c_str());
1421
1422                 int id;
1423                 istr >> id;
1424                 Paragraph * par = owner->buffer()->getParFromID(id);
1425                 if (par == 0) {
1426                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1427                                             << id << "]" << endl;
1428                         break;
1429                 } else {
1430                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1431                                             << " found." << endl;
1432                 }
1433
1434                 if (owner->view()->theLockingInset())
1435                         owner->view()->unlockInset(owner->view()->theLockingInset());
1436                 if (par->inInset()) {
1437                         par->inInset()->edit(owner->view());
1438                 }
1439                 // Set the cursor
1440                 owner->view()->getLyXText()->setCursor(owner->view(), par, 0);
1441                 owner->view()->setState();
1442                 owner->showState();
1443
1444                 // Recenter screen
1445                 owner->view()->center();
1446         }
1447         break;
1448
1449         case LFUN_APROPOS:
1450         case LFUN_GETTIP:
1451         {
1452                 int const qa = lyxaction.LookupFunc(argument);
1453                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1454         }
1455         break;
1456
1457         // --- toolbar ----------------------------------
1458         case LFUN_PUSH_TOOLBAR:
1459         {
1460                 int nth = strToInt(argument);
1461                 if (nth <= 0) {
1462                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1463                 } else {
1464                         owner->getToolbar()->push(nth);
1465                 }
1466         }
1467         break;
1468
1469         case LFUN_ADD_TO_TOOLBAR:
1470         {
1471                 if (lyxerr.debugging(Debug::GUI)) {
1472                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1473                                 "argument = `" << argument << '\'' << endl;
1474                 }
1475                 string tmp(argument);
1476                 //lyxerr <<string("Argument: ") + argument);
1477                 //lyxerr <<string("Tmp     : ") + tmp);
1478                 if (tmp.empty()) {
1479                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1480                 } else {
1481                         owner->getToolbar()->add(argument, false);
1482                         owner->getToolbar()->set();
1483                 }
1484         }
1485         break;
1486
1487         // --- insert characters ----------------------------------------
1488
1489         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1490         case LFUN_MATH_EXTERN:
1491         case LFUN_MATH_NUMBER:
1492         case LFUN_MATH_NONUMBER:
1493         case LFUN_MATH_LIMITS:
1494         {
1495                 setErrorMessage(N_("This is only allowed in math mode!"));
1496         }
1497         break;
1498
1499         // passthrough hat and underscore outside mathed:
1500         case LFUN_SUBSCRIPT:
1501                 dispatch(LFUN_SELFINSERT, "_");
1502                 break;
1503         case LFUN_SUPERSCRIPT:
1504                 dispatch(LFUN_SELFINSERT, "^");
1505                 break;
1506
1507         case LFUN_MATH_PANEL:
1508                 owner->getDialogs()->showMathPanel();
1509                 break;
1510
1511         case LFUN_CITATION_CREATE:
1512         {
1513                 InsetCommandParams p("cite");
1514
1515                 if (!argument.empty()) {
1516                         // This should be set at source, ie when typing
1517                         // "citation-insert foo" in the minibuffer.
1518                         // Question: would pybibliographer also need to be
1519                         // changed. Suspect so. Leave as-is therefore.
1520                         if (contains(argument, "|")) {
1521                                 p.setContents(token(argument, '|', 0));
1522                                 p.setOptions( token(argument, '|', 1));
1523                         } else {
1524                                 p.setContents(argument);
1525                         }
1526                         dispatch(LFUN_CITATION_INSERT, p.getAsString());
1527                 } else
1528                         owner->getDialogs()->createCitation(p.getAsString());
1529         }
1530         break;
1531
1532         case LFUN_CHILDOPEN:
1533         {
1534                 string const filename =
1535                         MakeAbsPath(argument,
1536                                     owner->buffer()->filePath());
1537                 setMessage(N_("Opening child document ") +
1538                            MakeDisplayPath(filename) + "...");
1539                 owner->view()->savePosition(0);
1540                 if (bufferlist.exists(filename))
1541                         owner->view()->buffer(bufferlist.getBuffer(filename));
1542                 else
1543                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1544         }
1545         break;
1546
1547         case LFUN_TOGGLECURSORFOLLOW:
1548                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1549                 break;
1550
1551         case LFUN_KMAP_OFF:             // keymap off
1552                 owner->getIntl()->KeyMapOn(false);
1553                 break;
1554
1555         case LFUN_KMAP_PRIM:    // primary keymap
1556                 owner->getIntl()->KeyMapPrim();
1557                 break;
1558
1559         case LFUN_KMAP_SEC:             // secondary keymap
1560                 owner->getIntl()->KeyMapSec();
1561                 break;
1562
1563         case LFUN_KMAP_TOGGLE:  // toggle keymap
1564                 owner->getIntl()->ToggleKeyMap();
1565                 break;
1566
1567         case LFUN_SEQUENCE:
1568         {
1569                 // argument contains ';'-terminated commands
1570                 while (argument.find(';') != string::npos) {
1571                         string first;
1572                         argument = split(argument, first, ';');
1573                         verboseDispatch(first, false);
1574                 }
1575         }
1576         break;
1577
1578         case LFUN_DIALOG_PREFERENCES:
1579                 owner->getDialogs()->showPreferences();
1580                 break;
1581
1582         case LFUN_SAVEPREFERENCES:
1583         {
1584                 Path p(user_lyxdir);
1585                 lyxrc.write("preferences");
1586         }
1587         break;
1588
1589         case LFUN_SCREEN_FONT_UPDATE:
1590         {
1591                 // handle the screen font changes.
1592                 //
1593                 lyxrc.set_font_norm_type();
1594                 fontloader.update();
1595                 // Of course we should only do the resize and the textcache.clear
1596                 // if values really changed...but not very important right now. (Lgb)
1597                 // All visible buffers will need resize
1598                 owner->view()->resize();
1599                 // We also need to empty the textcache so that
1600                 // the buffer will be formatted correctly after
1601                 // a zoom change.
1602                 textcache.clear();
1603         }
1604         break;
1605
1606         case LFUN_SET_COLOR:
1607         {
1608                 string lyx_name;
1609                 string const x11_name = split(argument, lyx_name, ' ');
1610                 if (lyx_name.empty() || x11_name.empty()) {
1611                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1612                                                 " <x11_name>"));
1613                         break;
1614                         }
1615
1616                 bool const graphicsbg_changed =
1617                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1618                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1619
1620                 if (!lcolor.setColor(lyx_name, x11_name)) {
1621                         static string const err1 (N_("Set-color \""));
1622                         static string const err2 (
1623                                 N_("\" failed - color is undefined "
1624                                    "or may not be redefined"));
1625                         setErrorMessage(_(err1) + lyx_name + _(err2));
1626                         break;
1627                 }
1628
1629                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1630
1631                 if (graphicsbg_changed) {
1632                         grfx::GCache & gc = grfx::GCache::get();
1633                         gc.changeDisplay(true);
1634                 }
1635
1636                 owner->view()->repaint();
1637                 break;
1638         }
1639
1640         case LFUN_MESSAGE:
1641                 owner->message(argument);
1642                 break;
1643
1644         case LFUN_MESSAGE_PUSH:
1645                 owner->messagePush(argument);
1646                 break;
1647
1648         case LFUN_MESSAGE_POP:
1649                 owner->messagePop();
1650                 break;
1651
1652         case LFUN_FORKS_SHOW:
1653                 owner->getDialogs()->showForks();
1654                 break;
1655
1656         case LFUN_FORKS_KILL:
1657         {
1658                 if (!isStrInt(argument))
1659                         break;
1660
1661                 pid_t const pid = strToInt(argument);
1662                 ForkedcallsController & fcc = ForkedcallsController::get();
1663                 fcc.kill(pid);
1664                 break;
1665         }
1666
1667         case LFUN_TOOLTIPS_TOGGLE:
1668                 owner->getDialogs()->toggleTooltips();
1669                 break;
1670
1671         default:
1672                 // Then if it was none of the above
1673                 // Trying the BufferView::pimpl dispatch:
1674                 if (!owner->view()->Dispatch(action, argument))
1675                         lyxerr << "A truly unknown func ["
1676                                << lyxaction.getActionName(action) << "]!"
1677                                << endl;
1678                 break;
1679         } // end of switch
1680
1681 exit_with_message:
1682
1683         string const res = getMessage();
1684
1685         if (!res.empty())
1686                 owner->message(_(res));
1687         owner->updateMenubar();
1688         owner->updateToolbar();
1689
1690         return res;
1691 }
1692
1693
1694 void LyXFunc::setupLocalKeymap()
1695 {
1696         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1697         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1698 }
1699
1700
1701 void LyXFunc::menuNew(bool fromTemplate)
1702 {
1703         string initpath = lyxrc.document_path;
1704
1705         if (owner->view()->available()) {
1706                 string const trypath = owner->buffer()->filePath();
1707                 // If directory is writeable, use this as default.
1708                 if (IsDirWriteable(trypath))
1709                         initpath = trypath;
1710         }
1711
1712         static int newfile_number;
1713         string s;
1714
1715         if (lyxrc.new_ask_filename) {
1716                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1717                                    LFUN_SELECT_FILE_SYNC,
1718                         make_pair(string(_("Documents|#o#O")),
1719                                   string(lyxrc.document_path)),
1720                         make_pair(string(_("Templates|#T#t")),
1721                                   string(lyxrc.template_path)));
1722
1723                 FileDialog::Result result =
1724                         fileDlg.Select(initpath,
1725                                        _("*.lyx|LyX Documents (*.lyx)"),
1726                                        _("newfile"));
1727
1728                 if (result.second.empty()) {
1729                         owner->message(_("Canceled."));
1730                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1731                         return;
1732                 }
1733
1734                 // get absolute path of file and make sure the filename ends
1735                 // with .lyx
1736                 s = MakeAbsPath(result.second);
1737                 if (!IsLyXFilename(s))
1738                         s += ".lyx";
1739
1740                 // Check if the document already is open
1741                 if (bufferlist.exists(s)) {
1742                         switch (Alert::askConfirmation(_("Document is already open:"),
1743                                                 MakeDisplayPath(s, 50),
1744                                                 _("Do you want to close that document now?\n"
1745                                                   "('No' will just switch to the open version)")))
1746                         {
1747                         case 1: // Yes: close the document
1748                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1749                                 // If close is canceled, we cancel here too.
1750                                         return;
1751                                 break;
1752                         case 2: // No: switch to the open document
1753                                 owner->view()->buffer(bufferlist.getBuffer(s));
1754                                 return;
1755                         case 3: // Cancel: Do nothing
1756                                 owner->message(_("Canceled."));
1757                                 return;
1758                         }
1759                 }
1760                 // Check whether the file already exists
1761                 FileInfo fi(s);
1762                 if (fi.readable() &&
1763                     Alert::askQuestion(_("File already exists:"),
1764                                 MakeDisplayPath(s, 50),
1765                                 _("Do you want to open the document?"))) {
1766                                 // loads document
1767                         string const disp_fn(MakeDisplayPath(s));
1768
1769                         ostringstream str;
1770                         str << _("Opening  document") << ' '
1771                             << disp_fn << "...";
1772
1773                         owner->message(str.str().c_str());
1774                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1775                         ostringstream str2;
1776                         str2 << _("Document") << ' '
1777                              << disp_fn << ' ' << _("opened.");
1778
1779                         owner->message(str2.str().c_str());
1780
1781                         return;
1782                 }
1783         } else {
1784                 s = AddName(lyxrc.document_path,
1785                             "newfile" + tostr(++newfile_number) + ".lyx");
1786                 FileInfo fi(s);
1787                 while (bufferlist.exists(s) || fi.readable()) {
1788                         ++newfile_number;
1789                         s = AddName(lyxrc.document_path,
1790                                     "newfile" + tostr(newfile_number) +
1791                                     ".lyx");
1792                         fi.newFile(s);
1793                 }
1794         }
1795
1796         // The template stuff
1797         string templname;
1798         if (fromTemplate) {
1799                 FileDialog fileDlg(owner, _("Select template file"),
1800                         LFUN_SELECT_FILE_SYNC,
1801                         make_pair(string(_("Documents|#o#O")),
1802                                   string(lyxrc.document_path)),
1803                         make_pair(string(_("Templates|#T#t")),
1804                                   string(lyxrc.template_path)));
1805
1806                 FileDialog::Result result =
1807                         fileDlg.Select(lyxrc.template_path,
1808                                        _("*.lyx|LyX Documents (*.lyx)"));
1809
1810                 if (result.first == FileDialog::Later)
1811                         return;
1812
1813                 string const fname = result.second;
1814
1815                 if (fname.empty())
1816                         return;
1817                 templname = fname;
1818         }
1819
1820         // find a free buffer
1821         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1822         owner->view()->buffer(bufferlist.newFile(s, templname));
1823 }
1824
1825
1826 void LyXFunc::open(string const & fname)
1827 {
1828         string initpath = lyxrc.document_path;
1829
1830         if (owner->view()->available()) {
1831                 string const trypath = owner->buffer()->filePath();
1832                 // If directory is writeable, use this as default.
1833                 if (IsDirWriteable(trypath))
1834                         initpath = trypath;
1835         }
1836
1837         string filename;
1838
1839         if (fname.empty()) {
1840                 FileDialog fileDlg(owner, _("Select document to open"),
1841                         LFUN_FILE_OPEN,
1842                         make_pair(string(_("Documents|#o#O")),
1843                                   string(lyxrc.document_path)),
1844                         make_pair(string(_("Examples|#E#e")),
1845                                   string(AddPath(system_lyxdir, "examples"))));
1846
1847                 FileDialog::Result result =
1848                         fileDlg.Select(initpath,
1849                                        "*.lyx|LyX Documents (*.lyx)");
1850
1851                 if (result.first == FileDialog::Later)
1852                         return;
1853
1854                 filename = result.second;
1855
1856                 // check selected filename
1857                 if (filename.empty()) {
1858                         owner->message(_("Canceled."));
1859                         return;
1860                 }
1861         } else
1862                 filename = fname;
1863
1864         // get absolute path of file and add ".lyx" to the filename if
1865         // necessary
1866         string const fullpath = FileSearch(string(), filename, "lyx");
1867         if (fullpath.empty()) {
1868                 Alert::alert(_("Error"), _("Could not find file"), filename);
1869                 return;
1870         }
1871
1872         filename = fullpath;
1873
1874         // loads document
1875         string const disp_fn(MakeDisplayPath(filename));
1876
1877         ostringstream str;
1878         str << _("Opening document") << ' ' << disp_fn << "...";
1879
1880         owner->message(str.str().c_str());
1881
1882         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1883         if (openbuf) {
1884                 owner->view()->buffer(openbuf);
1885                 ostringstream str;
1886                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1887                 owner->message(str.str().c_str());
1888         } else {
1889                 ostringstream str;
1890                 str << _("Could not open document") << ' ' << disp_fn;
1891                 owner->message(str.str().c_str());
1892         }
1893 }
1894
1895
1896 void LyXFunc::doImport(string const & argument)
1897 {
1898         string format;
1899         string filename = split(argument, format, ' ');
1900
1901         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1902                             << " file: " << filename << endl;
1903  
1904         // need user interaction
1905         if (filename.empty()) {
1906                 string initpath = lyxrc.document_path;
1907
1908                 if (owner->view()->available()) {
1909                         string const trypath = owner->buffer()->filePath();
1910                         // If directory is writeable, use this as default.
1911                         if (IsDirWriteable(trypath))
1912                                 initpath = trypath;
1913                 }
1914
1915                 string const text = _("Select ") + formats.prettyName(format)
1916                         + _(" file to import");
1917
1918                 FileDialog fileDlg(owner, text,
1919                         LFUN_IMPORT,
1920                         make_pair(string(_("Documents|#o#O")),
1921                                   string(lyxrc.document_path)),
1922                         make_pair(string(_("Examples|#E#e")),
1923                                   string(AddPath(system_lyxdir, "examples"))));
1924
1925                 string const extension = "*." + formats.extension(format)
1926                         + "| " + formats.prettyName(format)
1927                         + " (*." + formats.extension(format) + ")";
1928
1929                 FileDialog::Result result = fileDlg.Select(initpath,
1930                                                            extension);
1931
1932                 if (result.first == FileDialog::Later)
1933                         return;
1934
1935                 filename = result.second;
1936
1937                 // check selected filename
1938                 if (filename.empty())
1939                         owner->message(_("Canceled."));
1940         }
1941
1942         if (filename.empty())
1943                 return;
1944
1945         // get absolute path of file
1946         filename = MakeAbsPath(filename);
1947
1948         string const lyxfile = ChangeExtension(filename, ".lyx");
1949
1950         // Check if the document already is open
1951         if (lyxrc.use_gui && bufferlist.exists(lyxfile)) {
1952                 switch (Alert::askConfirmation(_("Document is already open:"),
1953                                         MakeDisplayPath(lyxfile, 50),
1954                                         _("Do you want to close that document now?\n"
1955                                           "('No' will just switch to the open version)")))
1956                         {
1957                         case 1:
1958                                 // If close is canceled, we cancel here too.
1959                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1960                                         return;
1961                                 break;
1962                         case 2:
1963                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1964                                 return;
1965                         case 3:
1966                                 owner->message(_("Canceled."));
1967                                 return;
1968                         }
1969         }
1970
1971         // if the file exists already, and we didn't do 
1972         // -i lyx thefile.lyx, warn
1973         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1974                 if (!Alert::askQuestion(_("A document by the name"),
1975                         MakeDisplayPath(lyxfile), _("already exists. Overwrite?"))) {
1976                         owner->message(_("Canceled"));
1977                         return;
1978                 }
1979         }
1980
1981         Importer::Import(owner, filename, format);
1982 }
1983
1984
1985 void LyXFunc::reloadBuffer()
1986 {
1987         string const fn = owner->buffer()->fileName();
1988         if (bufferlist.close(owner->buffer()))
1989                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1990 }
1991
1992
1993 void LyXFunc::closeBuffer()
1994 {
1995         if (bufferlist.close(owner->buffer()) && !quitting) {
1996                 if (bufferlist.empty()) {
1997                         // need this otherwise SEGV may occur while trying to
1998                         // set variables that don't exist
1999                         // since there's no current buffer
2000                         owner->getDialogs()->hideBufferDependent();
2001                 } else {
2002                         owner->view()->buffer(bufferlist.first());
2003                 }
2004         }
2005 }
2006
2007
2008 // Each "owner" should have it's own message method. lyxview and
2009 // the minibuffer would use the minibuffer, but lyxserver would
2010 // send an ERROR signal to its client.  Alejandro 970603
2011 // This func is bit problematic when it comes to NLS, to make the
2012 // lyx servers client be language indepenent we must not translate
2013 // strings sent to this func.
2014 void LyXFunc::setErrorMessage(string const & m) const
2015 {
2016         dispatch_buffer = m;
2017         errorstat = true;
2018 }
2019
2020
2021 void LyXFunc::setMessage(string const & m) const
2022 {
2023         dispatch_buffer = m;
2024 }
2025
2026
2027 void LyXFunc::setStatusMessage(string const & m) const
2028 {
2029         status_buffer = m;
2030 }
2031
2032
2033 void LyXFunc::initMiniBuffer()
2034 {
2035         string text = _("Welcome to LyX!");
2036
2037         // When meta-fake key is pressed, show the key sequence so far + "M-".
2038         if (wasMetaKey()) {
2039                 text = keyseq.print();
2040                 text += "M-";
2041         }
2042
2043         // Else, when a non-complete key sequence is pressed,
2044         // show the available options.
2045         if (keyseq.length() > 0 && !keyseq.deleted()) {
2046                 text = keyseq.printOptions();
2047         }
2048
2049         // Else, show the buffer state.
2050         else if (owner->view()->available()) {
2051                 Buffer * tmpbuf = owner->buffer();
2052
2053                 string const nicename =
2054                         MakeDisplayPath(tmpbuf->fileName());
2055                 // Should we do this instead? (kindo like emacs)
2056                 // leaves more room for other information
2057                 text = "LyX: ";
2058                 text += nicename;
2059                 if (tmpbuf->lyxvc.inUse()) {
2060                         text += " [";
2061                         text += tmpbuf->lyxvc.versionString();
2062                         text += ' ';
2063                         text += tmpbuf->lyxvc.locker();
2064                         if (tmpbuf->isReadonly())
2065                                 text += " (RO)";
2066                         text += ']';
2067                 } else if (tmpbuf->isReadonly())
2068                         text += " [RO]";
2069                 if (!tmpbuf->isLyxClean())
2070                         text += _(" (Changed)");
2071         } else {
2072                 if (text != _("Welcome to LyX!")) // this is a hack
2073                         text = _("* No document open *");
2074         }
2075
2076         owner->message(text);
2077 }