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