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