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