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