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