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