]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
bug 458 (dtrt with index entry insert)
[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 (lyxrc.display_shortcuts && show_sc) {
789                 if (action != LFUN_SELFINSERT) {
790                         // Put name of command and list of shortcuts
791                         // for it in minibuffer
792                         string comname = lyxaction.getActionName(action);
793
794                         int pseudoaction = action;
795                         bool argsadded = false;
796
797                         if (!argument.empty()) {
798                                 // the pseudoaction is useful for the bindings
799                                 pseudoaction =
800                                         lyxaction.searchActionArg(action,
801                                                                   argument);
802
803                                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
804                                         pseudoaction = action;
805                                 } else {
806                                         comname += " " + argument;
807                                         argsadded = true;
808                                 }
809                         }
810
811                         string const shortcuts =
812                                 toplevel_keymap->findbinding(pseudoaction);
813
814                         if (!shortcuts.empty()) {
815                                 comname += ": " + shortcuts;
816                         } else if (!argsadded && !argument.empty()) {
817                                 comname += " " + argument;
818                         }
819
820                         if (!comname.empty()) {
821                                 comname = strip(comname);
822                                 commandshortcut = "(" + comname + ')';
823                         }
824                 }
825         }
826
827         if (res.empty()) {
828                 if (!commandshortcut.empty()) {
829                         owner->getMiniBuffer()->addSet(commandshortcut);
830                 }
831         } else {
832                 owner->getMiniBuffer()->addSet(' ' + commandshortcut);
833         }
834 }
835
836
837 string const LyXFunc::dispatch(kb_action action, string argument)
838 {
839         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << action
840                               <<"] arg[" << argument << "]" << endl;
841
842         // we have not done anything wrong yet.
843         errorstat = false;
844         dispatch_buffer.erase();
845
846 #ifdef NEW_DISPATCHER
847         // We try do call the most specific dispatcher first:
848         //  1. the lockinginset's dispatch
849         //  2. the bufferview's dispatch
850         //  3. the lyxview's dispatch
851 #endif
852
853         selection_possible = false;
854
855         if (owner->view()->available())
856                 owner->view()->hideCursor();
857
858         // We cannot use this function here
859         if (getStatus(action, argument).disabled()) {
860                 lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: "
861                        << lyxaction.getActionName(action)
862                        << " [" << action << "] is disabled at this location"
863                        << endl;
864                 setErrorMessage(getStatusMessage());
865                 goto exit_with_message;
866         }
867
868         if (owner->view()->available() && owner->view()->theLockingInset()) {
869                 UpdatableInset::RESULT result;
870                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
871                                      (!keyseq.deleted())))
872                 {
873                         UpdatableInset * inset = owner->view()->theLockingInset();
874 #if 1
875                         int inset_x;
876                         int dummy_y;
877                         inset->getCursorPos(owner->view(), inset_x, dummy_y);
878 #endif
879                         if ((action == LFUN_UNKNOWN_ACTION)
880                             && argument.empty()) {
881                                 argument = keyseq.getLastKeyEncoded();
882                         }
883                         // Undo/Redo is a bit tricky for insets.
884                         if (action == LFUN_UNDO) {
885                                 owner->view()->menuUndo();
886                                 goto exit_with_message;
887                         } else if (action == LFUN_REDO) {
888                                 owner->view()->menuRedo();
889                                 goto exit_with_message;
890                         } else if (((result=inset->
891                                      // Hand-over to inset's own dispatch:
892                                      localDispatch(owner->view(), action, argument)) ==
893                                     UpdatableInset::DISPATCHED) ||
894                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
895                                 goto exit_with_message;
896                                         // If UNDISPATCHED, just soldier on
897                         else if (result == UpdatableInset::FINISHED) {
898                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
899                                                 TEXT()->cursorRight(owner->view());
900                                                 moveCursorUpdate(true, false);
901                                                 owner->showState();
902                                         }
903                                         goto exit_with_message;
904                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
905                                 if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
906                                         TEXT()->cursorRight(owner->view());
907                                         moveCursorUpdate(true, false);
908                                         owner->showState();
909                                 }
910                                 goto exit_with_message;
911                         } else if (result == UpdatableInset::FINISHED_UP) {
912                                 if (TEXT()->cursor.irow()->previous()) {
913 #if 1
914                                         TEXT()->setCursorFromCoordinates(
915                                                 owner->view(), TEXT()->cursor.ix() + inset_x,
916                                                 TEXT()->cursor.iy() -
917                                                 TEXT()->cursor.irow()->baseline() - 1);
918                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
919 #else
920                                         TEXT()->cursorUp(owner->view());
921 #endif
922                                         moveCursorUpdate(true, false);
923                                         owner->showState();
924                                 } else {
925                                         owner->view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
926                                 }
927                                 goto exit_with_message;
928                         } else if (result == UpdatableInset::FINISHED_DOWN) {
929                                 if (TEXT()->cursor.irow()->next()) {
930 #if 1
931                                         TEXT()->setCursorFromCoordinates(
932                                                 owner->view(), TEXT()->cursor.ix() + inset_x,
933                                                 TEXT()->cursor.iy() -
934                                                 TEXT()->cursor.irow()->baseline() +
935                                                 TEXT()->cursor.irow()->height() + 1);
936                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
937 #else
938                                         TEXT()->cursorDown(owner->view());
939 #endif
940                                 } else {
941                                         TEXT()->cursorRight(owner->view());
942                                 }
943                                 moveCursorUpdate(true, false);
944                                 owner->showState();
945                                 goto exit_with_message;
946                         }
947 #warning I am not sure this is still right, please have a look! (Jug 20020417)
948                         else { // result == UNDISPATCHED
949                                 //setMessage(N_("Text mode"));
950                                 switch (action) {
951                                 case LFUN_UNKNOWN_ACTION:
952                                 case LFUN_BREAKPARAGRAPH:
953                                 case LFUN_BREAKLINE:
954                                         TEXT()->cursorRight(owner->view());
955                                         owner->view()->setState();
956                                         owner->showState();
957                                         break;
958                                 case LFUN_RIGHT:
959                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
960                                                 TEXT()->cursorRight(owner->view());
961                                                 moveCursorUpdate(true, false);
962                                                 owner->showState();
963                                         }
964                                         goto exit_with_message;
965                                 case LFUN_LEFT:
966                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
967                                                 TEXT()->cursorRight(owner->view());
968                                                 moveCursorUpdate(true, false);
969                                                 owner->showState();
970                                         }
971                                         goto exit_with_message;
972                                 case LFUN_DOWN:
973                                         if (TEXT()->cursor.row()->next())
974                                                 TEXT()->cursorDown(owner->view());
975                                         else
976                                                 TEXT()->cursorRight(owner->view());
977                                         moveCursorUpdate(true, false);
978                                         owner->showState();
979                                         goto exit_with_message;
980                                 default:
981                                         break;
982                                 }
983                         }
984                 }
985         }
986
987         switch (action) {
988
989         case LFUN_ESCAPE:
990         {
991                 if (!owner->view()->available()) break;
992                 // this function should be used always [asierra060396]
993                 UpdatableInset * tli =
994                         owner->view()->theLockingInset();
995                 if (tli) {
996                         UpdatableInset * lock = tli->getLockingInset();
997
998                         if (tli == lock) {
999                                 owner->view()->unlockInset(tli);
1000                                 TEXT()->cursorRight(owner->view());
1001                                 moveCursorUpdate(true, false);
1002                                 owner->showState();
1003                         } else {
1004                                 tli->unlockInsetInInset(owner->view(),
1005                                                         lock,
1006                                                         true);
1007                         }
1008                         finishUndo();
1009                         // Tell the paragraph dialog that we changed paragraph
1010                         owner->getDialogs()->updateParagraph();
1011                 }
1012         }
1013         break;
1014
1015                 // --- Misc -------------------------------------------
1016         case LFUN_WORDFINDFORWARD  :
1017         case LFUN_WORDFINDBACKWARD : {
1018                 static string last_search;
1019                 string searched_string;
1020
1021                 if (!argument.empty()) {
1022                         last_search = argument;
1023                         searched_string = argument;
1024                 } else {
1025                         searched_string = last_search;
1026                 }
1027                 bool fw = (action == LFUN_WORDFINDBACKWARD);
1028                 if (!searched_string.empty()) {
1029                         lyxfind::LyXFind(owner->view(), searched_string, fw);
1030                 }
1031 //              owner->view()->showCursor();
1032         }
1033         break;
1034
1035         case LFUN_PREFIX:
1036         {
1037                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
1038                         owner->view()->update(TEXT(),
1039                                               BufferView::SELECT|BufferView::FITCUR);
1040                 }
1041                 owner->message(keyseq.printOptions());
1042         }
1043         break;
1044
1045         // --- Misc -------------------------------------------
1046         case LFUN_EXEC_COMMAND:
1047         {
1048                 vector<string> allCmds;
1049                 transform(lyxaction.func_begin(), lyxaction.func_end(),
1050                           back_inserter(allCmds), lyx::firster());
1051                 static vector<string> hist;
1052                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
1053                                                   allCmds, hist);
1054         }
1055         break;
1056
1057         case LFUN_CANCEL:                   // RVDK_PATCH_5
1058                 keyseq.reset();
1059                 meta_fake_bit = key_modifier::none;
1060                 if (owner->view()->available())
1061                         // cancel any selection
1062                         dispatch(LFUN_MARK_OFF);
1063                 setMessage(N_("Cancel"));
1064                 break;
1065
1066         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1067         {
1068                 meta_fake_bit = key_modifier::alt;
1069                 setMessage(keyseq.print());
1070         }
1071         break;
1072
1073         case LFUN_READ_ONLY_TOGGLE:
1074                 if (owner->buffer()->lyxvc.inUse()) {
1075                         owner->buffer()->lyxvc.toggleReadOnly();
1076                 } else {
1077                         owner->buffer()->setReadonly(
1078                                 !owner->buffer()->isReadonly());
1079                 }
1080                 break;
1081
1082         case LFUN_CENTER: // this is center and redraw.
1083                 owner->view()->center();
1084                 break;
1085
1086                 // --- Menus -----------------------------------------------
1087         case LFUN_MENUNEW:
1088                 menuNew(false);
1089                 break;
1090
1091         case LFUN_MENUNEWTMPLT:
1092                 menuNew(true);
1093                 break;
1094
1095         case LFUN_CLOSEBUFFER:
1096                 closeBuffer();
1097                 break;
1098
1099         case LFUN_MENUWRITE:
1100                 if (!owner->buffer()->isUnnamed()) {
1101                         ostringstream s1;
1102                         s1 << _("Saving document") << ' '
1103                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1104                         owner->message(s1.str().c_str());
1105                         MenuWrite(owner->view(), owner->buffer());
1106                 } else
1107                         WriteAs(owner->view(), owner->buffer());
1108                 break;
1109
1110         case LFUN_WRITEAS:
1111                 WriteAs(owner->view(), owner->buffer(), argument);
1112                 break;
1113
1114         case LFUN_MENURELOAD:
1115                 reloadBuffer();
1116                 break;
1117
1118         case LFUN_UPDATE:
1119                 Exporter::Export(owner->buffer(), argument, true);
1120                 break;
1121
1122         case LFUN_PREVIEW:
1123                 Exporter::Preview(owner->buffer(), argument);
1124                 break;
1125
1126         case LFUN_BUILDPROG:
1127                 Exporter::Export(owner->buffer(), "program", true);
1128                 break;
1129
1130         case LFUN_RUNCHKTEX:
1131                 MenuRunChktex(owner->buffer());
1132                 break;
1133
1134         case LFUN_MENUPRINT:
1135                 owner->getDialogs()->showPrint();
1136                 break;
1137
1138         case LFUN_EXPORT:
1139                 if (argument == "custom")
1140                         owner->getDialogs()->showSendto();
1141                 else
1142                         Exporter::Export(owner->buffer(), argument, false);
1143                 break;
1144
1145         case LFUN_IMPORT:
1146                 doImport(argument);
1147                 break;
1148
1149         case LFUN_QUIT:
1150                 QuitLyX();
1151                 break;
1152
1153         case LFUN_TOCVIEW:
1154 #if 0
1155         case LFUN_LOFVIEW:
1156         case LFUN_LOTVIEW:
1157         case LFUN_LOAVIEW:
1158 #endif
1159         {
1160                 InsetCommandParams p;
1161
1162 #if 0
1163                 if (action == LFUN_TOCVIEW)
1164 #endif
1165                         p.setCmdName("tableofcontents");
1166 #if 0
1167                 else if (action == LFUN_LOAVIEW)
1168                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1169                 else if (action == LFUN_LOFVIEW)
1170                         p.setCmdName("listoffigures");
1171                 else
1172                         p.setCmdName("listoftables");
1173 #endif
1174                 owner->getDialogs()->createTOC(p.getAsString());
1175                 break;
1176         }
1177
1178         case LFUN_DIALOG_TABULAR_INSERT:
1179                 owner->getDialogs()->showTabularCreate();
1180                 break;
1181
1182         case LFUN_AUTOSAVE:
1183                 AutoSave(owner->view());
1184                 break;
1185
1186         case LFUN_UNDO:
1187                 owner->view()->menuUndo();
1188                 break;
1189
1190         case LFUN_REDO:
1191                 owner->view()->menuRedo();
1192                 break;
1193
1194         case LFUN_MENUSEARCH:
1195                 owner->getDialogs()->showSearch();
1196                 break;
1197
1198         case LFUN_REMOVEERRORS:
1199                 if (owner->view()->removeAutoInsets()) {
1200                         owner->view()->redraw();
1201                         owner->view()->fitCursor();
1202                 }
1203                 break;
1204
1205         case LFUN_DEPTH_MIN:
1206                 changeDepth(owner->view(), TEXT(false), -1);
1207                 break;
1208
1209         case LFUN_DEPTH_PLUS:
1210                 changeDepth(owner->view(), TEXT(false), 1);
1211                 break;
1212
1213         case LFUN_FREE:
1214                 owner->getDialogs()->setUserFreeFont();
1215                 break;
1216
1217         case LFUN_RECONFIGURE:
1218                 Reconfigure(owner->view());
1219                 break;
1220
1221 #if 0
1222         case LFUN_FLOATSOPERATE:
1223                 if (argument == "openfoot")
1224                         owner->view()->allFloats(1,0);
1225                 else if (argument == "closefoot")
1226                         owner->view()->allFloats(0,0);
1227                 else if (argument == "openfig")
1228                         owner->view()->allFloats(1,1);
1229                 else if (argument == "closefig")
1230                         owner->view()->allFloats(0,1);
1231                 break;
1232 #else
1233 #ifdef WITH_WARNINGS
1234 //#warning Find another implementation here (or another lyxfunc)!
1235 #endif
1236 #endif
1237         case LFUN_HELP_ABOUTLYX:
1238                 owner->getDialogs()->showAboutlyx();
1239                 break;
1240
1241         case LFUN_HELP_TEXINFO:
1242                 owner->getDialogs()->showTexinfo();
1243                 break;
1244
1245         case LFUN_HELP_OPEN:
1246         {
1247                 string const arg = argument;
1248                 if (arg.empty()) {
1249                         setErrorMessage(N_("Missing argument"));
1250                         break;
1251                 }
1252                 owner->prohibitInput();
1253                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1254                 if (fname.empty()) {
1255                         lyxerr << "LyX: unable to find documentation file `"
1256                                << arg << "'. Bad installation?" << endl;
1257                         owner->allowInput();
1258                         break;
1259                 }
1260                 ostringstream str;
1261                 str << _("Opening help file") << ' '
1262                     << MakeDisplayPath(fname) << "...";
1263                 owner->message(str.str().c_str());
1264                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1265                 owner->allowInput();
1266                 break;
1267         }
1268
1269                 // --- version control -------------------------------
1270         case LFUN_VC_REGISTER:
1271         {
1272                 if (!owner->buffer()->lyxvc.inUse())
1273                         owner->buffer()->lyxvc.registrer();
1274         }
1275         break;
1276
1277         case LFUN_VC_CHECKIN:
1278         {
1279                 if (owner->buffer()->lyxvc.inUse()
1280                     && !owner->buffer()->isReadonly())
1281                         owner->buffer()->lyxvc.checkIn();
1282         }
1283         break;
1284
1285         case LFUN_VC_CHECKOUT:
1286         {
1287                 if (owner->buffer()->lyxvc.inUse()
1288                     && owner->buffer()->isReadonly())
1289                         owner->buffer()->lyxvc.checkOut();
1290         }
1291         break;
1292
1293         case LFUN_VC_REVERT:
1294         {
1295                 owner->buffer()->lyxvc.revert();
1296         }
1297         break;
1298
1299         case LFUN_VC_UNDO:
1300         {
1301                 owner->buffer()->lyxvc.undoLast();
1302         }
1303         break;
1304
1305         case LFUN_VC_HISTORY:
1306         {
1307                 owner->getDialogs()->showVCLogFile();
1308                 break;
1309         }
1310
1311         // --- buffers ----------------------------------------
1312
1313         case LFUN_SWITCHBUFFER:
1314                 owner->view()->buffer(bufferlist.getBuffer(argument));
1315                 break;
1316
1317         case LFUN_FILE_NEW:
1318         {
1319                 // servercmd: argument must be <file>:<template>
1320                 Buffer * tmpbuf = NewLyxFile(argument);
1321                 if (tmpbuf)
1322                         owner->view()->buffer(tmpbuf);
1323         }
1324         break;
1325
1326         case LFUN_FILE_OPEN:
1327                 open(argument);
1328                 break;
1329
1330         case LFUN_LATEX_LOG:
1331                 owner->getDialogs()->showLogFile();
1332                 break;
1333
1334         case LFUN_LAYOUT_DOCUMENT:
1335                 owner->getDialogs()->showDocument();
1336                 break;
1337
1338         case LFUN_LAYOUT_PARAGRAPH:
1339                 owner->getDialogs()->showParagraph();
1340                 break;
1341
1342         case LFUN_LAYOUT_CHARACTER:
1343                 owner->getDialogs()->showCharacter();
1344                 break;
1345
1346         case LFUN_LAYOUT_TABULAR:
1347             if (owner->view()->theLockingInset()) {
1348                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1349                     InsetTabular * inset = static_cast<InsetTabular *>
1350                         (owner->view()->theLockingInset());
1351                     inset->openLayoutDialog(owner->view());
1352                 } else if (owner->view()->theLockingInset()->
1353                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1354                     InsetTabular * inset = static_cast<InsetTabular *>(
1355                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1356                     inset->openLayoutDialog(owner->view());
1357                 }
1358             }
1359             break;
1360
1361         case LFUN_LAYOUT_PREAMBLE:
1362                 owner->getDialogs()->showPreamble();
1363                 break;
1364
1365         case LFUN_DROP_LAYOUTS_CHOICE:
1366                 owner->getToolbar()->openLayoutList();
1367                 break;
1368
1369         case LFUN_MENU_OPEN_BY_NAME:
1370                 owner->getMenubar()->openByName(argument);
1371                 break; // RVDK_PATCH_5
1372
1373         case LFUN_SPELLCHECK:
1374                 if (lyxrc.isp_command != "none")
1375                         owner->getDialogs()->showSpellchecker();
1376                 break;
1377
1378         // --- lyxserver commands ----------------------------
1379
1380
1381         case LFUN_GETNAME:
1382                 setMessage(owner->buffer()->fileName());
1383                 lyxerr[Debug::INFO] << "FNAME["
1384                                << owner->buffer()->fileName()
1385                                << "] " << endl;
1386                 break;
1387
1388         case LFUN_NOTIFY:
1389         {
1390                 dispatch_buffer = keyseq.print();
1391                 lyxserver->notifyClient(dispatch_buffer);
1392         }
1393         break;
1394
1395         case LFUN_GOTOFILEROW:
1396         {
1397                 string file_name;
1398                 int row;
1399                 istringstream istr(argument.c_str());
1400                 istr >> file_name >> row;
1401                 // Must replace extension of the file to be .lyx and get full path
1402                 string const s(ChangeExtension(file_name, ".lyx"));
1403
1404                 // Either change buffer or load the file
1405                 if (bufferlist.exists(s)) {
1406                         owner->view()->buffer(bufferlist.getBuffer(s));
1407                 } else {
1408                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1409                 }
1410
1411                 // Set the cursor
1412                 owner->view()->setCursorFromRow(row);
1413
1414                 // Recenter screen
1415                 owner->view()->center();
1416         }
1417         break;
1418
1419         case LFUN_GOTO_PARAGRAPH:
1420         {
1421                 istringstream istr(argument.c_str());
1422
1423                 int id;
1424                 istr >> id;
1425                 Paragraph * par = owner->buffer()->getParFromID(id);
1426                 if (par == 0) {
1427                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1428                                             << id << "]" << endl;
1429                         break;
1430                 } else {
1431                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1432                                             << " found." << endl;
1433                 }
1434
1435                 if (owner->view()->theLockingInset())
1436                         owner->view()->unlockInset(owner->view()->theLockingInset());
1437                 if (par->inInset()) {
1438                         par->inInset()->edit(owner->view());
1439                 }
1440                 // Set the cursor
1441                 owner->view()->getLyXText()->setCursor(owner->view(), par, 0);
1442                 owner->view()->setState();
1443                 owner->showState();
1444
1445                 // Recenter screen
1446                 owner->view()->center();
1447         }
1448         break;
1449
1450         case LFUN_APROPOS:
1451         case LFUN_GETTIP:
1452         {
1453                 int const qa = lyxaction.LookupFunc(argument);
1454                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1455         }
1456         break;
1457
1458         // --- toolbar ----------------------------------
1459         case LFUN_PUSH_TOOLBAR:
1460         {
1461                 int nth = strToInt(argument);
1462                 if (nth <= 0) {
1463                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1464                 } else {
1465                         owner->getToolbar()->push(nth);
1466                 }
1467         }
1468         break;
1469
1470         case LFUN_ADD_TO_TOOLBAR:
1471         {
1472                 if (lyxerr.debugging(Debug::GUI)) {
1473                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1474                                 "argument = `" << argument << '\'' << endl;
1475                 }
1476                 string tmp(argument);
1477                 //lyxerr <<string("Argument: ") + argument);
1478                 //lyxerr <<string("Tmp     : ") + tmp);
1479                 if (tmp.empty()) {
1480                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1481                 } else {
1482                         owner->getToolbar()->add(argument, false);
1483                         owner->getToolbar()->set();
1484                 }
1485         }
1486         break;
1487
1488         // --- insert characters ----------------------------------------
1489
1490         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1491         case LFUN_MATH_EXTERN:
1492         case LFUN_MATH_NUMBER:
1493         case LFUN_MATH_NONUMBER:
1494         case LFUN_MATH_LIMITS:
1495         {
1496                 setErrorMessage(N_("This is only allowed in math mode!"));
1497         }
1498         break;
1499
1500         // passthrough hat and underscore outside mathed:
1501         case LFUN_SUBSCRIPT:
1502                 dispatch(LFUN_SELFINSERT, "_");
1503                 break;
1504         case LFUN_SUPERSCRIPT:
1505                 dispatch(LFUN_SELFINSERT, "^");
1506                 break;
1507
1508         case LFUN_MATH_PANEL:
1509                 owner->getDialogs()->showMathPanel();
1510                 break;
1511
1512         case LFUN_CITATION_CREATE:
1513         {
1514                 InsetCommandParams p("cite");
1515
1516                 if (!argument.empty()) {
1517                         // This should be set at source, ie when typing
1518                         // "citation-insert foo" in the minibuffer.
1519                         // Question: would pybibliographer also need to be
1520                         // changed. Suspect so. Leave as-is therefore.
1521                         if (contains(argument, "|")) {
1522                                 p.setContents(token(argument, '|', 0));
1523                                 p.setOptions( token(argument, '|', 1));
1524                         } else {
1525                                 p.setContents(argument);
1526                         }
1527                         dispatch(LFUN_CITATION_INSERT, p.getAsString());
1528                 } else
1529                         owner->getDialogs()->createCitation(p.getAsString());
1530         }
1531         break;
1532
1533         case LFUN_CHILDOPEN:
1534         {
1535                 string const filename =
1536                         MakeAbsPath(argument,
1537                                     owner->buffer()->filePath());
1538                 setMessage(N_("Opening child document ") +
1539                            MakeDisplayPath(filename) + "...");
1540                 owner->view()->savePosition(0);
1541                 if (bufferlist.exists(filename))
1542                         owner->view()->buffer(bufferlist.getBuffer(filename));
1543                 else
1544                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1545         }
1546         break;
1547
1548         case LFUN_TOGGLECURSORFOLLOW:
1549                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1550                 break;
1551
1552         case LFUN_KMAP_OFF:             // keymap off
1553                 owner->getIntl()->KeyMapOn(false);
1554                 break;
1555
1556         case LFUN_KMAP_PRIM:    // primary keymap
1557                 owner->getIntl()->KeyMapPrim();
1558                 break;
1559
1560         case LFUN_KMAP_SEC:             // secondary keymap
1561                 owner->getIntl()->KeyMapSec();
1562                 break;
1563
1564         case LFUN_KMAP_TOGGLE:  // toggle keymap
1565                 owner->getIntl()->ToggleKeyMap();
1566                 break;
1567
1568         case LFUN_SEQUENCE:
1569         {
1570                 // argument contains ';'-terminated commands
1571                 while (argument.find(';') != string::npos) {
1572                         string first;
1573                         argument = split(argument, first, ';');
1574                         verboseDispatch(first, false);
1575                 }
1576         }
1577         break;
1578
1579         case LFUN_DIALOG_PREFERENCES:
1580                 owner->getDialogs()->showPreferences();
1581                 break;
1582
1583         case LFUN_SAVEPREFERENCES:
1584         {
1585                 Path p(user_lyxdir);
1586                 lyxrc.write("preferences");
1587         }
1588         break;
1589
1590         case LFUN_SCREEN_FONT_UPDATE:
1591         {
1592                 // handle the screen font changes.
1593                 //
1594                 lyxrc.set_font_norm_type();
1595                 fontloader.update();
1596                 // Of course we should only do the resize and the textcache.clear
1597                 // if values really changed...but not very important right now. (Lgb)
1598                 // All visible buffers will need resize
1599                 owner->view()->resize();
1600                 // We also need to empty the textcache so that
1601                 // the buffer will be formatted correctly after
1602                 // a zoom change.
1603                 textcache.clear();
1604         }
1605         break;
1606
1607         case LFUN_SET_COLOR:
1608         {
1609                 string lyx_name;
1610                 string const x11_name = split(argument, lyx_name, ' ');
1611                 if (lyx_name.empty() || x11_name.empty()) {
1612                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1613                                                 " <x11_name>"));
1614                         break;
1615                         }
1616
1617                 bool const graphicsbg_changed =
1618                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1619                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1620
1621                 if (!lcolor.setColor(lyx_name, x11_name)) {
1622                         static string const err1 (N_("Set-color \""));
1623                         static string const err2 (
1624                                 N_("\" failed - color is undefined "
1625                                    "or may not be redefined"));
1626                         setErrorMessage(_(err1) + lyx_name + _(err2));
1627                         break;
1628                 }
1629
1630                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1631
1632                 if (graphicsbg_changed) {
1633                         grfx::GCache & gc = grfx::GCache::get();
1634                         gc.changeDisplay(true);
1635                 }
1636
1637                 owner->view()->redraw();
1638                 break;
1639         }
1640
1641         case LFUN_MESSAGE:
1642                 owner->message(argument);
1643                 break;
1644
1645         case LFUN_MESSAGE_PUSH:
1646                 owner->messagePush(argument);
1647                 break;
1648
1649         case LFUN_MESSAGE_POP:
1650                 owner->messagePop();
1651                 break;
1652
1653         case LFUN_FORKS_SHOW:
1654                 owner->getDialogs()->showForks();
1655                 break;
1656
1657         case LFUN_FORKS_KILL:
1658         {
1659                 if (!isStrInt(argument))
1660                         break;
1661
1662                 pid_t const pid = strToInt(argument);
1663                 ForkedcallsController & fcc = ForkedcallsController::get();
1664                 fcc.kill(pid);
1665                 break;
1666         }
1667
1668         case LFUN_TOOLTIPS_TOGGLE:
1669                 owner->getDialogs()->toggleTooltips();
1670                 break;
1671
1672         default:
1673                 // Then if it was none of the above
1674                 // Trying the BufferView::pimpl dispatch:
1675                 if (!owner->view()->Dispatch(action, argument))
1676                         lyxerr << "A truly unknown func ["
1677                                << lyxaction.getActionName(action) << "]!"
1678                                << endl;
1679                 break;
1680         } // end of switch
1681
1682 exit_with_message:
1683
1684         string const res = getMessage();
1685
1686         if (!res.empty())
1687                 owner->message(_(res));
1688         owner->updateMenubar();
1689         owner->updateToolbar();
1690
1691         return res;
1692 }
1693
1694
1695 void LyXFunc::setupLocalKeymap()
1696 {
1697         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1698         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1699 }
1700
1701
1702 void LyXFunc::menuNew(bool fromTemplate)
1703 {
1704         string initpath = lyxrc.document_path;
1705
1706         if (owner->view()->available()) {
1707                 string const trypath = owner->buffer()->filePath();
1708                 // If directory is writeable, use this as default.
1709                 if (IsDirWriteable(trypath))
1710                         initpath = trypath;
1711         }
1712
1713         static int newfile_number;
1714         string s;
1715
1716         if (lyxrc.new_ask_filename) {
1717                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1718                                    LFUN_SELECT_FILE_SYNC,
1719                         make_pair(string(_("Documents|#o#O")),
1720                                   string(lyxrc.document_path)),
1721                         make_pair(string(_("Templates|#T#t")),
1722                                   string(lyxrc.template_path)));
1723
1724                 FileDialog::Result result =
1725                         fileDlg.Select(initpath,
1726                                        _("*.lyx|LyX Documents (*.lyx)"),
1727                                        _("newfile"));
1728
1729                 if (result.second.empty()) {
1730                         owner->message(_("Canceled."));
1731                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1732                         return;
1733                 }
1734
1735                 // get absolute path of file and make sure the filename ends
1736                 // with .lyx
1737                 s = MakeAbsPath(result.second);
1738                 if (!IsLyXFilename(s))
1739                         s += ".lyx";
1740
1741                 // Check if the document already is open
1742                 if (bufferlist.exists(s)) {
1743                         switch (Alert::askConfirmation(_("Document is already open:"),
1744                                                 MakeDisplayPath(s, 50),
1745                                                 _("Do you want to close that document now?\n"
1746                                                   "('No' will just switch to the open version)")))
1747                         {
1748                         case 1: // Yes: close the document
1749                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1750                                 // If close is canceled, we cancel here too.
1751                                         return;
1752                                 break;
1753                         case 2: // No: switch to the open document
1754                                 owner->view()->buffer(bufferlist.getBuffer(s));
1755                                 return;
1756                         case 3: // Cancel: Do nothing
1757                                 owner->message(_("Canceled."));
1758                                 return;
1759                         }
1760                 }
1761                 // Check whether the file already exists
1762                 FileInfo fi(s);
1763                 if (fi.readable() &&
1764                     Alert::askQuestion(_("File already exists:"),
1765                                 MakeDisplayPath(s, 50),
1766                                 _("Do you want to open the document?"))) {
1767                                 // loads document
1768                         string const disp_fn(MakeDisplayPath(s));
1769
1770                         ostringstream str;
1771                         str << _("Opening  document") << ' '
1772                             << disp_fn << "...";
1773
1774                         owner->message(str.str().c_str());
1775                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1776                         ostringstream str2;
1777                         str2 << _("Document") << ' '
1778                              << disp_fn << ' ' << _("opened.");
1779
1780                         owner->message(str2.str().c_str());
1781
1782                         return;
1783                 }
1784         } else {
1785                 s = AddName(lyxrc.document_path,
1786                             "newfile" + tostr(++newfile_number) + ".lyx");
1787                 FileInfo fi(s);
1788                 while (bufferlist.exists(s) || fi.readable()) {
1789                         ++newfile_number;
1790                         s = AddName(lyxrc.document_path,
1791                                     "newfile" + tostr(newfile_number) +
1792                                     ".lyx");
1793                         fi.newFile(s);
1794                 }
1795         }
1796
1797         // The template stuff
1798         string templname;
1799         if (fromTemplate) {
1800                 FileDialog fileDlg(owner, _("Select template file"),
1801                         LFUN_SELECT_FILE_SYNC,
1802                         make_pair(string(_("Documents|#o#O")),
1803                                   string(lyxrc.document_path)),
1804                         make_pair(string(_("Templates|#T#t")),
1805                                   string(lyxrc.template_path)));
1806
1807                 FileDialog::Result result =
1808                         fileDlg.Select(lyxrc.template_path,
1809                                        _("*.lyx|LyX Documents (*.lyx)"));
1810
1811                 if (result.first == FileDialog::Later)
1812                         return;
1813
1814                 string const fname = result.second;
1815
1816                 if (fname.empty())
1817                         return;
1818                 templname = fname;
1819         }
1820
1821         // find a free buffer
1822         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1823         owner->view()->buffer(bufferlist.newFile(s, templname));
1824 }
1825
1826
1827 void LyXFunc::open(string const & fname)
1828 {
1829         string initpath = lyxrc.document_path;
1830
1831         if (owner->view()->available()) {
1832                 string const trypath = owner->buffer()->filePath();
1833                 // If directory is writeable, use this as default.
1834                 if (IsDirWriteable(trypath))
1835                         initpath = trypath;
1836         }
1837
1838         string filename;
1839
1840         if (fname.empty()) {
1841                 FileDialog fileDlg(owner, _("Select document to open"),
1842                         LFUN_FILE_OPEN,
1843                         make_pair(string(_("Documents|#o#O")),
1844                                   string(lyxrc.document_path)),
1845                         make_pair(string(_("Examples|#E#e")),
1846                                   string(AddPath(system_lyxdir, "examples"))));
1847
1848                 FileDialog::Result result =
1849                         fileDlg.Select(initpath,
1850                                        "*.lyx|LyX Documents (*.lyx)");
1851
1852                 if (result.first == FileDialog::Later)
1853                         return;
1854
1855                 filename = result.second;
1856
1857                 // check selected filename
1858                 if (filename.empty()) {
1859                         owner->message(_("Canceled."));
1860                         return;
1861                 }
1862         } else
1863                 filename = fname;
1864
1865         // get absolute path of file and add ".lyx" to the filename if
1866         // necessary
1867         string const fullpath = FileSearch(string(), filename, "lyx");
1868         if (fullpath.empty()) {
1869                 Alert::alert(_("Error"), _("Could not find file"), filename);
1870                 return;
1871         }
1872
1873         filename = fullpath;
1874
1875         // loads document
1876         string const disp_fn(MakeDisplayPath(filename));
1877
1878         ostringstream str;
1879         str << _("Opening document") << ' ' << disp_fn << "...";
1880
1881         owner->message(str.str().c_str());
1882
1883         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1884         if (openbuf) {
1885                 owner->view()->buffer(openbuf);
1886                 ostringstream str;
1887                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1888                 owner->message(str.str().c_str());
1889         } else {
1890                 ostringstream str;
1891                 str << _("Could not open document") << ' ' << disp_fn;
1892                 owner->message(str.str().c_str());
1893         }
1894 }
1895
1896
1897 void LyXFunc::doImport(string const & argument)
1898 {
1899         string format;
1900         string filename = split(argument, format, ' ');
1901
1902         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1903                             << " file: " << filename << endl;
1904  
1905         // need user interaction
1906         if (filename.empty()) {
1907                 string initpath = lyxrc.document_path;
1908
1909                 if (owner->view()->available()) {
1910                         string const trypath = owner->buffer()->filePath();
1911                         // If directory is writeable, use this as default.
1912                         if (IsDirWriteable(trypath))
1913                                 initpath = trypath;
1914                 }
1915
1916                 string const text = _("Select ") + formats.prettyName(format)
1917                         + _(" file to import");
1918
1919                 FileDialog fileDlg(owner, text,
1920                         LFUN_IMPORT,
1921                         make_pair(string(_("Documents|#o#O")),
1922                                   string(lyxrc.document_path)),
1923                         make_pair(string(_("Examples|#E#e")),
1924                                   string(AddPath(system_lyxdir, "examples"))));
1925
1926                 string const extension = "*." + formats.extension(format)
1927                         + "| " + formats.prettyName(format)
1928                         + " (*." + formats.extension(format) + ")";
1929
1930                 FileDialog::Result result = fileDlg.Select(initpath,
1931                                                            extension);
1932
1933                 if (result.first == FileDialog::Later)
1934                         return;
1935
1936                 filename = result.second;
1937
1938                 // check selected filename
1939                 if (filename.empty())
1940                         owner->message(_("Canceled."));
1941         }
1942
1943         if (filename.empty())
1944                 return;
1945
1946         // get absolute path of file
1947         filename = MakeAbsPath(filename);
1948
1949         string const lyxfile = ChangeExtension(filename, ".lyx");
1950
1951         // Check if the document already is open
1952         if (lyxrc.use_gui && bufferlist.exists(lyxfile)) {
1953                 switch (Alert::askConfirmation(_("Document is already open:"),
1954                                         MakeDisplayPath(lyxfile, 50),
1955                                         _("Do you want to close that document now?\n"
1956                                           "('No' will just switch to the open version)")))
1957                         {
1958                         case 1:
1959                                 // If close is canceled, we cancel here too.
1960                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1961                                         return;
1962                                 break;
1963                         case 2:
1964                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1965                                 return;
1966                         case 3:
1967                                 owner->message(_("Canceled."));
1968                                 return;
1969                         }
1970         }
1971
1972         // if the file exists already, and we didn't do 
1973         // -i lyx thefile.lyx, warn
1974         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1975                 if (!Alert::askQuestion(_("A document by the name"),
1976                         MakeDisplayPath(lyxfile), _("already exists. Overwrite?"))) {
1977                         owner->message(_("Canceled"));
1978                         return;
1979                 }
1980         }
1981
1982         Importer::Import(owner, filename, format);
1983 }
1984
1985
1986 void LyXFunc::reloadBuffer()
1987 {
1988         string const fn = owner->buffer()->fileName();
1989         if (bufferlist.close(owner->buffer()))
1990                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1991 }
1992
1993
1994 void LyXFunc::closeBuffer()
1995 {
1996         if (bufferlist.close(owner->buffer()) && !quitting) {
1997                 if (bufferlist.empty()) {
1998                         // need this otherwise SEGV may occur while trying to
1999                         // set variables that don't exist
2000                         // since there's no current buffer
2001                         owner->getDialogs()->hideBufferDependent();
2002                 } else {
2003                         owner->view()->buffer(bufferlist.first());
2004                 }
2005         }
2006 }
2007
2008
2009 // Each "owner" should have it's own message method. lyxview and
2010 // the minibuffer would use the minibuffer, but lyxserver would
2011 // send an ERROR signal to its client.  Alejandro 970603
2012 // This func is bit problematic when it comes to NLS, to make the
2013 // lyx servers client be language indepenent we must not translate
2014 // strings sent to this func.
2015 void LyXFunc::setErrorMessage(string const & m) const
2016 {
2017         dispatch_buffer = m;
2018         errorstat = true;
2019 }
2020
2021
2022 void LyXFunc::setMessage(string const & m) const
2023 {
2024         dispatch_buffer = m;
2025 }
2026
2027
2028 void LyXFunc::setStatusMessage(string const & m) const
2029 {
2030         status_buffer = m;
2031 }
2032
2033
2034 void LyXFunc::initMiniBuffer()
2035 {
2036         string text = _("Welcome to LyX!");
2037
2038         // When meta-fake key is pressed, show the key sequence so far + "M-".
2039         if (wasMetaKey()) {
2040                 text = keyseq.print();
2041                 text += "M-";
2042         }
2043
2044         // Else, when a non-complete key sequence is pressed,
2045         // show the available options.
2046         if (keyseq.length() > 0 && !keyseq.deleted()) {
2047                 text = keyseq.printOptions();
2048         }
2049
2050         // Else, show the buffer state.
2051         else if (owner->view()->available()) {
2052                 Buffer * tmpbuf = owner->buffer();
2053
2054                 string const nicename =
2055                         MakeDisplayPath(tmpbuf->fileName());
2056                 // Should we do this instead? (kindo like emacs)
2057                 // leaves more room for other information
2058                 text = "LyX: ";
2059                 text += nicename;
2060                 if (tmpbuf->lyxvc.inUse()) {
2061                         text += " [";
2062                         text += tmpbuf->lyxvc.versionString();
2063                         text += ' ';
2064                         text += tmpbuf->lyxvc.locker();
2065                         if (tmpbuf->isReadonly())
2066                                 text += " (RO)";
2067                         text += ']';
2068                 } else if (tmpbuf->isReadonly())
2069                         text += " [RO]";
2070                 if (!tmpbuf->isLyxClean())
2071                         text += _(" (Changed)");
2072         } else {
2073                 if (text != _("Welcome to LyX!")) // this is a hack
2074                         text = _("* No document open *");
2075         }
2076
2077         owner->message(text);
2078 }