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