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