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