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