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