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