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