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