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