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