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