]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
func_status cleanup from Martin; fix small configure bug
[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 FuncStatus LyXFunc::getStatus(int ac) const
347 {
348         return getStatus(ac, string());
349 }
350
351 FuncStatus LyXFunc::getStatus(int ac,
352                               string const & not_to_use_arg) const
353 {
354         kb_action action;
355         FuncStatus flag;
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; // except here
365         }
366         
367         if (action == LFUN_UNKNOWN_ACTION) {
368                 setErrorMessage(N_("Unknown action"));
369                 return flag.unknown(true);
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.disabled(true);
384                         }
385                 } else {
386                         // no
387                         setErrorMessage(N_("Command not allowed with"
388                                            "out any document open"));
389                         return flag.disabled(true);
390                 }
391         }
392
393         // I would really like to avoid having this switch and rather try to
394         // encode this in the function itself.
395         bool disable = false;
396         switch (action) {
397         case LFUN_MENUPRINT:
398                 disable = !Exporter::IsExportable(buf, "dvi")
399                         || lyxrc.print_command == "none";
400                 break;
401         case LFUN_EXPORT:
402                 disable = argument == "fax" &&
403                         !Exporter::IsExportable(buf, argument);
404                 break;
405         case LFUN_UNDO:
406                 disable = buf->undostack.empty();
407                 break;
408         case LFUN_REDO:
409                 disable = buf->redostack.empty();
410                 break;
411         case LFUN_SPELLCHECK:
412                 disable = lyxrc.isp_command == "none";
413                 break;
414 #ifndef HAVE_LIBAIKSAURUS
415         case LFUN_THESAURUS_ENTRY:
416                 disable = true;
417                 break;
418 #endif
419         case LFUN_RUNCHKTEX:
420                 disable = lyxrc.chktex_command == "none";
421                 break;
422         case LFUN_BUILDPROG:
423                 disable = !Exporter::IsExportable(buf, "program");
424                 break;
425
426         case LFUN_LAYOUT_TABULAR:
427                 disable = true;
428                 if (owner->view()->theLockingInset()) {
429                         disable = (owner->view()->theLockingInset()->lyxCode() != Inset::TABULAR_CODE) &&
430                                 !owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE);
431                 }
432                 break;
433
434         case LFUN_TABULAR_FEATURE:
435                 disable = true;
436                 if (owner->view()->theLockingInset()) {
437                         FuncStatus ret;
438                         ret.disabled(true);
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                         FuncStatus ret;
454
455                         disable = true;
456                         ret = inset.getStatus(argument);
457                         if (ret.onoff(true) || ret.onoff(false)) flag.setOnOff(false);
458                 }
459                 break;
460
461         case LFUN_VC_REGISTER:
462                 disable = buf->lyxvc.inUse();
463                 break;
464         case LFUN_VC_CHECKIN:
465                 disable = !buf->lyxvc.inUse() || buf->isReadonly();
466                 break;
467         case LFUN_VC_CHECKOUT:
468                 disable = !buf->lyxvc.inUse() || !buf->isReadonly();
469                 break;
470         case LFUN_VC_REVERT:
471         case LFUN_VC_UNDO:
472         case LFUN_VC_HISTORY:
473                 disable = !buf->lyxvc.inUse();
474                 break;
475         case LFUN_BOOKMARK_GOTO:
476                 disable =  !owner->view()->
477                         isSavedPosition(strToUnsignedInt(argument));
478                 break;
479
480
481         case LFUN_INSET_TOGGLE:
482                 disable = (TEXT(false)->getInset() == 0);
483                 break;
484
485         case LFUN_MATH_VALIGN: {
486     // I think this test can be simplified (Andre')
487                 // mathcursor is != 0  iff we are in math mode
488                 //Inset * tli = owner->view()->theLockingInset();
489                 //if (tli && (tli->lyxCode() == Inset::MATH_CODE 
490                 //          || tli->lyxCode() == Inset::MATHMACRO_CODE)) {
491                 //
492                 if (mathcursor) {
493                         char align = mathcursor->valign();
494                         if (align == '\0') {
495                                 disable = true;
496                                 break;
497                         }
498                         if (argument.empty()) {
499                                 flag.clear();
500                                 break;
501                         }
502                         if (!contains("tcb", argument[0])) {
503                                 disable = true;
504                                 break;
505                         }
506                         flag.setOnOff(argument[0] == align);
507                 } else
508                         disable = true;
509                 break;
510         }
511         case LFUN_MATH_HALIGN: {
512                 //Inset * tli = owner->view()->theLockingInset();
513                 //if (tli && (tli->lyxCode() == Inset::MATH_CODE 
514                 //          || tli->lyxCode() == Inset::MATHMACRO_CODE)) {
515                 if (mathcursor) {
516                         char align = mathcursor->halign();
517                         if (align == '\0') {
518                                 disable = true;
519                                 break;
520                         }
521                         if (argument.empty()) {
522                                 flag.clear();
523                                 break;
524                         }
525                         if (!contains("lcr", argument[0])) {
526                                 disable = true;
527                                 break;
528                         }
529                         flag.setOnOff(argument[0] == align);
530                 } else
531                         disable = true;
532                 break;
533         }
534         case LFUN_MATH_MUTATE: {
535                 Inset * tli = owner->view()->theLockingInset();
536                 if (tli && (tli->lyxCode() == Inset::MATH_CODE)) {
537                         MathInsetTypes type = mathcursor->formula()->getType();
538                         if (argument == "inline") {
539                                 flag.setOnOff(type == LM_OT_SIMPLE);
540                         } else if (argument == "display") {
541                                 flag.setOnOff(type == LM_OT_EQUATION);
542                         } else if (argument == "eqnarray") {
543                                 flag.setOnOff(type == LM_OT_EQNARRAY);
544                         } else if (argument == "align") {
545                                 flag.setOnOff(type == LM_OT_ALIGN);
546                         } else {
547                                 disable = true;
548                         }
549                 } else
550                         disable = true;
551                 break;
552         }
553
554         // we just need to be in math mode to enable that
555         case LFUN_MATH_SIZE: 
556         case LFUN_MATH_SPACE:
557         case LFUN_MATH_LIMITS: 
558         case LFUN_MATH_NONUMBER: 
559         case LFUN_MATH_NUMBER:
560                 disable = !mathcursor;
561                 break;
562
563         // we need to be math mode and a math array for that
564         // Hack: halign produces non-zero result iff we are in a math array
565         case LFUN_MATH_ROW_INSERT: 
566         case LFUN_MATH_ROW_DELETE: 
567         case LFUN_MATH_COLUMN_INSERT: 
568         case LFUN_MATH_COLUMN_DELETE: 
569                 disable = !mathcursor || !mathcursor->halign();
570                 break;
571
572         default:
573                 break;
574         }
575
576         // the functions which insert insets
577         Inset::Code code = Inset::NO_CODE;
578         switch (action) {
579         case LFUN_INSET_TEXT:
580                 code = Inset::TEXT_CODE;
581                 break;
582         case LFUN_INSET_ERT:
583                 code = Inset::ERT_CODE;         
584                 break;
585         case LFUN_FIGURE:
586         case LFUN_INSET_GRAPHICS:
587                 code = Inset::GRAPHICS_CODE;
588                 break;
589         case LFUN_INSET_FOOTNOTE:
590                 code = Inset::FOOT_CODE;
591                 break;
592         case LFUN_DIALOG_TABULAR_INSERT:
593         case LFUN_INSET_TABULAR:
594                 code = Inset::TABULAR_CODE;
595                 break;
596         case LFUN_INSET_EXTERNAL:
597                 code = Inset::EXTERNAL_CODE;
598                 break;
599         case LFUN_INSET_MARGINAL:
600                 code = Inset::MARGIN_CODE;
601                 break;
602         case LFUN_INSET_MINIPAGE:
603                 code = Inset::MINIPAGE_CODE;
604                 break;
605         case LFUN_INSET_FLOAT:
606         case LFUN_INSET_WIDE_FLOAT:
607                 code = Inset::FLOAT_CODE;
608                 break;
609         case LFUN_FLOAT_LIST:
610                 code = Inset::FLOAT_LIST_CODE;
611                 break;
612 #if 0
613         case LFUN_INSET_LIST:
614                 code = Inset::LIST_CODE;
615                 break;
616         case LFUN_INSET_THEOREM:
617                 code = Inset::THEOREM_CODE;
618                 break;
619 #endif
620         case LFUN_INSET_CAPTION:
621                 code = Inset::CAPTION_CODE;
622                 break;
623         case LFUN_INSERT_NOTE:
624                 code = Inset::IGNORE_CODE;
625                 break;
626         case LFUN_INSERT_LABEL:
627                 code = Inset::LABEL_CODE;
628                 break;
629         case LFUN_REF_INSERT:
630                 code = Inset::REF_CODE;
631                 break;
632         case LFUN_CITATION_CREATE:
633         case LFUN_CITATION_INSERT:
634                 code = Inset::CITE_CODE;
635                 break;
636         case LFUN_INSERT_BIBTEX:
637                 code = Inset::BIBTEX_CODE;
638                 break;
639         case LFUN_INDEX_INSERT:
640         case LFUN_INDEX_INSERT_LAST:
641         case LFUN_INDEX_CREATE:
642                 code = Inset::INDEX_CODE;
643                 break;
644         case LFUN_INDEX_PRINT:
645                 code = Inset::INDEX_PRINT_CODE;
646                 break;
647         case LFUN_CHILD_INSERT:
648                 code = Inset::INCLUDE_CODE;
649                 break;
650         case LFUN_TOC_INSERT:
651                 code = Inset::TOC_CODE;
652                 break;
653         case LFUN_PARENTINSERT:
654                 code = Inset::PARENT_CODE;
655                 break;
656         case LFUN_HTMLURL:
657         case LFUN_URL:
658         case LFUN_INSERT_URL:
659                 code = Inset::URL_CODE;
660                 break;
661         case LFUN_QUOTE:
662                 // always allow this, since we will inset a raw quote
663                 // if an inset is not allowed.
664                 break;
665         case LFUN_HYPHENATION:
666         case LFUN_LIGATURE_BREAK:
667         case LFUN_HFILL:
668         case LFUN_MENU_SEPARATOR:
669         case LFUN_LDOTS:
670         case LFUN_END_OF_SENTENCE:
671         case LFUN_PROTECTEDSPACE:
672                 code = Inset::SPECIALCHAR_CODE;
673                 break;
674         default:
675                 break;
676         }
677         if (code != Inset::NO_CODE 
678             && owner->view()->theLockingInset()
679             && !owner->view()->theLockingInset()->insetAllowed(code)) {
680                 disable = true;
681         }
682
683         if (disable)
684                         flag.disabled(true);
685         
686         // A few general toggles
687         switch (action) {
688         case LFUN_READ_ONLY_TOGGLE:
689                 flag.setOnOff(buf->isReadonly());
690                 break;
691         case LFUN_APPENDIX:
692                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
693                 break;
694         default:
695                 break;
696         }
697
698         // the font related toggles
699         if (!mathcursor) {
700                 LyXFont const & font = TEXT(false)->real_current_font;
701                 switch (action) {
702                 case LFUN_EMPH:
703                         flag.setOnOff(font.emph() == LyXFont::ON);
704                         break;
705                 case LFUN_NOUN:
706                         flag.setOnOff(font.noun() == LyXFont::ON);
707                         break;
708                 case LFUN_BOLD:
709                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
710                         break;
711                 case LFUN_SANS:
712                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
713                         break;
714                 case LFUN_ROMAN:
715                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
716                         break;
717                 case LFUN_CODE:
718                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
719                         break;
720                 default:
721                         break;
722                 }
723         }
724         else {
725                 MathTextCodes tc = mathcursor->getLastCode();
726                 switch (action) {
727                 case LFUN_BOLD:
728                         flag.setOnOff(tc == LM_TC_BF);
729                         break;
730                 case LFUN_SANS:
731                         flag.setOnOff(tc == LM_TC_SF);
732                         break;
733                 case LFUN_EMPH:
734                         flag.setOnOff(tc == LM_TC_CAL);
735                         break;
736                 case LFUN_ROMAN:
737                         flag.setOnOff(tc == LM_TC_RM);
738                         break;
739                 case LFUN_CODE:
740                         flag.setOnOff(tc == LM_TC_TT);
741                         break;
742                 case LFUN_NOUN:
743                         flag.setOnOff(tc == LM_TC_BB);
744                         break;
745                 case LFUN_DEFAULT:
746                         flag.setOnOff(tc == LM_TC_VAR);
747                         break;
748                 default:
749                         break;
750                 }
751         }
752         
753         return flag;
754 }
755
756
757 // temporary dispatch method
758 void LyXFunc::miniDispatch(string const & s) 
759 {
760         string s2(frontStrip(strip(s))); 
761  
762         if (!s2.empty()) {
763                 dispatch(s2);
764         }
765 }
766
767
768 string const LyXFunc::dispatch(string const & s) 
769 {
770         // Split command string into command and argument
771         string cmd;
772         string line = frontStrip(s);
773         string const arg = strip(frontStrip(split(line, cmd, ' ')));
774
775         int action = lyxaction.LookupFunc(cmd);
776  
777         if (action == LFUN_UNKNOWN_ACTION) {
778                 string const msg = string(_("Unknown function ("))
779                         + cmd + ")";
780                 owner->message(msg);
781                 return string();
782         } else {
783                 return dispatch(action, arg);
784         } 
785 }
786
787
788 string const LyXFunc::dispatch(int ac,
789                                string const & do_not_use_this_arg)
790 {
791         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << ac
792                               <<"] arg[" << do_not_use_this_arg << "]" << endl;
793         
794         string argument;
795         kb_action action;
796         
797         // we have not done anything wrong yet.
798         errorstat = false;
799         dispatch_buffer.erase();
800         
801         // if action is a pseudo-action, we need the real action
802         if (lyxaction.isPseudoAction(ac)) {
803                 string tmparg;
804                 action = static_cast<kb_action>
805                         (lyxaction.retrieveActionArg(ac, tmparg));
806                 if (!tmparg.empty())
807                         argument = tmparg;
808         } else {
809                 action = static_cast<kb_action>(ac);
810                 if (!do_not_use_this_arg.empty())
811                         argument = do_not_use_this_arg; // except here
812         }
813
814  
815 #ifdef NEW_DISPATCHER
816         // We try do call the most specific dispatcher first:
817         //  1. the lockinginset's dispatch
818         //  2. the bufferview's dispatch
819         //  3. the lyxview's dispatch
820 #endif
821         
822         selection_possible = false;
823         
824         if (owner->view()->available())
825                 owner->view()->hideCursor();
826
827         // We cannot use this function here
828         if (getStatus(ac, do_not_use_this_arg).disabled()) {
829                 lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: "
830                        << lyxaction.getActionName(ac)
831                        << " [" << ac << "] is disabled at this location"
832                        << endl;
833                 goto exit_with_message;
834         }
835
836         if (owner->view()->available() && owner->view()->theLockingInset()) {
837                 UpdatableInset::RESULT result;
838                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
839                                      (!keyseq.deleted())))
840                 {
841                         if ((action==LFUN_UNKNOWN_ACTION) && argument.empty()){
842                                 argument = keyseq.getiso();
843                         }
844                         // Undo/Redo is a bit tricky for insets.
845                         if (action == LFUN_UNDO) {
846                                 owner->view()->menuUndo();
847                                 return string();
848                         } else if (action == LFUN_REDO) {
849                                 owner->view()->menuRedo();
850                                 return string();
851                         } else if (((result=owner->view()->theLockingInset()->
852                                      localDispatch(owner->view(), action, argument)) ==
853                                     UpdatableInset::DISPATCHED) ||
854                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
855                                 return string();
856                         else if (result == UpdatableInset::FINISHED) {
857                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
858                                                 TEXT()->cursorRight(owner->view());
859                                                 moveCursorUpdate(true, false);
860                                                 owner->showState();
861                                         }
862                                         return string();
863                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
864                                 if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
865                                         TEXT()->cursorRight(owner->view());
866                                         moveCursorUpdate(true, false);
867                                         owner->showState();
868                                 }
869                                 return string();
870                         } else if (result == UpdatableInset::FINISHED_UP) {
871                                 if (TEXT()->cursor.row()->previous()) {
872                                         TEXT()->cursorUp(owner->view());
873                                         moveCursorUpdate(true, false);
874                                         owner->showState();
875                                 }
876                                 return string();
877                         } else if (result == UpdatableInset::FINISHED_DOWN) {
878                                 if (TEXT()->cursor.row()->next())
879                                         TEXT()->cursorDown(owner->view());
880                                 else
881                                         TEXT()->cursorRight(owner->view());
882                                 moveCursorUpdate(true, false);
883                                 owner->showState();
884                                 return string();
885                         } else {
886                                 //setMessage(N_("Text mode"));
887                                 switch (action) {
888                                 case LFUN_UNKNOWN_ACTION:
889                                 case LFUN_BREAKPARAGRAPH:
890                                 case LFUN_BREAKLINE:
891                                         TEXT()->cursorRight(owner->view());
892                                         owner->view()->setState();
893                                         owner->showState();
894                                         break;
895                                 case LFUN_RIGHT:
896                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
897                                                 TEXT()->cursorRight(owner->view());
898                                                 moveCursorUpdate(true, false);
899                                                 owner->showState();
900                                         }
901                                         return string();
902                                 case LFUN_LEFT: 
903                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
904                                                 TEXT()->cursorRight(owner->view());
905                                                 moveCursorUpdate(true, false);
906                                                 owner->showState();
907                                         }
908                                         return string();
909                                 case LFUN_DOWN:
910                                         if (TEXT()->cursor.row()->next())
911                                                 TEXT()->cursorDown(owner->view());
912                                         else
913                                                 TEXT()->cursorRight(owner->view());
914                                         moveCursorUpdate(true, false);
915                                         owner->showState();
916                                         return string();
917                                 default:
918                                         break;
919                                 }
920                         }
921                 }
922         }
923
924         switch (action) {
925                 
926         case LFUN_ESCAPE:
927         {
928                 if (!owner->view()->available()) break;
929                 // this function should be used always [asierra060396]
930                 UpdatableInset * tli =
931                         owner->view()->theLockingInset();
932                 if (tli) {
933                         UpdatableInset * lock = tli->getLockingInset();
934                         
935                         if (tli == lock) {
936                                 owner->view()->unlockInset(tli);
937                                 TEXT()->cursorRight(owner->view());
938                                 moveCursorUpdate(true, false);
939                                 owner->showState();
940                         } else {
941                                 tli->unlockInsetInInset(owner->view(),
942                                                         lock,
943                                                         true);
944                         }
945                         finishUndo();
946                 }
947         }
948         break;
949                         
950                 // --- Misc -------------------------------------------
951         case LFUN_WORDFINDFORWARD  : 
952         case LFUN_WORDFINDBACKWARD : {
953                 static string last_search;
954                 string searched_string;
955             
956                 if (!argument.empty()) {
957                         last_search = argument;
958                         searched_string = argument;
959                 } else {
960                         searched_string = last_search;
961                 }
962                 bool fw = (action == LFUN_WORDFINDBACKWARD);
963                 if (!searched_string.empty()) {
964                         LyXFind(owner->view(), searched_string, fw);
965                 }
966 //              owner->view()->showCursor();
967         }
968         break;
969                 
970         case LFUN_PREFIX:
971         {
972                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
973                         owner->view()->update(TEXT(),
974                                               BufferView::SELECT|BufferView::FITCUR);
975                 }
976                 owner->message(keyseq.print());
977         }
978         break;
979
980         // --- Misc -------------------------------------------
981         case LFUN_EXEC_COMMAND:
982         {
983                 std::vector<string> allCmds;
984                 std::transform(lyxaction.func_begin(), lyxaction.func_end(),
985                                std::back_inserter(allCmds), lyx::firster());
986                 static std::vector<string> hist;
987                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
988                                                   allCmds, hist);
989         }
990         break;
991                 
992         case LFUN_CANCEL:                   // RVDK_PATCH_5
993                 keyseq.reset();
994                 meta_fake_bit = 0;
995                 if (owner->view()->available())
996                         // cancel any selection
997                         dispatch(LFUN_MARK_OFF);
998                 setMessage(N_("Cancel"));
999                 break;
1000
1001         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1002         {
1003                 meta_fake_bit = Mod1Mask;
1004                 setMessage(keyseq.print());
1005         }
1006         break;  
1007
1008         case LFUN_READ_ONLY_TOGGLE:
1009                 if (owner->buffer()->lyxvc.inUse()) {
1010                         owner->buffer()->lyxvc.toggleReadOnly();
1011                 } else {
1012                         owner->buffer()->setReadonly(
1013                                 !owner->buffer()->isReadonly());
1014                 }
1015                 break;
1016                 
1017         case LFUN_CENTER: // this is center and redraw.
1018                 owner->view()->center();
1019                 break;
1020                 
1021                 // --- Menus -----------------------------------------------
1022         case LFUN_MENUNEW:
1023                 menuNew(false);
1024                 break;
1025                 
1026         case LFUN_MENUNEWTMPLT:
1027                 menuNew(true);
1028                 break;
1029                 
1030         case LFUN_CLOSEBUFFER:
1031                 closeBuffer();
1032                 break;
1033                 
1034         case LFUN_MENUWRITE:
1035                 if (!owner->buffer()->isUnnamed()) {
1036                         ostringstream s1;
1037                         s1 << _("Saving document") << ' '
1038                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1039                         owner->message(s1.str().c_str());
1040                         MenuWrite(owner->view(), owner->buffer());
1041                 } else
1042                         WriteAs(owner->view(), owner->buffer());
1043                 break;
1044                 
1045         case LFUN_WRITEAS:
1046                 WriteAs(owner->view(), owner->buffer(), argument);
1047                 break;
1048                 
1049         case LFUN_MENURELOAD:
1050                 reloadBuffer();
1051                 break;
1052                 
1053         case LFUN_UPDATE:
1054                 Exporter::Export(owner->buffer(), argument, true);
1055                 break;
1056
1057         case LFUN_PREVIEW:
1058                 Exporter::Preview(owner->buffer(), argument);
1059                 break;
1060                 
1061         case LFUN_BUILDPROG:
1062                 Exporter::Export(owner->buffer(), "program", true);
1063                 break;
1064                 
1065         case LFUN_RUNCHKTEX:
1066                 MenuRunChktex(owner->buffer());
1067                 break;
1068                                 
1069         case LFUN_MENUPRINT:
1070                 owner->getDialogs()->showPrint();
1071                 break;
1072
1073         case LFUN_EXPORT:
1074                 if (argument == "custom")
1075                         MenuSendto();
1076                 else
1077                         Exporter::Export(owner->buffer(), argument, false);
1078                 break;
1079
1080         case LFUN_IMPORT:
1081                 doImport(argument);
1082                 break;
1083                 
1084         case LFUN_QUIT:
1085                 QuitLyX();
1086                 break;
1087                 
1088         case LFUN_TOCVIEW:
1089 #if 0
1090         case LFUN_LOFVIEW:
1091         case LFUN_LOTVIEW:
1092         case LFUN_LOAVIEW:
1093 #endif
1094         {
1095                 InsetCommandParams p;
1096
1097 #if 0
1098                 if (action == LFUN_TOCVIEW)
1099 #endif
1100                         p.setCmdName("tableofcontents");
1101 #if 0
1102                 else if (action == LFUN_LOAVIEW )
1103                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1104                 else if (action == LFUN_LOFVIEW)
1105                         p.setCmdName("listoffigures");
1106                 else
1107                         p.setCmdName("listoftables");
1108 #endif
1109                 owner->getDialogs()->createTOC(p.getAsString());
1110                 break;
1111         }       
1112
1113         case LFUN_DIALOG_TABULAR_INSERT:
1114                 owner->getDialogs()->showTabularCreate();
1115                 break;
1116                 
1117         case LFUN_FIGURE:
1118                 Figure();
1119                 break;
1120
1121         case LFUN_AUTOSAVE:
1122                 AutoSave(owner->view());
1123                 break;
1124                 
1125         case LFUN_UNDO:
1126                 owner->view()->menuUndo();
1127                 break;
1128                 
1129         case LFUN_REDO:
1130                 owner->view()->menuRedo();
1131                 break;
1132                 
1133         case LFUN_MENUSEARCH:
1134                 owner->getDialogs()->showSearch();
1135                 break;
1136                 
1137         case LFUN_REMOVEERRORS:
1138                 if (owner->view()->removeAutoInsets()) {
1139                         owner->view()->redraw();
1140                         owner->view()->fitCursor();
1141                 }
1142                 break;
1143
1144         case LFUN_DEPTH:
1145                 changeDepth(owner->view(), TEXT(false), 0);
1146                 break;
1147                 
1148         case LFUN_DEPTH_MIN:
1149                 changeDepth(owner->view(), TEXT(false), -1);
1150                 break;
1151                 
1152         case LFUN_DEPTH_PLUS:
1153                 changeDepth(owner->view(), TEXT(false), 1);
1154                 break;
1155                 
1156         case LFUN_FREE:
1157                 owner->getDialogs()->setUserFreeFont();
1158                 break;
1159
1160         case LFUN_RECONFIGURE:
1161                 Reconfigure(owner->view());
1162                 break;
1163
1164 #if 0
1165         case LFUN_FLOATSOPERATE:
1166                 if (argument == "openfoot")
1167                         owner->view()->allFloats(1,0);
1168                 else if (argument == "closefoot")
1169                         owner->view()->allFloats(0,0);
1170                 else if (argument == "openfig")
1171                         owner->view()->allFloats(1,1);
1172                 else if (argument == "closefig")
1173                         owner->view()->allFloats(0,1);
1174                 break;
1175 #else
1176 #ifdef WITH_WARNINGS
1177 //#warning Find another implementation here (or another lyxfunc)!
1178 #endif
1179 #endif
1180         case LFUN_HELP_ABOUTLYX:
1181                 owner->getDialogs()->showAboutlyx();
1182                 break;
1183
1184         case LFUN_HELP_TEXINFO:
1185                 owner->getDialogs()->showTexinfo();
1186                 break;
1187
1188         case LFUN_HELP_OPEN:
1189         {
1190                 string const arg = argument;
1191                 if (arg.empty()) {
1192                         setErrorMessage(N_("Missing argument"));
1193                         break;
1194                 }
1195                 owner->prohibitInput();
1196                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1197                 if (fname.empty()) {
1198                         lyxerr << "LyX: unable to find documentation file `"
1199                                << arg << "'. Bad installation?" << endl;
1200                         owner->allowInput();
1201                         break;
1202                 }
1203                 ostringstream str;
1204                 str << _("Opening help file") << ' '
1205                     << MakeDisplayPath(fname) << "...";
1206                 owner->message(str.str().c_str());
1207                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1208                 owner->allowInput();
1209                 break;
1210         }
1211
1212                 // --- version control -------------------------------
1213         case LFUN_VC_REGISTER:
1214         {
1215                 if (!owner->buffer()->lyxvc.inUse())
1216                         owner->buffer()->lyxvc.registrer();
1217         }
1218         break;
1219                 
1220         case LFUN_VC_CHECKIN:
1221         {
1222                 if (owner->buffer()->lyxvc.inUse()
1223                     && !owner->buffer()->isReadonly())
1224                         owner->buffer()->lyxvc.checkIn();
1225         }
1226         break;
1227                 
1228         case LFUN_VC_CHECKOUT:
1229         {
1230                 if (owner->buffer()->lyxvc.inUse()
1231                     && owner->buffer()->isReadonly())
1232                         owner->buffer()->lyxvc.checkOut();
1233         }
1234         break;
1235         
1236         case LFUN_VC_REVERT:
1237         {
1238                 owner->buffer()->lyxvc.revert();
1239         }
1240         break;
1241                 
1242         case LFUN_VC_UNDO:
1243         {
1244                 owner->buffer()->lyxvc.undoLast();
1245         }
1246         break;
1247                 
1248         case LFUN_VC_HISTORY:
1249         {
1250                 owner->getDialogs()->showVCLogFile();
1251                 break;
1252         }
1253         
1254         // --- buffers ----------------------------------------
1255
1256         case LFUN_SWITCHBUFFER:
1257                 owner->view()->buffer(bufferlist.getBuffer(argument));
1258                 break;
1259
1260         case LFUN_FILE_NEW:
1261         {
1262                 // servercmd: argument must be <file>:<template>
1263                 Buffer * tmpbuf = NewLyxFile(argument);
1264                 if (tmpbuf)
1265                         owner->view()->buffer(tmpbuf);
1266         }
1267         break;
1268                         
1269         case LFUN_FILE_OPEN:
1270                 open(argument);
1271                 break;
1272
1273         case LFUN_LATEX_LOG:
1274                 owner->getDialogs()->showLogFile();
1275                 break;
1276                 
1277         case LFUN_LAYOUT_DOCUMENT:
1278                 owner->getDialogs()->showDocument();
1279                 break;
1280                 
1281         case LFUN_LAYOUT_PARAGRAPH:
1282                 owner->getDialogs()->showParagraph();
1283                 break;
1284                 
1285         case LFUN_LAYOUT_CHARACTER:
1286                 owner->getDialogs()->showCharacter();
1287                 break;
1288
1289         case LFUN_LAYOUT_TABULAR:
1290             if (owner->view()->theLockingInset()) {
1291                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1292                     InsetTabular * inset = static_cast<InsetTabular *>
1293                         (owner->view()->theLockingInset());
1294                     inset->openLayoutDialog(owner->view());
1295                 } else if (owner->view()->theLockingInset()->
1296                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1297                     InsetTabular * inset = static_cast<InsetTabular *>(
1298                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1299                     inset->openLayoutDialog(owner->view());
1300                 }
1301             }
1302             break;
1303
1304         case LFUN_LAYOUT_PREAMBLE:
1305                 owner->getDialogs()->showPreamble();
1306                 break;
1307                 
1308         case LFUN_DROP_LAYOUTS_CHOICE:
1309                 owner->getToolbar()->openLayoutList();
1310                 break;
1311
1312         case LFUN_MENU_OPEN_BY_NAME:
1313                 owner->getMenubar()->openByName(argument);
1314                 break; // RVDK_PATCH_5
1315                 
1316         case LFUN_SPELLCHECK:
1317                 if (lyxrc.isp_command != "none")
1318                         owner->getDialogs()->showSpellchecker();
1319                 break;
1320                 
1321         // --- lyxserver commands ----------------------------
1322
1323
1324         case LFUN_GETNAME:
1325                 setMessage(owner->buffer()->fileName());
1326                 lyxerr[Debug::INFO] << "FNAME["
1327                                << owner->buffer()->fileName()
1328                                << "] " << endl;
1329                 break;
1330                 
1331         case LFUN_NOTIFY:
1332         {
1333                 dispatch_buffer = keyseq.print();
1334                 lyxserver->notifyClient(dispatch_buffer);
1335         }
1336         break;
1337
1338         case LFUN_GOTOFILEROW:
1339         {
1340                 string file_name;
1341                 int row;
1342                 istringstream istr(argument.c_str());
1343                 istr >> file_name >> row;
1344                 // Must replace extension of the file to be .lyx and get full path
1345                 string const s(ChangeExtension(file_name, ".lyx"));
1346
1347                 // Either change buffer or load the file
1348                 if (bufferlist.exists(s)) {
1349                         owner->view()->buffer(bufferlist.getBuffer(s));
1350                 } else {
1351                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1352                 }
1353                 
1354                 // Set the cursor  
1355                 owner->view()->setCursorFromRow(row);
1356
1357                 // Recenter screen
1358                 owner->view()->center();
1359         }
1360         break;
1361
1362         case LFUN_GOTO_PARAGRAPH:
1363         {
1364                 istringstream istr(argument.c_str());
1365
1366                 int id;
1367                 istr >> id;
1368                 Paragraph * par = owner->buffer()->getParFromID(id);
1369                 if (par == 0) {
1370                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1371                                             << id << "]" << std::endl;
1372                         break;
1373                 } else {
1374                         lyxerr << "Paragraph " << par->id()
1375                                << " found." << endl;
1376                 }
1377
1378                 // Set the cursor
1379                 owner->view()->text->setCursor(owner->view(), par, 0);
1380                 owner->view()->setState();
1381                 owner->showState();
1382
1383                 // Recenter screen
1384                 owner->view()->center();
1385         }
1386         break;
1387
1388         case LFUN_APROPOS:
1389         case LFUN_GETTIP:
1390         {
1391                 int const qa = lyxaction.LookupFunc(argument);
1392                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1393         }
1394         break;
1395
1396         // --- toolbar ----------------------------------
1397         case LFUN_PUSH_TOOLBAR:
1398         {
1399                 int nth = strToInt(argument);
1400                 if (nth <= 0) {
1401                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1402                 } else {
1403                         owner->getToolbar()->push(nth);
1404                 }
1405         }
1406         break;
1407         
1408         case LFUN_ADD_TO_TOOLBAR:
1409         {
1410                 if (lyxerr.debugging(Debug::GUI)) {
1411                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1412                                 "argument = `" << argument << '\'' << endl;
1413                 }
1414                 string tmp(argument);
1415                 //lyxerr <<string("Argument: ") + argument);
1416                 //lyxerr <<string("Tmp     : ") + tmp);
1417                 if (tmp.empty()) {
1418                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1419                 } else {
1420                         owner->getToolbar()->add(argument, false);
1421                         owner->getToolbar()->set();
1422                 }
1423         }
1424         break;
1425         
1426         // --- insert characters ----------------------------------------
1427
1428         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1429         case LFUN_MATH_EXTERN:
1430         case LFUN_MATH_NUMBER:
1431         case LFUN_MATH_NONUMBER:
1432         case LFUN_MATH_LIMITS:
1433         {
1434                 setErrorMessage(N_("This is only allowed in math mode!"));
1435         }
1436         break;
1437
1438         // passthrough hat and underscore outside mathed:
1439         case LFUN_SUBSCRIPT:
1440                 dispatch(LFUN_SELFINSERT, "_");
1441                 break;
1442         case LFUN_SUPERSCRIPT:
1443                 dispatch(LFUN_SELFINSERT, "^");
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 && !argument.empty()) {
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