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