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