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