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