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