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