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