]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
small mathed change add the find_if
[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 "lyxfr1.h"
79 #include "bufferview_funcs.h"
80 #include "frontends/Dialogs.h"
81 #include "frontends/Toolbar.h"
82 #include "frontends/Menubar.h"
83 #include "FloatList.h"
84 #include "converter.h"
85 #include "exporter.h"
86 #include "importer.h"
87 #include "FontLoader.h"
88 #include "TextCache.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                      TEXT()->SearchBackward(owner->view(), searched_string) :
712                      TEXT()->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                 // Ok this is one _very_ bad solution, but I think that some
907                 // of this will be rewritten as part of GUI indep anyway.
908                 // Lgb
909                 static LyXFindReplace FR_;
910                 FR_.StartSearch(owner->view());
911         }
912         break;
913                 
914         case LFUN_REMOVEERRORS:
915                 if (owner->view()->removeAutoInsets()) {
916                         owner->view()->redraw();
917                         owner->view()->fitCursor(TEXT());
918                 }
919                 break;
920                 
921 #ifndef NEW_INSETS
922         case LFUN_OPENSTUFF:
923                 owner->view()->openStuff();
924                 break;
925 #endif
926                 
927         case LFUN_HYPHENATION:
928                 owner->view()->hyphenationPoint();
929                 break;
930                 
931         case LFUN_LDOTS:
932                 owner->view()->ldots();
933                 break;
934                 
935         case LFUN_END_OF_SENTENCE:
936                 owner->view()->endOfSentenceDot();
937                 break;
938
939         case LFUN_MENU_SEPARATOR:
940                 owner->view()->menuSeparator();
941                 break;
942                 
943         case LFUN_HFILL:
944                 owner->view()->hfill();
945                 break;
946                 
947         case LFUN_DEPTH:
948                 changeDepth(owner->view(), TEXT(false), 0);
949                 break;
950                 
951         case LFUN_DEPTH_MIN:
952                 changeDepth(owner->view(), TEXT(false), -1);
953                 break;
954                 
955         case LFUN_DEPTH_PLUS:
956                 changeDepth(owner->view(), TEXT(false), 1);
957                 break;
958                 
959         case LFUN_FREE:
960                 owner->getDialogs()->setUserFreeFont();
961                 break;
962                 
963         case LFUN_TEX:
964                 Tex(owner->view());
965                 owner->view()->setState();
966                 owner->showState();
967                 break;
968 #ifndef NEW_INSETS              
969         case LFUN_MELT:
970                 Melt(owner->view());
971                 break;
972 #endif
973         case LFUN_RECONFIGURE:
974                 Reconfigure(owner->view());
975                 break;
976 #ifndef NEW_INSETS
977         case LFUN_FOOTMELT:
978                 if (owner->view()->available()
979                     && !TEXT()->selection
980                     && TEXT()->cursor.par()->footnoteflag
981                     != LyXParagraph::NO_FOOTNOTE)
982                         { // only melt footnotes with FOOTMELT, not margins etc
983                                 if (TEXT()->cursor.par()->footnotekind == LyXParagraph::FOOTNOTE)
984                                         Melt(owner->view());
985                         }
986                 else
987                         Foot(owner->view()); 
988                 owner->view()->setState();
989                 break;
990
991         case LFUN_MARGINMELT:
992                 if (owner->view()->available()
993                     && !TEXT()->selection
994                     && TEXT()->cursor.par()->footnoteflag
995                     != LyXParagraph::NO_FOOTNOTE) {
996                         // only melt margins
997                         if (TEXT()->cursor.par()->footnotekind == LyXParagraph::MARGIN)
998                                 Melt(owner->view());
999                 } else
1000                         Margin(owner->view()); 
1001                 owner->view()->setState();
1002                 break;
1003 #endif
1004 #ifndef NEW_INSETS
1005         case LFUN_FLOATSOPERATE:
1006                 if (argument == "openfoot")
1007                         owner->view()->allFloats(1,0);
1008                 else if (argument == "closefoot")
1009                         owner->view()->allFloats(0,0);
1010                 else if (argument == "openfig")
1011                         owner->view()->allFloats(1,1);
1012                 else if (argument == "closefig")
1013                         owner->view()->allFloats(0,1);
1014                 break;
1015 #else
1016 #warning Find another implementation here (or another lyxfunc)!
1017 #endif
1018         case LFUN_HELP_COPYRIGHT:
1019                 owner->getDialogs()->showCopyright();
1020                 break;
1021
1022         case LFUN_HELP_CREDITS:
1023                 owner->getDialogs()->showCredits();
1024                 break;
1025
1026         case LFUN_HELP_OPEN: {
1027                 string arg = argument;
1028                 if (arg.empty()) {
1029                         setErrorMessage(N_("Missing argument"));
1030                         break;
1031                 }
1032                 ProhibitInput(owner->view());
1033                 string fname = i18nLibFileSearch("doc", arg, "lyx");
1034                 if (fname.empty()) {
1035                         lyxerr << "LyX: unable to find documentation file `"
1036                                << arg << "'. Bad installation?" << endl;
1037                         AllowInput(owner->view());
1038                         break;
1039                 }
1040                 owner->getMiniBuffer()->Set(_("Opening help file"),
1041                                             MakeDisplayPath(fname),"...");
1042                 owner->view()->buffer(bufferlist.loadLyXFile(fname,false));
1043                 AllowInput(owner->view());
1044                 break;
1045         }
1046
1047         case LFUN_HELP_VERSION: {
1048                 ProhibitInput(owner->view());
1049                 string msg(_("LyX Version "));
1050                 msg += LYX_VERSION;
1051                 msg += " of ";
1052                 msg += LYX_RELEASE;
1053                 fl_show_message(msg.c_str(),
1054                                 (_("Library directory: ")
1055                                  + MakeDisplayPath(system_lyxdir)).c_str(),
1056                                 (_("User directory: ") 
1057                                  + MakeDisplayPath(user_lyxdir)).c_str());
1058                 AllowInput(owner->view());
1059                 break;
1060         }
1061         
1062                 // --- version control -------------------------------
1063         case LFUN_VC_REGISTER:
1064         {
1065                 if (!owner->buffer()->lyxvc.inUse())
1066                         owner->buffer()->lyxvc.registrer();
1067         }
1068         break;
1069                 
1070         case LFUN_VC_CHECKIN:
1071         {
1072                 if (owner->buffer()->lyxvc.inUse()
1073                     && !owner->buffer()->isReadonly())
1074                         owner->buffer()->lyxvc.checkIn();
1075         }
1076         break;
1077                 
1078         case LFUN_VC_CHECKOUT:
1079         {
1080                 if (owner->buffer()->lyxvc.inUse()
1081                     && owner->buffer()->isReadonly())
1082                         owner->buffer()->lyxvc.checkOut();
1083         }
1084         break;
1085         
1086         case LFUN_VC_REVERT:
1087         {
1088                 owner->buffer()->lyxvc.revert();
1089         }
1090         break;
1091                 
1092         case LFUN_VC_UNDO:
1093         {
1094                 owner->buffer()->lyxvc.undoLast();
1095         }
1096         break;
1097                 
1098         case LFUN_VC_HISTORY:
1099         {
1100                 owner->getDialogs()->showVCLogFile();
1101                 break;
1102         }
1103         
1104         // --- buffers ----------------------------------------
1105
1106         case LFUN_SWITCHBUFFER:
1107                 owner->view()->buffer(bufferlist.getBuffer(argument));
1108                 break;
1109
1110         case LFUN_FILE_NEW:
1111         {
1112                 // servercmd: argument must be <file>:<template>
1113                 Buffer * tmpbuf = NewLyxFile(argument);
1114                 if (tmpbuf)
1115                         owner->view()->buffer(tmpbuf);
1116         }
1117         break;
1118                         
1119         case LFUN_FILE_OPEN:
1120                 owner->view()->buffer(bufferlist.loadLyXFile(argument));
1121                 break;
1122
1123         case LFUN_LATEX_LOG:
1124                 owner->getDialogs()->showLogFile();
1125                 break;
1126                 
1127         case LFUN_LAYOUTNO:
1128         {
1129                 lyxerr.debug() << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1130                 int sel = strToInt(argument);
1131                 lyxerr.debug() << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1132                 
1133                 // Should this give a setMessage instead?
1134                 if (sel == 0) 
1135                         return string(); // illegal argument
1136
1137                 --sel; // sel 1..., but layout 0...
1138
1139                 // Pretend we got the name instead.
1140                 Dispatch(int(LFUN_LAYOUT), 
1141                          textclasslist.NameOfLayout(owner->view()
1142                                                     ->buffer()->params.textclass,
1143                                                     sel));
1144                 return string();
1145         }
1146                 
1147         case LFUN_LAYOUT_DOCUMENT:
1148                 owner->getDialogs()->showLayoutDocument();
1149                 break;
1150                 
1151         case LFUN_LAYOUT_PARAGRAPH:
1152 #ifdef USE_OLD_PARAGRAPH_LAYOUT
1153                 MenuLayoutParagraph();
1154 #else
1155                 owner->getDialogs()->showLayoutParagraph();
1156 #endif
1157                 break;
1158                 
1159         case LFUN_LAYOUT_CHARACTER:
1160                 owner->getDialogs()->showLayoutCharacter();
1161                 break;
1162
1163         case LFUN_LAYOUT_TABULAR:
1164             if (owner->view()->theLockingInset()) {
1165                 if (owner->view()->theLockingInset()->LyxCode()==Inset::TABULAR_CODE) {
1166                     InsetTabular * inset = static_cast<InsetTabular *>
1167                         (owner->view()->theLockingInset());
1168                     inset->OpenLayoutDialog(owner->view());
1169                 } else if (owner->view()->theLockingInset()->
1170                            GetFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1171                     InsetTabular * inset = static_cast<InsetTabular *>(
1172                         owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE));
1173                     inset->OpenLayoutDialog(owner->view());
1174                 }
1175             }
1176             break;
1177
1178         case LFUN_LAYOUT_PREAMBLE:
1179                 owner->getDialogs()->showPreamble();
1180                 break;
1181                 
1182         case LFUN_LAYOUT_SAVE_DEFAULT:
1183                 MenuLayoutSave(owner->view());
1184                 break;
1185                 
1186         case LFUN_DROP_LAYOUTS_CHOICE:
1187                 owner->getToolbar()->openLayoutList();
1188                 break;
1189
1190         case LFUN_MENU_OPEN_BY_NAME:
1191                 owner->getMenubar()->openByName(argument);
1192                 break; // RVDK_PATCH_5
1193                 
1194         case LFUN_SPELLCHECK:
1195                 if (lyxrc.isp_command != "none")
1196                         ShowSpellChecker(owner->view());
1197                 break; // RVDK_PATCH_5
1198                 
1199         // --- lyxserver commands ----------------------------
1200
1201
1202         case LFUN_GETNAME:
1203                 setMessage(owner->buffer()->fileName());
1204                 lyxerr.debug() << "FNAME["
1205                                << owner->buffer()->fileName()
1206                                << "] " << endl;
1207                 break;
1208                 
1209         case LFUN_NOTIFY:
1210         {
1211                 string buf;
1212                 keyseq.print(buf);
1213                 dispatch_buffer = buf;
1214                 lyxserver->notifyClient(dispatch_buffer);
1215         }
1216         break;
1217
1218         case LFUN_GOTOFILEROW:
1219         {
1220                 char file_name[100];
1221                 int row;
1222                 ::sscanf(argument.c_str(), " %s %d", file_name, &row);
1223
1224                 // Must replace extension of the file to be .lyx and get full path
1225                 string s = ChangeExtension(string(file_name), ".lyx");
1226
1227                 // Either change buffer or load the file
1228                 if (bufferlist.exists(s))
1229                         owner->view()->buffer(bufferlist.getBuffer(s));
1230                 else
1231                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1232
1233                 // Set the cursor  
1234                 owner->view()->setCursorFromRow(row);
1235
1236                 // Recenter screen
1237                 owner->view()->center();
1238         }
1239         break;
1240
1241         case LFUN_GOTO_PARAGRAPH:
1242         {
1243                 istringstream istr(argument.c_str());
1244
1245                 int id;
1246                 istr >> id;
1247                 LyXParagraph * par = TEXT()->GetParFromID(id);
1248
1249                 // Set the cursor
1250                 TEXT()->SetCursor(owner->view(), par, 0);
1251                 owner->view()->setState();
1252                 owner->showState();
1253
1254                 // Recenter screen
1255                 owner->view()->center();
1256         }
1257         break;
1258
1259         case LFUN_APROPOS:
1260         case LFUN_GETTIP:
1261         {
1262                 int const qa = lyxaction.LookupFunc(argument);
1263                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1264         }
1265         break;
1266
1267         // --- toolbar ----------------------------------
1268         case LFUN_PUSH_TOOLBAR:
1269         {
1270                 int nth = strToInt(argument);
1271                 if (nth <= 0) {
1272                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1273                 } else {
1274                         owner->getToolbar()->push(nth);
1275                 }
1276         }
1277         break;
1278         
1279         case LFUN_ADD_TO_TOOLBAR:
1280         {
1281                 if (lyxerr.debugging(Debug::GUI)) {
1282                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1283                                 "argument = `" << argument << '\'' << endl;
1284                 }
1285                 string tmp(argument);
1286                 //lyxerr <<string("Argument: ") + argument);
1287                 //lyxerr <<string("Tmp     : ") + tmp);
1288                 if (tmp.empty()) {
1289                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1290                 } else {
1291                         owner->getToolbar()->add(argument, false);
1292                         owner->getToolbar()->set();
1293                 }
1294         }
1295         break;
1296         
1297         // --- insert characters ----------------------------------------
1298
1299         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1300         
1301         // Greek mode     
1302         case LFUN_GREEK:
1303         {
1304                 if (!greek_kb_flag) {
1305                         greek_kb_flag = 1;
1306                         setMessage(N_("Math greek mode on"));
1307                 } else
1308                         greek_kb_flag = 0;
1309         }  
1310         break;
1311       
1312         // Greek keyboard      
1313         case LFUN_GREEK_TOGGLE:
1314         {
1315                 greek_kb_flag = greek_kb_flag ? 0 : 2;
1316                 if (greek_kb_flag) {
1317                         setMessage(N_("Math greek keyboard on"));
1318                 } else {
1319                         setMessage(N_("Math greek keyboard off"));
1320                 }
1321         }
1322         break;
1323         
1324         case LFUN_MATH_NUMBER:
1325         case LFUN_MATH_LIMITS:
1326         {
1327                 setErrorMessage(N_("This is only allowed in math mode!"));
1328         
1329         }
1330         break;
1331
1332         case LFUN_MATH_PANEL:
1333         {
1334                 show_symbols_form(this);
1335         }
1336         break;
1337         
1338         case LFUN_CITATION_CREATE:
1339         {
1340                 InsetCommandParams p( "cite" );
1341                 
1342                 if (!argument.empty()) {
1343                         // This should be set at source, ie when typing
1344                         // "citation-insert foo" in the minibuffer.
1345                         // Question: would pybibliographer also need to be
1346                         // changed. Suspect so. Leave as-is therefore.
1347                         if (contains(argument, "|")) {
1348                                 p.setContents( token(argument, '|', 0) );
1349                                 p.setOptions(  token(argument, '|', 1) );
1350                         } else {
1351                                 p.setContents( argument );
1352                         }
1353                         Dispatch(LFUN_CITATION_INSERT, p.getAsString());
1354                 } else
1355                         owner->getDialogs()->createCitation( p.getAsString() );
1356         }
1357         break;
1358                     
1359         case LFUN_CHILD_CREATE:
1360         {
1361                 InsetCommandParams p("include");
1362  
1363                 if (!argument.empty()) {
1364                         if (contains(argument, "|")) {
1365                                 p.setContents(token(argument, '|', 0));
1366                                 p.setOptions(token(argument, '|', 1));
1367                         } else
1368                                 p.setContents(argument);
1369                         Dispatch(LFUN_CHILD_INSERT, p.getAsString());
1370                 } else
1371                         owner->getDialogs()->createInclude(p.getAsString());
1372         }
1373         break;
1374
1375         case LFUN_CHILDOPEN:
1376         {
1377                 string const filename =
1378                         MakeAbsPath(argument, 
1379                                     OnlyPath(owner->buffer()->fileName()));
1380                 setMessage(N_("Opening child document ") +
1381                            MakeDisplayPath(filename) + "...");
1382                 owner->view()->savePosition(0);
1383                 if (bufferlist.exists(filename))
1384                         owner->view()->buffer(bufferlist.getBuffer(filename));
1385                 else
1386                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1387         }
1388         break;
1389
1390 #ifndef NEW_INSETS
1391         case LFUN_INSERTFOOTNOTE: 
1392         {
1393                 LyXParagraph::footnote_kind kind;
1394                 if (argument == "footnote") {
1395                         kind = LyXParagraph::FOOTNOTE;
1396                 } else if (argument == "margin") {
1397                         kind = LyXParagraph::MARGIN;
1398                 } else if (argument == "figure") {
1399                         kind = LyXParagraph::FIG;
1400                 } else if (argument == "table") {
1401                         kind = LyXParagraph::TAB;
1402                 } else if (argument == "wide-fig") {
1403                         kind = LyXParagraph::WIDE_FIG;
1404                 } else if (argument == "wide-tab") {
1405                         kind = LyXParagraph::WIDE_TAB;
1406                 } else if (argument == "algorithm") {
1407                         kind = LyXParagraph::ALGORITHM;
1408                 } else {
1409                         setErrorMessage(N_("Unknown kind of footnote"));
1410                         break;
1411                 }
1412                 TEXT()->InsertFootnoteEnvironment(owner->view(), kind);
1413                 owner->view()->update(TEXT(),
1414                                       BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1415                 owner->view()->setState();
1416         }
1417         break;
1418 #endif
1419         case LFUN_TOGGLECURSORFOLLOW:
1420                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1421                 break;
1422                 
1423         case LFUN_KMAP_OFF:             // keymap off
1424                 owner->getIntl()->KeyMapOn(false);
1425                 break;
1426                 
1427         case LFUN_KMAP_PRIM:    // primary keymap
1428                 owner->getIntl()->KeyMapPrim();
1429                 break;
1430                 
1431         case LFUN_KMAP_SEC:             // secondary keymap
1432                 owner->getIntl()->KeyMapSec();
1433                 break;
1434                 
1435         case LFUN_KMAP_TOGGLE:  // toggle keymap
1436                 owner->getIntl()->ToggleKeyMap();
1437                 break;
1438
1439         case LFUN_SEQUENCE: 
1440         {
1441                 // argument contains ';'-terminated commands
1442                 while (argument.find(';') != string::npos) {
1443                         string first;
1444                         argument = split(argument, first, ';');
1445                         Dispatch(first);
1446                 }
1447         }
1448         break;
1449
1450         case LFUN_DIALOG_PREFERENCES:
1451                 owner->getDialogs()->showPreferences();
1452                 break;
1453                 
1454         case LFUN_SAVEPREFERENCES:
1455         {
1456                 Path p(user_lyxdir);
1457                 lyxrc.write("preferences");
1458         }
1459         break;
1460
1461         case LFUN_SCREEN_FONT_UPDATE:
1462         {
1463                 // handle the screen font changes.
1464                 // 
1465                 lyxrc.set_font_norm_type();
1466                 fontloader.update();
1467                 // Of course we should only do the resize and the textcache.clear
1468                 // if values really changed...but not very important right now. (Lgb)
1469                 // All buffers will need resize
1470                 bufferlist.resize();
1471                 // We also need to empty the textcache so that
1472                 // the buffer will be formatted correctly after
1473                 // a zoom change.
1474                 textcache.clear();
1475         }
1476         break;
1477
1478         case LFUN_SET_COLOR:
1479         {
1480                 string lyx_name;
1481                 string const x11_name = split(argument, lyx_name, ' ');
1482                 if (lyx_name.empty() || x11_name.empty()) {
1483                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1484                                                 " <x11_name>"));
1485                         break;
1486                         }
1487
1488                 if (!lcolor.setColor(lyx_name, x11_name)) {
1489                         static string const err1 (N_("Set-color \""));
1490                         static string const err2 (
1491                                 N_("\" failed - color is undefined "
1492                                    "or may not be redefined"));
1493                         setErrorMessage(_(err1) + lyx_name + _(err2));
1494                         break;
1495                 }
1496                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1497                 owner->view()->redraw();
1498                 break;
1499         }
1500
1501         default:
1502                 // Then if it was none of the above
1503                 if (!owner->view()->Dispatch(action, argument))
1504                         lyxerr << "A truly unknown func!" << endl;
1505                 break;
1506         } // end of switch
1507
1508 exit_with_message:
1509
1510         string const res = getMessage();
1511
1512         if (res.empty()) {
1513                 if (!commandshortcut.empty()) {
1514                         string const newbuf =
1515                                 owner->getMiniBuffer()->GetText();
1516                         if (newbuf != commandshortcut) {
1517                                 owner->getMiniBuffer()->Set(newbuf
1518                                                             + " " +
1519                                                             commandshortcut);
1520                         }
1521                 }
1522         } else {
1523                 string msg(_(res));
1524                 msg += " ";
1525                 msg += commandshortcut;
1526                 owner->getMiniBuffer()->Set(msg);
1527         }
1528
1529         return res;
1530 }
1531
1532
1533 void LyXFunc::setupLocalKeymap()
1534 {
1535         keyseq.stdmap = keyseq.curmap = toplevel_keymap;
1536         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap;
1537 }
1538
1539
1540 void LyXFunc::MenuNew(bool fromTemplate)
1541 {
1542         string initpath = lyxrc.document_path;
1543         LyXFileDlg fileDlg;
1544
1545         if (owner->view()->available()) {
1546                 string const trypath = owner->buffer()->filepath;
1547                 // If directory is writeable, use this as default.
1548                 if (IsDirWriteable(trypath) == 1)
1549                         initpath = trypath;
1550         }
1551
1552         static int newfile_number = 0;
1553         string s;
1554         
1555         if (lyxrc.new_ask_filename) {
1556                 ProhibitInput(owner->view());
1557                 fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
1558                 fileDlg.SetButton(1, _("Templates"), lyxrc.template_path);
1559                 string fname = fileDlg.Select(_("Enter Filename for new document"), 
1560                                        initpath, "*.lyx", _("newfile"));
1561                 AllowInput(owner->view());
1562         
1563                 if (fname.empty()) {
1564                         owner->getMiniBuffer()->Set(_("Canceled."));
1565                         lyxerr.debug() << "New Document Cancelled." << endl;
1566                         return;
1567                 }
1568         
1569                 // get absolute path of file and make sure the filename ends
1570                 // with .lyx
1571                 s = MakeAbsPath(fname);
1572                 if (!IsLyXFilename(s))
1573                         s += ".lyx";
1574
1575                 // Check if the document already is open
1576                 if (bufferlist.exists(s)) {
1577                         switch (AskConfirmation(_("Document is already open:"), 
1578                                                MakeDisplayPath(s, 50),
1579                                                _("Do you want to close that document now?\n"
1580                                                  "('No' will just switch to the open version)")))
1581                         {
1582                         case 1: // Yes: close the document
1583                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1584                                 // If close is canceled, we cancel here too.
1585                                         return;
1586                                 break;
1587                         case 2: // No: switch to the open document
1588                                 owner->view()->buffer(bufferlist.getBuffer(s));
1589                                 return;
1590                         case 3: // Cancel: Do nothing
1591                                 owner->getMiniBuffer()->Set(_("Canceled."));
1592                                 return;
1593                         }
1594                 }
1595                 // Check whether the file already exists
1596                 if (IsLyXFilename(s)) {
1597                         FileInfo fi(s);
1598                         if (fi.readable() &&
1599                             AskQuestion(_("File already exists:"), 
1600                                         MakeDisplayPath(s, 50),
1601                                         _("Do you want to open the document?"))) {
1602                                 // loads document
1603                                 owner->getMiniBuffer()->Set(_("Opening document"), 
1604                                                             MakeDisplayPath(s), "...");
1605                                 XFlush(fl_get_display());
1606                                 owner->view()->buffer(
1607                                         bufferlist.loadLyXFile(s));
1608                                 owner->getMiniBuffer()->Set(_("Document"),
1609                                                             MakeDisplayPath(s),
1610                                                             _("opened."));
1611                                 return;
1612                         }
1613                 }
1614         } else {
1615                 s = AddName(lyxrc.document_path,
1616                             "newfile" + tostr(++newfile_number) + ".lyx");
1617                 FileInfo fi(s);
1618                 while (bufferlist.exists(s) || fi.readable()) {
1619                         ++newfile_number;
1620                         s = AddName(lyxrc.document_path,
1621                                     "newfile" + tostr(newfile_number) +
1622                                     ".lyx");
1623                         fi.newFile(s);
1624                 }
1625         }
1626
1627         // The template stuff
1628         string templname;
1629         if (fromTemplate) {
1630                 ProhibitInput(owner->view());
1631                 string const fname = fileDlg.Select(_("Choose template"),
1632                                                     lyxrc.template_path,
1633                                                     "*.lyx");
1634                 AllowInput(owner->view());
1635                 if (fname.empty()) return;
1636                 templname = fname;
1637         }
1638   
1639         // find a free buffer
1640         lyxerr.debug() << "Find a free buffer." << endl;
1641         owner->view()->buffer(bufferlist.newFile(s, templname));
1642 }
1643
1644
1645 void LyXFunc::MenuOpen()
1646 {
1647         string initpath = lyxrc.document_path;
1648         LyXFileDlg fileDlg;
1649   
1650         if (owner->view()->available()) {
1651                 string const trypath = owner->buffer()->filepath;
1652                 // If directory is writeable, use this as default.
1653                 if (IsDirWriteable(trypath) == 1)
1654                         initpath = trypath;
1655         }
1656
1657         // launches dialog
1658         ProhibitInput(owner->view());
1659         fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
1660         fileDlg.SetButton(1, _("Examples"), 
1661                           AddPath(system_lyxdir, "examples"));
1662         string filename = fileDlg.Select(_("Select Document to Open"),
1663                                          initpath, "*.lyx");
1664         AllowInput(owner->view());
1665  
1666         // check selected filename
1667         if (filename.empty()) {
1668                 owner->getMiniBuffer()->Set(_("Canceled."));
1669                 return;
1670         }
1671
1672         // get absolute path of file and make sure the filename ends
1673         // with .lyx
1674         filename = MakeAbsPath(filename);
1675         if (!IsLyXFilename(filename))
1676                 filename += ".lyx";
1677
1678         // loads document
1679         owner->getMiniBuffer()->Set(_("Opening document"),
1680                                     MakeDisplayPath(filename), "...");
1681         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1682         if (openbuf) {
1683                 owner->view()->buffer(openbuf);
1684                 owner->getMiniBuffer()->Set(_("Document"),
1685                                             MakeDisplayPath(filename),
1686                                             _("opened."));
1687         } else {
1688                 owner->getMiniBuffer()->Set(_("Could not open document"),
1689                                             MakeDisplayPath(filename));
1690         }
1691 }
1692
1693
1694 // checks for running without gui are missing.
1695 void LyXFunc::doImport(string const & argument)
1696 {
1697         string format;
1698         string filename = split(argument, format, ' ');
1699         lyxerr.debug() << "LyXFunc::doImport: " << format 
1700                        << " file: " << filename << endl;
1701
1702         if (filename.empty()) { // need user interaction
1703                 string initpath = lyxrc.document_path;
1704                 LyXFileDlg fileDlg;
1705                 
1706                 if (owner->view()->available()) {
1707                         string const trypath = owner->buffer()->filepath;
1708                         // If directory is writeable, use this as default.
1709                         if (IsDirWriteable(trypath) == 1)
1710                                 initpath = trypath;
1711                 }
1712
1713                 // launches dialog
1714                 ProhibitInput(owner->view());
1715                 fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
1716                 fileDlg.SetButton(1, _("Examples"), 
1717                                         AddPath(system_lyxdir, "examples"));
1718                 string const text = _("Select ") + formats.PrettyName(format)
1719                         + _(" file to import");
1720                 string const extension = "*." + formats.Extension(format);
1721                 filename = fileDlg.Select(text, initpath, extension);
1722                 AllowInput(owner->view());
1723  
1724                 // check selected filename
1725                 if (filename.empty()) 
1726                         owner->getMiniBuffer()->Set(_("Canceled."));
1727         }
1728
1729         // still no filename? abort
1730         if (filename.empty()) 
1731                 return;
1732
1733         // get absolute path of file
1734         filename = MakeAbsPath(filename);
1735
1736         string const lyxfile = ChangeExtension(filename, ".lyx");
1737
1738         // Check if the document already is open
1739         if (bufferlist.exists(lyxfile)) {
1740                 switch (AskConfirmation(_("Document is already open:"), 
1741                                        MakeDisplayPath(lyxfile, 50),
1742                                        _("Do you want to close that document now?\n"
1743                                          "('No' will just switch to the open version)")))
1744                         {
1745                         case 1: // Yes: close the document
1746                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1747                                 // If close is canceled, we cancel here too.
1748                                         return;
1749                                 break;
1750                         case 2: // No: switch to the open document
1751                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1752                                 return;
1753                         case 3: // Cancel: Do nothing
1754                                 owner->getMiniBuffer()->Set(_("Canceled."));
1755                                 return;
1756                         }
1757         }
1758
1759         // Check if a LyX document by the same root exists in filesystem
1760         FileInfo const f(lyxfile, true);
1761         if (f.exist() && !AskQuestion(_("A document by the name"), 
1762                                       MakeDisplayPath(lyxfile),
1763                                       _("already exists. Overwrite?"))) {
1764                 owner->getMiniBuffer()->Set(_("Canceled."));
1765                 return;
1766         }
1767         // filename should be valid now
1768
1769         Importer::Import(owner, filename, format);
1770 }
1771
1772
1773 void LyXFunc::reloadBuffer()
1774 {
1775         string const fn = owner->buffer()->fileName();
1776         if (bufferlist.close(owner->buffer()))
1777                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1778 }
1779
1780
1781 void LyXFunc::CloseBuffer()
1782 {
1783         if (bufferlist.close(owner->buffer()) && !quitting) {
1784                 if (bufferlist.empty()) {
1785                         // need this otherwise SEGV may occur while trying to
1786                         // set variables that don't exist
1787                         // since there's no current buffer
1788                         owner->getDialogs()->hideBufferDependent();
1789                 } else {
1790                         owner->view()->buffer(bufferlist.first());
1791                 }
1792         }
1793 }
1794
1795
1796 // Each "owner" should have it's own message method. lyxview and
1797 // the minibuffer would use the minibuffer, but lyxserver would
1798 // send an ERROR signal to its client.  Alejandro 970603
1799 // This func is bit problematic when it comes to NLS, to make the
1800 // lyx servers client be language indepenent we must not translate
1801 // strings sent to this func.
1802 void LyXFunc::setErrorMessage(string const & m) const
1803 {
1804         dispatch_buffer = m;
1805         errorstat = true;
1806 }
1807
1808
1809 void LyXFunc::setMessage(string const & m)
1810 {
1811         dispatch_buffer = m;
1812 }