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