]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
127ed00b3023c4295e590a32a1a860dbae57b182
[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                 code = Inset::SPECIALCHAR_CODE;
691                 break;
692         default:
693                 break;
694         }
695         if (code != Inset::NO_CODE 
696             && owner->view()->theLockingInset()
697             && !owner->view()->theLockingInset()->insetAllowed(code)) {
698                 disable = true;
699         }
700
701         if (disable)
702                 flag |= func_status::Disabled;
703         
704         // the font related functions
705         func_status::value_type box = func_status::ToggleOff;
706         LyXFont const & font =
707                 TEXT(false)->real_current_font;
708         switch (action) {
709         case LFUN_EMPH:
710                 if (font.emph() == LyXFont::ON)
711                         box = func_status::ToggleOn;
712                 break;
713         case LFUN_NOUN:
714                 if (font.noun() == LyXFont::ON)
715                         box = func_status::ToggleOn;
716                 break;
717         case LFUN_BOLD:
718                 if (font.series() == LyXFont::BOLD_SERIES)
719                         box = func_status::ToggleOn;
720                 break;
721 #ifndef NO_LATEX
722         case LFUN_TEX:
723                 if (font.latex() == LyXFont::ON)
724                         box = func_status::ToggleOn;
725                 break;
726 #endif
727         case LFUN_READ_ONLY_TOGGLE:
728                 if (buf->isReadonly())
729                         box = func_status::ToggleOn;
730                 break;
731         default:
732                 box = func_status::OK;
733                 break;
734         }
735         flag |= box;
736
737         return flag;
738 }
739
740
741 // temporary dispatch method
742 void LyXFunc::miniDispatch(string const & s) 
743 {
744         if (!s.empty()) {
745                 dispatch(s);
746         }
747 }
748
749
750 string const LyXFunc::dispatch(string const & s) 
751 {
752         // Split command string into command and argument
753         string cmd;
754         string line = frontStrip(s);
755         string const arg = strip(frontStrip(split(line, cmd, ' ')));
756
757         return dispatch(lyxaction.LookupFunc(cmd), arg);
758 }
759
760
761 string const LyXFunc::dispatch(int ac,
762                                string const & do_not_use_this_arg)
763 {
764         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << ac
765                               <<"] arg[" << do_not_use_this_arg << "]" << endl;
766         
767         string argument;
768         kb_action action;
769         
770         // we have not done anything wrong yet.
771         errorstat = false;
772         dispatch_buffer.erase();
773         
774         // if action is a pseudo-action, we need the real action
775         if (lyxaction.isPseudoAction(ac)) {
776                 string tmparg;
777                 action = static_cast<kb_action>
778                         (lyxaction.retrieveActionArg(ac, tmparg));
779                 if (!tmparg.empty())
780                         argument = tmparg;
781         } else {
782                 action = static_cast<kb_action>(ac);
783                 if (!do_not_use_this_arg.empty())
784                         argument = do_not_use_this_arg; // except here
785         }
786
787 #ifdef NEW_DISPATCHER
788         // We try do call the most specific dispatcher first:
789         //  1. the lockinginset's dispatch
790         //  2. the bufferview's dispatch
791         //  3. the lyxview's dispatch
792 #endif
793         
794         selection_possible = false;
795         
796         if (owner->view()->available())
797                 owner->view()->hideCursor();
798
799         // We cannot use this function here
800         if (getStatus(ac, do_not_use_this_arg) & func_status::Disabled)
801                 goto exit_with_message;
802
803
804         if (owner->view()->available() && owner->view()->theLockingInset()) {
805                 UpdatableInset::RESULT result;
806                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
807                                      (keyseq.length >= -1)))
808                 {
809                         if ((action==LFUN_UNKNOWN_ACTION) && argument.empty()){
810                                 argument = keyseq.getiso();
811                         }
812                         // Undo/Redo is a bit tricky for insets.
813                         if (action == LFUN_UNDO) {
814 #ifdef RETHINK_THIS_FOR_NOW_WE_LEAVE_ALL_UNLOCKED
815                                 int slx;
816                                 int sly;
817                                 UpdatableInset * inset = 
818                                         owner->view()->theLockingInset()->getLockingInset();
819                                 int inset_id = inset->id();
820                                 inset->getCursorPos(owner->view(), slx, sly);
821                                 owner->view()->unlockInset(inset);
822 #else
823                                 owner->view()->unlockInset(owner->view()->theLockingInset());
824 #endif
825                                 owner->view()->menuUndo();
826 #ifdef RETHINK_THIS_FOR_NOW_WE_LEAVE_ALL_UNLOCKED
827 #if 0
828                                 if (TEXT()->cursor.par()->
829                                     isInset(TEXT()->cursor.pos())) {
830                                         inset = static_cast<UpdatableInset*>(
831                                                 TEXT()->cursor.par()->
832                                                 getInset(TEXT()->
833                                                          cursor.pos()));
834                                 } else {
835                                         inset = 0;
836                                 }
837 #else
838                                 inset = static_cast<UpdatableInset *>(owner->view()->buffer()->getInsetFromID(inset_id));
839 #endif
840                                 if (inset)
841                                         inset->edit(owner->view(),slx,sly,0);
842 #endif
843                                 return string();
844                         } else if (action == LFUN_REDO) {
845                                 int slx;
846                                 int sly;
847                                 UpdatableInset * inset = owner->view()->
848                                         theLockingInset();
849                                 inset->getCursorPos(owner->view(), slx, sly);
850                                 owner->view()->unlockInset(inset);
851                                 owner->view()->menuRedo();
852                                 inset = static_cast<UpdatableInset*>(
853                                         TEXT()->cursor.par()->
854                                         getInset(TEXT()->
855                                                  cursor.pos()));
856                                 if (inset)
857                                         inset->edit(owner->view(),slx,sly,0); 
858                                 return string();
859                         } else if (((result=owner->view()->theLockingInset()->
860                                    localDispatch(owner->view(), action,
861                                                  argument)) ==
862                                    UpdatableInset::DISPATCHED) ||
863                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
864                                 return string();
865                         else {
866                                 //setMessage(N_("Text mode"));
867                                 switch (action) {
868                                 case LFUN_UNKNOWN_ACTION:
869                                 case LFUN_BREAKPARAGRAPH:
870                                 case LFUN_BREAKLINE:
871                                         TEXT()->cursorRight(owner->view());
872                                         owner->view()->setState();
873                                         owner->showState();
874                                         break;
875                                 case LFUN_RIGHT:
876                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
877                                                 TEXT()->cursorRight(owner->view());
878                                                 moveCursorUpdate(true, false);
879                                                 owner->showState();
880                                         }
881                                         return string();
882                                 case LFUN_LEFT: 
883                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
884                                                 TEXT()->cursorRight(owner->view());
885                                                 moveCursorUpdate(true, false);
886                                                 owner->showState();
887                                         }
888                                         return string();
889                                 case LFUN_DOWN:
890                                         if (TEXT()->cursor.row()->next())
891                                                 TEXT()->cursorDown(owner->view());
892                                         else
893                                                 TEXT()->cursorRight(owner->view());
894                                         moveCursorUpdate(true, false);
895                                         owner->showState();
896                                         return string();
897                                 default:
898                                         break;
899                                 }
900                         }
901                 }
902         }
903
904         lyx::Assert(action != LFUN_SELECT_FILE_SYNC);
905
906         switch (action) {
907                 
908         case LFUN_ESCAPE:
909         {
910                 if (!owner->view()->available()) break;
911                 
912                 // this function should be used always [asierra060396]
913                 UpdatableInset * tli =
914                         owner->view()->theLockingInset();
915                 if (tli) {
916                         UpdatableInset * lock = tli->getLockingInset();
917                         
918                         if (tli == lock) {
919                                 owner->view()->unlockInset(tli);
920                                 TEXT()->cursorRight(owner->view());
921                                 moveCursorUpdate(true, false);
922                                 owner->showState();
923                         } else {
924                                 tli->unlockInsetInInset(owner->view(),
925                                                         lock,
926                                                         true);
927                         }
928                 }
929         }
930         break;
931                         
932                 // --- Misc -------------------------------------------
933         case LFUN_WORDFINDFORWARD  : 
934         case LFUN_WORDFINDBACKWARD : {
935                 static string last_search;
936                 string searched_string;
937             
938                 if (!argument.empty()) {
939                         last_search = argument;
940                         searched_string = argument;
941                 } else {
942                         searched_string = last_search;
943                 }
944                 bool fw = (action == LFUN_WORDFINDBACKWARD);
945                 if (!searched_string.empty()) {
946                         LyXFind(owner->view(), searched_string, fw);
947                 }
948 //              owner->view()->showCursor();
949         }
950         break;
951                 
952         case LFUN_PREFIX:
953         {
954                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
955                         owner->view()->update(TEXT(),
956                                               BufferView::SELECT|BufferView::FITCUR);
957                 }
958                 string buf;
959                 keyseq.print(buf, true);
960                 owner->message(buf);
961         }
962         break;
963
964         // --- Misc -------------------------------------------
965         case LFUN_EXEC_COMMAND:
966         {
967                 std::vector<string> allCmds;
968                 std::transform(lyxaction.func_begin(), lyxaction.func_end(),
969                                std::back_inserter(allCmds), lyx::firster());
970                 static std::vector<string> hist;
971                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
972                                                   allCmds, hist);
973         }
974         break;
975                 
976         case LFUN_CANCEL:                   // RVDK_PATCH_5
977                 keyseq.reset();
978                 meta_fake_bit = 0;
979                 if (owner->view()->available())
980                         // cancel any selection
981                         dispatch(LFUN_MARK_OFF);
982                 setMessage(N_("Cancel"));
983                 break;
984
985         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
986         {
987                 meta_fake_bit = Mod1Mask;
988                 string buf;
989                 keyseq.print(buf, true);
990                 setMessage(buf); // RVDK_PATCH_5
991         }
992         break;  
993
994         case LFUN_READ_ONLY_TOGGLE:
995                 if (owner->buffer()->lyxvc.inUse()) {
996                         owner->buffer()->lyxvc.toggleReadOnly();
997                 } else {
998                         owner->buffer()->setReadonly(
999                                 !owner->buffer()->isReadonly());
1000                 }
1001                 break;
1002                 
1003         case LFUN_CENTER: // this is center and redraw.
1004                 owner->view()->center();
1005                 break;
1006                 
1007                 // --- Menus -----------------------------------------------
1008         case LFUN_MENUNEW:
1009                 menuNew(false);
1010                 break;
1011                 
1012         case LFUN_MENUNEWTMPLT:
1013                 menuNew(true);
1014                 break;
1015                 
1016         case LFUN_CLOSEBUFFER:
1017                 closeBuffer();
1018                 break;
1019                 
1020         case LFUN_MENUWRITE:
1021                 if (!owner->buffer()->isUnnamed()) {
1022                         ostringstream s1;
1023                         s1 << _("Saving document") << ' '
1024                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1025                         owner->message(s1.str().c_str());
1026                         MenuWrite(owner->view(), owner->buffer());
1027                 } else
1028                         WriteAs(owner->view(), owner->buffer());
1029                 break;
1030                 
1031         case LFUN_WRITEAS:
1032                 WriteAs(owner->view(), owner->buffer(), argument);
1033                 break;
1034                 
1035         case LFUN_MENURELOAD:
1036                 reloadBuffer();
1037                 break;
1038                 
1039         case LFUN_UPDATE:
1040                 Exporter::Export(owner->buffer(), argument, true);
1041                 break;
1042
1043         case LFUN_PREVIEW:
1044                 Exporter::Preview(owner->buffer(), argument);
1045                 break;
1046                 
1047         case LFUN_BUILDPROG:
1048                 Exporter::Export(owner->buffer(), "program", true);
1049                 break;
1050                 
1051         case LFUN_RUNCHKTEX:
1052                 MenuRunChktex(owner->buffer());
1053                 break;
1054                                 
1055         case LFUN_MENUPRINT:
1056                 owner->getDialogs()->showPrint();
1057                 break;
1058
1059         case LFUN_EXPORT:
1060                 if (argument == "custom")
1061                         MenuSendto();
1062                 else
1063                         Exporter::Export(owner->buffer(), argument, false);
1064                 break;
1065
1066         case LFUN_IMPORT:
1067                 doImport(argument);
1068                 break;
1069                 
1070         case LFUN_QUIT:
1071                 QuitLyX();
1072                 break;
1073                 
1074         case LFUN_TOCVIEW:
1075 #if 0
1076         case LFUN_LOFVIEW:
1077         case LFUN_LOTVIEW:
1078         case LFUN_LOAVIEW:
1079 #endif
1080         {
1081                 InsetCommandParams p;
1082
1083 #if 0
1084                 if (action == LFUN_TOCVIEW)
1085 #endif
1086                         p.setCmdName("tableofcontents");
1087 #if 0
1088                 else if (action == LFUN_LOAVIEW )
1089                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1090                 else if (action == LFUN_LOFVIEW)
1091                         p.setCmdName("listoffigures");
1092                 else
1093                         p.setCmdName("listoftables");
1094 #endif
1095                 owner->getDialogs()->createTOC(p.getAsString());
1096                 break;
1097         }       
1098
1099         case LFUN_DIALOG_TABULAR_INSERT:
1100                 owner->getDialogs()->showTabularCreate();
1101                 break;
1102                 
1103         case LFUN_FIGURE:
1104                 Figure();
1105                 break;
1106
1107         case LFUN_AUTOSAVE:
1108                 AutoSave(owner->view());
1109                 break;
1110                 
1111         case LFUN_UNDO:
1112                 owner->view()->menuUndo();
1113                 break;
1114                 
1115         case LFUN_REDO:
1116                 owner->view()->menuRedo();
1117                 break;
1118                 
1119         case LFUN_MENUSEARCH:
1120                 owner->getDialogs()->showSearch();
1121                 break;
1122                 
1123         case LFUN_REMOVEERRORS:
1124                 if (owner->view()->removeAutoInsets()) {
1125                         owner->view()->redraw();
1126                         owner->view()->fitCursor(TEXT());
1127                 }
1128                 break;
1129
1130         case LFUN_DEPTH:
1131                 changeDepth(owner->view(), TEXT(false), 0);
1132                 break;
1133                 
1134         case LFUN_DEPTH_MIN:
1135                 changeDepth(owner->view(), TEXT(false), -1);
1136                 break;
1137                 
1138         case LFUN_DEPTH_PLUS:
1139                 changeDepth(owner->view(), TEXT(false), 1);
1140                 break;
1141                 
1142         case LFUN_FREE:
1143                 owner->getDialogs()->setUserFreeFont();
1144                 break;
1145
1146 #ifndef NO_LATEX
1147         case LFUN_TEX:
1148                 Tex(owner->view());
1149                 owner->view()->setState();
1150                 owner->showState();
1151                 break;
1152 #endif
1153                 
1154         case LFUN_RECONFIGURE:
1155                 Reconfigure(owner->view());
1156                 break;
1157
1158 #if 0
1159         case LFUN_FLOATSOPERATE:
1160                 if (argument == "openfoot")
1161                         owner->view()->allFloats(1,0);
1162                 else if (argument == "closefoot")
1163                         owner->view()->allFloats(0,0);
1164                 else if (argument == "openfig")
1165                         owner->view()->allFloats(1,1);
1166                 else if (argument == "closefig")
1167                         owner->view()->allFloats(0,1);
1168                 break;
1169 #else
1170 #ifdef WITH_WARNINGS
1171 #warning Find another implementation here (or another lyxfunc)!
1172 #endif
1173 #endif
1174         case LFUN_HELP_ABOUTLYX:
1175                 owner->getDialogs()->showAboutlyx();
1176                 break;
1177
1178         case LFUN_HELP_COPYRIGHT:
1179         case LFUN_HELP_CREDITS:
1180                 
1181
1182         case LFUN_HELP_OPEN:
1183         {
1184                 string const arg = argument;
1185                 if (arg.empty()) {
1186                         setErrorMessage(N_("Missing argument"));
1187                         break;
1188                 }
1189                 owner->prohibitInput();
1190                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1191                 if (fname.empty()) {
1192                         lyxerr << "LyX: unable to find documentation file `"
1193                                << arg << "'. Bad installation?" << endl;
1194                         owner->allowInput();
1195                         break;
1196                 }
1197                 ostringstream str;
1198                 str << _("Opening help file") << ' '
1199                     << MakeDisplayPath(fname) << "...";
1200                 owner->message(str.str().c_str());
1201                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1202                 owner->allowInput();
1203                 break;
1204         }
1205
1206         case LFUN_HELP_VERSION:
1207         
1208                 // --- version control -------------------------------
1209         case LFUN_VC_REGISTER:
1210         {
1211                 if (!owner->buffer()->lyxvc.inUse())
1212                         owner->buffer()->lyxvc.registrer();
1213         }
1214         break;
1215                 
1216         case LFUN_VC_CHECKIN:
1217         {
1218                 if (owner->buffer()->lyxvc.inUse()
1219                     && !owner->buffer()->isReadonly())
1220                         owner->buffer()->lyxvc.checkIn();
1221         }
1222         break;
1223                 
1224         case LFUN_VC_CHECKOUT:
1225         {
1226                 if (owner->buffer()->lyxvc.inUse()
1227                     && owner->buffer()->isReadonly())
1228                         owner->buffer()->lyxvc.checkOut();
1229         }
1230         break;
1231         
1232         case LFUN_VC_REVERT:
1233         {
1234                 owner->buffer()->lyxvc.revert();
1235         }
1236         break;
1237                 
1238         case LFUN_VC_UNDO:
1239         {
1240                 owner->buffer()->lyxvc.undoLast();
1241         }
1242         break;
1243                 
1244         case LFUN_VC_HISTORY:
1245         {
1246                 owner->getDialogs()->showVCLogFile();
1247                 break;
1248         }
1249         
1250         // --- buffers ----------------------------------------
1251
1252         case LFUN_SWITCHBUFFER:
1253                 owner->view()->buffer(bufferlist.getBuffer(argument));
1254                 break;
1255
1256         case LFUN_FILE_NEW:
1257         {
1258                 // servercmd: argument must be <file>:<template>
1259                 Buffer * tmpbuf = NewLyxFile(argument);
1260                 if (tmpbuf)
1261                         owner->view()->buffer(tmpbuf);
1262         }
1263         break;
1264                         
1265         case LFUN_FILE_OPEN:
1266                 open(argument);
1267                 break;
1268
1269         case LFUN_LATEX_LOG:
1270                 owner->getDialogs()->showLogFile();
1271                 break;
1272                 
1273         case LFUN_LAYOUTNO:
1274         {
1275                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1276                 int sel = strToInt(argument);
1277                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1278                 
1279                 // Should this give a setMessage instead?
1280                 if (sel == 0) 
1281                         return string(); // illegal argument
1282
1283                 --sel; // sel 1..., but layout 0...
1284
1285                 // Pretend we got the name instead.
1286                 dispatch(int(LFUN_LAYOUT), 
1287                          textclasslist.NameOfLayout(owner->view()
1288                                                     ->buffer()->params.textclass,
1289                                                     sel));
1290                 return string();
1291         }
1292                 
1293         case LFUN_LAYOUT_DOCUMENT:
1294                 owner->getDialogs()->showDocument();
1295                 break;
1296                 
1297         case LFUN_LAYOUT_PARAGRAPH:
1298                 owner->getDialogs()->showParagraph();
1299                 break;
1300                 
1301         case LFUN_LAYOUT_CHARACTER:
1302                 owner->getDialogs()->showCharacter();
1303                 break;
1304
1305         case LFUN_LAYOUT_TABULAR:
1306             if (owner->view()->theLockingInset()) {
1307                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1308                     InsetTabular * inset = static_cast<InsetTabular *>
1309                         (owner->view()->theLockingInset());
1310                     inset->openLayoutDialog(owner->view());
1311                 } else if (owner->view()->theLockingInset()->
1312                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1313                     InsetTabular * inset = static_cast<InsetTabular *>(
1314                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1315                     inset->openLayoutDialog(owner->view());
1316                 }
1317             }
1318             break;
1319
1320         case LFUN_LAYOUT_PREAMBLE:
1321                 owner->getDialogs()->showPreamble();
1322                 break;
1323                 
1324         case LFUN_LAYOUT_SAVE_DEFAULT:
1325                 MenuLayoutSave(owner->view());
1326                 break;
1327                 
1328         case LFUN_DROP_LAYOUTS_CHOICE:
1329                 owner->getToolbar()->openLayoutList();
1330                 break;
1331
1332         case LFUN_MENU_OPEN_BY_NAME:
1333                 owner->getMenubar()->openByName(argument);
1334                 break; // RVDK_PATCH_5
1335                 
1336         case LFUN_SPELLCHECK:
1337                 if (lyxrc.isp_command != "none")
1338                         owner->getDialogs()->showSpellchecker();
1339                 break;
1340                 
1341         // --- lyxserver commands ----------------------------
1342
1343
1344         case LFUN_GETNAME:
1345                 setMessage(owner->buffer()->fileName());
1346                 lyxerr[Debug::INFO] << "FNAME["
1347                                << owner->buffer()->fileName()
1348                                << "] " << endl;
1349                 break;
1350                 
1351         case LFUN_NOTIFY:
1352         {
1353                 string buf;
1354                 keyseq.print(buf);
1355                 dispatch_buffer = buf;
1356                 lyxserver->notifyClient(dispatch_buffer);
1357         }
1358         break;
1359
1360         case LFUN_GOTOFILEROW:
1361         {
1362 #if 0
1363                 char file_name[100];
1364                 int row;
1365                 ::sscanf(argument.c_str(), " %s %d", file_name, &row);
1366 #else
1367                 string file_name;
1368                 int row;
1369                 istringstream istr(argument.c_str());
1370                 istr >> file_name >> row;
1371 #endif
1372                 // Must replace extension of the file to be .lyx and get full path
1373                 string const s(ChangeExtension(file_name, ".lyx"));
1374
1375                 // Either change buffer or load the file
1376                 if (bufferlist.exists(s)) {
1377                         owner->view()->buffer(bufferlist.getBuffer(s));
1378                 } else {
1379                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1380                 }
1381                 
1382                 // Set the cursor  
1383                 owner->view()->setCursorFromRow(row);
1384
1385                 // Recenter screen
1386                 owner->view()->center();
1387         }
1388         break;
1389
1390         case LFUN_GOTO_PARAGRAPH:
1391         {
1392                 istringstream istr(argument.c_str());
1393
1394                 int id;
1395                 istr >> id;
1396                 Paragraph * par = owner->buffer()->getParFromID(id);
1397                 if (par == 0) {
1398                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1399                                             << id << "]" << std::endl;
1400                         break;
1401                 }
1402
1403                 // Set the cursor
1404                 TEXT()->setCursor(owner->view(), par, 0);
1405                 owner->view()->setState();
1406                 owner->showState();
1407
1408                 // Recenter screen
1409                 owner->view()->center();
1410         }
1411         break;
1412
1413         case LFUN_APROPOS:
1414         case LFUN_GETTIP:
1415         {
1416                 int const qa = lyxaction.LookupFunc(argument);
1417                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1418         }
1419         break;
1420
1421         // --- toolbar ----------------------------------
1422         case LFUN_PUSH_TOOLBAR:
1423         {
1424                 int nth = strToInt(argument);
1425                 if (nth <= 0) {
1426                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1427                 } else {
1428                         owner->getToolbar()->push(nth);
1429                 }
1430         }
1431         break;
1432         
1433         case LFUN_ADD_TO_TOOLBAR:
1434         {
1435                 if (lyxerr.debugging(Debug::GUI)) {
1436                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1437                                 "argument = `" << argument << '\'' << endl;
1438                 }
1439                 string tmp(argument);
1440                 //lyxerr <<string("Argument: ") + argument);
1441                 //lyxerr <<string("Tmp     : ") + tmp);
1442                 if (tmp.empty()) {
1443                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1444                 } else {
1445                         owner->getToolbar()->add(argument, false);
1446                         owner->getToolbar()->set();
1447                 }
1448         }
1449         break;
1450         
1451         // --- insert characters ----------------------------------------
1452
1453         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1454         
1455         // Greek mode     
1456         case LFUN_GREEK:
1457         {
1458                 if (!greek_kb_flag) {
1459                         greek_kb_flag = 1;
1460                         setMessage(N_("Math greek mode on"));
1461                 } else
1462                         greek_kb_flag = 0;
1463         }  
1464         break;
1465       
1466         // Greek keyboard      
1467         case LFUN_GREEK_TOGGLE:
1468         {
1469                 greek_kb_flag = greek_kb_flag ? 0 : 2;
1470                 if (greek_kb_flag) {
1471                         setMessage(N_("Math greek keyboard on"));
1472                 } else {
1473                         setMessage(N_("Math greek keyboard off"));
1474                 }
1475         }
1476         break;
1477         
1478         case LFUN_MATH_EXTERN:
1479         case LFUN_MATH_NUMBER:
1480         case LFUN_MATH_NONUMBER:
1481         case LFUN_MATH_LIMITS:
1482         {
1483                 setErrorMessage(N_("This is only allowed in math mode!"));
1484         }
1485         break;
1486
1487         case LFUN_MATH_PANEL:
1488                 owner->getDialogs()->showMathPanel();
1489                 break;
1490         
1491         case LFUN_CITATION_CREATE:
1492         {
1493                 InsetCommandParams p( "cite" );
1494                 
1495                 if (!argument.empty()) {
1496                         // This should be set at source, ie when typing
1497                         // "citation-insert foo" in the minibuffer.
1498                         // Question: would pybibliographer also need to be
1499                         // changed. Suspect so. Leave as-is therefore.
1500                         if (contains(argument, "|")) {
1501                                 p.setContents( token(argument, '|', 0) );
1502                                 p.setOptions(  token(argument, '|', 1) );
1503                         } else {
1504                                 p.setContents( argument );
1505                         }
1506                         dispatch(LFUN_CITATION_INSERT, p.getAsString());
1507                 } else
1508                         owner->getDialogs()->createCitation( p.getAsString() );
1509         }
1510         break;
1511                     
1512         case LFUN_CHILDOPEN:
1513         {
1514                 string const filename =
1515                         MakeAbsPath(argument, 
1516                                     OnlyPath(owner->buffer()->fileName()));
1517                 setMessage(N_("Opening child document ") +
1518                            MakeDisplayPath(filename) + "...");
1519                 owner->view()->savePosition(0);
1520                 if (bufferlist.exists(filename))
1521                         owner->view()->buffer(bufferlist.getBuffer(filename));
1522                 else
1523                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1524         }
1525         break;
1526
1527         case LFUN_TOGGLECURSORFOLLOW:
1528                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1529                 break;
1530                 
1531         case LFUN_KMAP_OFF:             // keymap off
1532                 owner->getIntl()->KeyMapOn(false);
1533                 break;
1534                 
1535         case LFUN_KMAP_PRIM:    // primary keymap
1536                 owner->getIntl()->KeyMapPrim();
1537                 break;
1538                 
1539         case LFUN_KMAP_SEC:             // secondary keymap
1540                 owner->getIntl()->KeyMapSec();
1541                 break;
1542                 
1543         case LFUN_KMAP_TOGGLE:  // toggle keymap
1544                 owner->getIntl()->ToggleKeyMap();
1545                 break;
1546
1547         case LFUN_SEQUENCE: 
1548         {
1549                 // argument contains ';'-terminated commands
1550                 while (argument.find(';') != string::npos) {
1551                         string first;
1552                         argument = split(argument, first, ';');
1553                         dispatch(first);
1554                 }
1555         }
1556         break;
1557
1558         case LFUN_DIALOG_PREFERENCES:
1559                 owner->getDialogs()->showPreferences();
1560                 break;
1561                 
1562         case LFUN_SAVEPREFERENCES:
1563         {
1564                 Path p(user_lyxdir);
1565                 lyxrc.write("preferences");
1566         }
1567         break;
1568
1569         case LFUN_SCREEN_FONT_UPDATE:
1570         {
1571                 // handle the screen font changes.
1572                 // 
1573                 lyxrc.set_font_norm_type();
1574                 fontloader.update();
1575                 // Of course we should only do the resize and the textcache.clear
1576                 // if values really changed...but not very important right now. (Lgb)
1577                 // All visible buffers will need resize
1578                 owner->resize();
1579                 // We also need to empty the textcache so that
1580                 // the buffer will be formatted correctly after
1581                 // a zoom change.
1582                 textcache.clear();
1583         }
1584         break;
1585
1586         case LFUN_SET_COLOR:
1587         {
1588                 string lyx_name;
1589                 string const x11_name = split(argument, lyx_name, ' ');
1590                 if (lyx_name.empty() || x11_name.empty()) {
1591                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1592                                                 " <x11_name>"));
1593                         break;
1594                         }
1595
1596                 if (!lcolor.setColor(lyx_name, x11_name)) {
1597                         static string const err1 (N_("Set-color \""));
1598                         static string const err2 (
1599                                 N_("\" failed - color is undefined "
1600                                    "or may not be redefined"));
1601                         setErrorMessage(_(err1) + lyx_name + _(err2));
1602                         break;
1603                 }
1604                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1605                 owner->view()->redraw();
1606                 break;
1607         }
1608
1609         case LFUN_MESSAGE:
1610                 owner->message(argument);
1611                 break;
1612
1613         case LFUN_MESSAGE_PUSH:
1614                 owner->messagePush(argument);
1615                 break;
1616
1617         case LFUN_MESSAGE_POP:
1618                 owner->messagePop();
1619                 break;
1620
1621         default:
1622                 // Then if it was none of the above
1623                 if (!owner->view()->Dispatch(action, argument))
1624                         lyxerr << "A truly unknown func ["
1625                                << lyxaction.getActionName(action) << "]!"
1626                                << endl;
1627                 break;
1628         } // end of switch
1629
1630 exit_with_message:
1631
1632         commandshortcut.erase();
1633         
1634         if (lyxrc.display_shortcuts && show_sc) {
1635                 if (action != LFUN_SELFINSERT) {
1636                         // Put name of command and list of shortcuts
1637                         // for it in minibuffer
1638                         string comname = lyxaction.getActionName(action);
1639
1640                         int pseudoaction = action;
1641                         bool argsadded = false;
1642
1643                         if (!argument.empty()) {
1644                                 // If we have the command with argument, 
1645                                 // this is better
1646                                 pseudoaction = 
1647                                         lyxaction.searchActionArg(action,
1648                                                                   argument);
1649
1650                                 if (pseudoaction == -1) {
1651                                         pseudoaction = action;
1652                                 } else {
1653                                         comname += " " + argument;
1654                                         argsadded = true;
1655                                 }
1656                         }
1657
1658                         string const shortcuts =
1659                                 toplevel_keymap->findbinding(pseudoaction);
1660
1661                         if (!shortcuts.empty()) {
1662                                 comname += ": " + shortcuts;
1663                         } else if (!argsadded) {
1664                                 comname += " " + argument;
1665                         }
1666
1667                         if (!comname.empty()) {
1668                                 comname = strip(comname);
1669                                 commandshortcut = "(" + comname + ')';
1670
1671                                 // Here we could even add a small pause,
1672                                 // to annoy the user and make him learn
1673                                 // the shortcuts.
1674                                 // No! That will just annoy, not teach
1675                                 // anything. The user will read the messages
1676                                 // if they are interested. (Asger)
1677                         }
1678                 }
1679         }
1680
1681         string const res = getMessage();
1682
1683         if (res.empty()) {
1684                 if (!commandshortcut.empty()) {
1685                         owner->getMiniBuffer()->addSet(commandshortcut);
1686                 }
1687         } else {
1688                 string const msg(_(res) + ' ' + commandshortcut);
1689                 owner->message(msg);
1690         }
1691
1692         return res;
1693 }
1694
1695
1696 void LyXFunc::setupLocalKeymap()
1697 {
1698         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1699         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1700 }
1701
1702
1703 void LyXFunc::menuNew(bool fromTemplate)
1704 {
1705         string initpath = lyxrc.document_path;
1706
1707         if (owner->view()->available()) {
1708                 string const trypath = owner->buffer()->filepath;
1709                 // If directory is writeable, use this as default.
1710                 if (IsDirWriteable(trypath) == 1)
1711                         initpath = trypath;
1712         }
1713
1714         static int newfile_number;
1715         string s;
1716         
1717         if (lyxrc.new_ask_filename) {
1718                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1719                                    LFUN_SELECT_FILE_SYNC,
1720                         make_pair(string(_("Documents")),
1721                                   string(lyxrc.document_path)),
1722                         make_pair(string(_("Templates")),
1723                                   string(lyxrc.template_path)));
1724
1725                 FileDialog::Result result =
1726                         fileDlg.Select(initpath,
1727                                        _("*.lyx|LyX Documents (*.lyx)"),
1728                                        _("newfile"));
1729         
1730                 if (result.second.empty()) {
1731                         owner->message(_("Canceled."));
1732                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1733                         return;
1734                 }
1735         
1736                 // get absolute path of file and make sure the filename ends
1737                 // with .lyx
1738                 s = MakeAbsPath(result.second);
1739                 if (!IsLyXFilename(s))
1740                         s += ".lyx";
1741
1742                 // Check if the document already is open
1743                 if (bufferlist.exists(s)) {
1744                         switch (AskConfirmation(_("Document is already open:"),
1745                                                 MakeDisplayPath(s, 50),
1746                                                 _("Do you want to close that document now?\n"
1747                                                   "('No' will just switch to the open version)")))
1748                         {
1749                         case 1: // Yes: close the document
1750                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1751                                 // If close is canceled, we cancel here too.
1752                                         return;
1753                                 break;
1754                         case 2: // No: switch to the open document
1755                                 owner->view()->buffer(bufferlist.getBuffer(s));
1756                                 return;
1757                         case 3: // Cancel: Do nothing
1758                                 owner->message(_("Canceled."));
1759                                 return;
1760                         }
1761                 }
1762                 // Check whether the file already exists
1763                 FileInfo fi(s);
1764                 if (fi.readable() &&
1765                     AskQuestion(_("File already exists:"), 
1766                                 MakeDisplayPath(s, 50),
1767                                 _("Do you want to open the document?"))) {
1768                                 // loads document
1769                         string const disp_fn(MakeDisplayPath(s));
1770                         
1771                         ostringstream str;
1772                         str << _("Opening  document") << ' '
1773                             << disp_fn << "...";
1774                         
1775                         owner->message(str.str().c_str());
1776                         //XFlush(fl_get_display());
1777                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1778                         ostringstream str2;
1779                         str2 << _("Document") << ' '
1780                              << disp_fn << ' ' << _("opened.");
1781                         
1782                         owner->message(str2.str().c_str());
1783                         
1784                         return;
1785                 }
1786         } else {
1787                 s = AddName(lyxrc.document_path,
1788                             "newfile" + tostr(++newfile_number) + ".lyx");
1789                 FileInfo fi(s);
1790                 while (bufferlist.exists(s) || fi.readable()) {
1791                         ++newfile_number;
1792                         s = AddName(lyxrc.document_path,
1793                                     "newfile" + tostr(newfile_number) +
1794                                     ".lyx");
1795                         fi.newFile(s);
1796                 }
1797         }
1798
1799         // The template stuff
1800         string templname;
1801         if (fromTemplate) {
1802                 FileDialog fileDlg(owner, _("Select template file"),
1803                         LFUN_SELECT_FILE_SYNC,
1804                         make_pair(string(_("Documents")),
1805                                   string(lyxrc.document_path)),
1806                         make_pair(string(_("Templates")),
1807                                   string(lyxrc.template_path)));
1808
1809                 FileDialog::Result result =
1810                         fileDlg.Select(lyxrc.template_path,
1811                                        _("*.lyx|LyX Documents (*.lyx)"));
1812         
1813                 if (result.first == FileDialog::Later)
1814                         return;
1815
1816                 string const fname = result.second;
1817
1818                 if (fname.empty()) 
1819                         return;
1820                 templname = fname;
1821         }
1822   
1823         // find a free buffer
1824         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1825         owner->view()->buffer(bufferlist.newFile(s, templname));
1826 }
1827
1828
1829 void LyXFunc::open(string const & fname)
1830 {
1831         string initpath = lyxrc.document_path;
1832   
1833         if (owner->view()->available()) {
1834                 string const trypath = owner->buffer()->filepath;
1835                 // If directory is writeable, use this as default.
1836                 if (IsDirWriteable(trypath) == 1)
1837                         initpath = trypath;
1838         }
1839
1840         string filename;
1841  
1842         if (fname.empty()) {
1843                 FileDialog fileDlg(owner, _("Select document to open"),
1844                         LFUN_FILE_OPEN,
1845                         make_pair(string(_("Documents")),
1846                                   string(lyxrc.document_path)),
1847                         make_pair(string(_("Examples")),
1848                                   string(AddPath(system_lyxdir, "examples"))));
1849
1850                 FileDialog::Result result =
1851                         fileDlg.Select(initpath,
1852                                        "*.lyx|LyX Documents (*.lyx)");
1853         
1854                 if (result.first == FileDialog::Later)
1855                         return;
1856
1857                 filename = result.second;
1858  
1859                 // check selected filename
1860                 if (filename.empty()) {
1861                         owner->message(_("Canceled."));
1862                         return;
1863                 }
1864         } else
1865                 filename = fname;
1866
1867         // get absolute path of file and add ".lyx" to the filename if
1868         // necessary
1869         filename = FileSearch(string(), filename, "lyx");
1870
1871         // loads document
1872         string const disp_fn(MakeDisplayPath(filename));
1873
1874         ostringstream str;
1875         str << _("Opening document") << ' ' << disp_fn << "...";
1876         
1877         owner->message(str.str().c_str());
1878
1879         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1880         if (openbuf) {
1881                 owner->view()->buffer(openbuf);
1882                 ostringstream str;
1883                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1884                 owner->message(str.str().c_str());
1885         } else {
1886                 ostringstream str;
1887                 str << _("Could not open docuent") << ' ' << disp_fn;
1888                 owner->message(str.str().c_str());
1889         }
1890 }
1891
1892
1893 // checks for running without gui are missing.
1894 void LyXFunc::doImport(string const & argument)
1895 {
1896         string format;
1897         string filename = split(argument, format, ' ');
1898         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format 
1899                             << " file: " << filename << endl;
1900
1901         if (filename.empty()) { // need user interaction
1902                 string initpath = lyxrc.document_path;
1903                 
1904                 if (owner->view()->available()) {
1905                         string const trypath = owner->buffer()->filepath;
1906                         // If directory is writeable, use this as default.
1907                         if (IsDirWriteable(trypath) == 1)
1908                                 initpath = trypath;
1909                 }
1910
1911                 string const text = _("Select ") + formats.PrettyName(format)
1912                         + _(" file to import");
1913
1914                 FileDialog fileDlg(owner, text, 
1915                         LFUN_IMPORT,
1916                         make_pair(string(_("Documents")),
1917                                   string(lyxrc.document_path)),
1918                         make_pair(string(_("Examples")),
1919                                   string(AddPath(system_lyxdir, "examples"))));
1920                         
1921                 string const extension = "*." + formats.Extension(format)
1922                         + "| " + formats.PrettyName(format)
1923                         + " (*." + formats.Extension(format) + ")";
1924
1925                 FileDialog::Result result = fileDlg.Select(initpath,
1926                                                            extension);
1927
1928                 if (result.first == FileDialog::Later)
1929                         return;
1930
1931                 filename = result.second;
1932  
1933                 // check selected filename
1934                 if (filename.empty())
1935                         owner->message(_("Canceled."));
1936         }
1937
1938         // still no filename? abort
1939         if (filename.empty()) 
1940                 return;
1941
1942         // get absolute path of file
1943         filename = MakeAbsPath(filename);
1944
1945         string const lyxfile = ChangeExtension(filename, ".lyx");
1946
1947         // Check if the document already is open
1948         if (bufferlist.exists(lyxfile)) {
1949                 switch (AskConfirmation(_("Document is already open:"), 
1950                                         MakeDisplayPath(lyxfile, 50),
1951                                         _("Do you want to close that document now?\n"
1952                                           "('No' will just switch to the open version)")))
1953                         {
1954                         case 1: // Yes: close the document
1955                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1956                                 // If close is canceled, we cancel here too.
1957                                         return;
1958                                 break;
1959                         case 2: // No: switch to the open document
1960                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1961                                 return;
1962                         case 3: // Cancel: Do nothing
1963                                 owner->message(_("Canceled."));
1964                                 return;
1965                         }
1966         }
1967
1968         // Check if a LyX document by the same root exists in filesystem
1969         FileInfo const f(lyxfile, true);
1970         if (f.exist() && !AskQuestion(_("A document by the name"), 
1971                                       MakeDisplayPath(lyxfile),
1972                                       _("already exists. Overwrite?"))) {
1973                 owner->message(_("Canceled"));
1974                 return;
1975         }
1976         // filename should be valid now
1977         
1978         Importer::Import(owner, filename, format);
1979 }
1980
1981
1982 void LyXFunc::reloadBuffer()
1983 {
1984         string const fn = owner->buffer()->fileName();
1985         if (bufferlist.close(owner->buffer()))
1986                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1987 }
1988
1989
1990 void LyXFunc::closeBuffer()
1991 {
1992         if (bufferlist.close(owner->buffer()) && !quitting) {
1993                 if (bufferlist.empty()) {
1994                         // need this otherwise SEGV may occur while trying to
1995                         // set variables that don't exist
1996                         // since there's no current buffer
1997                         owner->getDialogs()->hideBufferDependent();
1998                 } else {
1999                         owner->view()->buffer(bufferlist.first());
2000                 }
2001         }
2002 }
2003
2004
2005 // Each "owner" should have it's own message method. lyxview and
2006 // the minibuffer would use the minibuffer, but lyxserver would
2007 // send an ERROR signal to its client.  Alejandro 970603
2008 // This func is bit problematic when it comes to NLS, to make the
2009 // lyx servers client be language indepenent we must not translate
2010 // strings sent to this func.
2011 void LyXFunc::setErrorMessage(string const & m) const
2012 {
2013         dispatch_buffer = m;
2014         errorstat = true;
2015 }
2016
2017
2018 void LyXFunc::setMessage(string const & m)
2019 {
2020         dispatch_buffer = m;
2021 }
2022
2023
2024 void LyXFunc::initMiniBuffer() 
2025 {
2026         string text = _("Welcome to LyX!");
2027         
2028         // When meta-fake key is pressed, show the key sequence so far + "M-".
2029         if (wasMetaKey()) {
2030                 keyseqStr();
2031                 text += "M-";
2032         }
2033
2034         // Else, when a non-complete key sequence is pressed,
2035         // show the available options.
2036         else if (keyseqUncomplete()) 
2037                 text = keyseqOptions();
2038    
2039         // Else, show the buffer state.
2040         else if (owner->view()->available()) {
2041                 Buffer * tmpbuf = owner->buffer();
2042                 
2043                 string const nicename = 
2044                         MakeDisplayPath(tmpbuf->fileName());
2045                 // Should we do this instead? (kindo like emacs)
2046                 // leaves more room for other information
2047                 text = "LyX: ";
2048                 text += nicename;
2049                 if (tmpbuf->lyxvc.inUse()) {
2050                         text += " [";
2051                         text += tmpbuf->lyxvc.version();
2052                         text += ' ';
2053                         text += tmpbuf->lyxvc.locker();
2054                         if (tmpbuf->isReadonly())
2055                                 text += " (RO)";
2056                         text += ']';
2057                 } else if (tmpbuf->isReadonly())
2058                         text += " [RO]";
2059                 if (!tmpbuf->isLyxClean())
2060                         text += _(" (Changed)");
2061         } else {
2062                 if (text != _("Welcome to LyX!")) // this is a hack
2063                         text = _("* No document open *");
2064         }
2065         
2066         owner->message(text);
2067 }
2068