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