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