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