]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
6f6a4156a83e4f19cb35527467b992a151120d4b
[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                         string const s1 = _("Saving document") + ' '
873                                 + MakeDisplayPath(owner->buffer()->fileName()
874                                                   + "...");
875                         
876                         owner->message(s1);
877                         MenuWrite(owner->view(), owner->buffer());
878                 } else
879                         WriteAs(owner->view(), owner->buffer());
880                 break;
881                 
882         case LFUN_WRITEAS:
883                 WriteAs(owner->view(), owner->buffer(), argument);
884                 break;
885                 
886         case LFUN_MENURELOAD:
887                 reloadBuffer();
888                 break;
889                 
890         case LFUN_UPDATE:
891                 Exporter::Export(owner->buffer(), argument, true);
892                 break;
893
894         case LFUN_PREVIEW:
895                 Exporter::Preview(owner->buffer(), argument);
896                 break;
897                 
898         case LFUN_BUILDPROG:
899                 Exporter::Export(owner->buffer(), "program", true);
900                 break;
901                 
902         case LFUN_RUNCHKTEX:
903                 MenuRunChktex(owner->buffer());
904                 break;
905                                 
906         case LFUN_MENUPRINT:
907                 owner->getDialogs()->showPrint();
908                 break;
909
910         case LFUN_EXPORT:
911                 if (argument == "custom")
912                         MenuSendto();
913                 else
914                         Exporter::Export(owner->buffer(), argument, false);
915                 break;
916
917         case LFUN_IMPORT:
918                 doImport(argument);
919                 break;
920                 
921         case LFUN_QUIT:
922                 QuitLyX();
923                 break;
924                 
925         case LFUN_TOCVIEW:
926 #if 0
927         case LFUN_LOFVIEW:
928         case LFUN_LOTVIEW:
929         case LFUN_LOAVIEW:
930 #endif
931         {
932                 InsetCommandParams p;
933
934 #if 0
935                 if (action == LFUN_TOCVIEW)
936 #endif
937                         p.setCmdName("tableofcontents");
938 #if 0
939                 else if (action == LFUN_LOAVIEW )
940                         p.setCmdName("listof{algorithm}{List of Algorithms}");
941                 else if (action == LFUN_LOFVIEW)
942                         p.setCmdName("listoffigures");
943                 else
944                         p.setCmdName("listoftables");
945 #endif
946                 owner->getDialogs()->createTOC(p.getAsString());
947                 break;
948         }       
949
950         case LFUN_DIALOG_TABULAR_INSERT:
951                 owner->getDialogs()->showTabularCreate();
952                 break;
953                 
954         case LFUN_FIGURE:
955                 Figure();
956                 break;
957
958         case LFUN_AUTOSAVE:
959                 AutoSave(owner->view());
960                 break;
961                 
962         case LFUN_UNDO:
963                 owner->view()->menuUndo();
964                 break;
965                 
966         case LFUN_REDO:
967                 owner->view()->menuRedo();
968                 break;
969                 
970         case LFUN_MENUSEARCH:
971                 owner->getDialogs()->showSearch();
972                 break;
973                 
974         case LFUN_REMOVEERRORS:
975                 if (owner->view()->removeAutoInsets()) {
976                         owner->view()->redraw();
977                         owner->view()->fitCursor(TEXT());
978                 }
979                 break;
980
981         case LFUN_DEPTH:
982                 changeDepth(owner->view(), TEXT(false), 0);
983                 break;
984                 
985         case LFUN_DEPTH_MIN:
986                 changeDepth(owner->view(), TEXT(false), -1);
987                 break;
988                 
989         case LFUN_DEPTH_PLUS:
990                 changeDepth(owner->view(), TEXT(false), 1);
991                 break;
992                 
993         case LFUN_FREE:
994                 owner->getDialogs()->setUserFreeFont();
995                 break;
996                 
997         case LFUN_TEX:
998                 Tex(owner->view());
999                 owner->view()->setState();
1000                 owner->showState();
1001                 break;
1002
1003         case LFUN_RECONFIGURE:
1004                 Reconfigure(owner->view());
1005                 break;
1006
1007 #if 0
1008         case LFUN_FLOATSOPERATE:
1009                 if (argument == "openfoot")
1010                         owner->view()->allFloats(1,0);
1011                 else if (argument == "closefoot")
1012                         owner->view()->allFloats(0,0);
1013                 else if (argument == "openfig")
1014                         owner->view()->allFloats(1,1);
1015                 else if (argument == "closefig")
1016                         owner->view()->allFloats(0,1);
1017                 break;
1018 #else
1019 #ifdef WITH_WARNINGS
1020 #warning Find another implementation here (or another lyxfunc)!
1021 #endif
1022 #endif
1023         case LFUN_HELP_COPYRIGHT:
1024                 owner->getDialogs()->showCopyright();
1025                 break;
1026
1027         case LFUN_HELP_CREDITS:
1028                 owner->getDialogs()->showCredits();
1029                 break;
1030
1031         case LFUN_HELP_OPEN:
1032         {
1033                 string const arg = argument;
1034                 if (arg.empty()) {
1035                         setErrorMessage(N_("Missing argument"));
1036                         break;
1037                 }
1038                 ProhibitInput(owner->view());
1039                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1040                 if (fname.empty()) {
1041                         lyxerr << "LyX: unable to find documentation file `"
1042                                << arg << "'. Bad installation?" << endl;
1043                         AllowInput(owner->view());
1044                         break;
1045                 }
1046                 string const str = _("Opening help file") + ' '
1047                         + MakeDisplayPath(fname) + "...";
1048                 
1049                 owner->message(str);
1050                 owner->view()->buffer(bufferlist.loadLyXFile(fname,false));
1051                 AllowInput(owner->view());
1052                 break;
1053         }
1054
1055         case LFUN_HELP_VERSION: {
1056                 ProhibitInput(owner->view());
1057                 string msg(_("LyX Version "));
1058                 msg += LYX_VERSION;
1059                 msg += " of ";
1060                 msg += LYX_RELEASE;
1061                 fl_show_message(msg.c_str(),
1062                                 (_("Library directory: ")
1063                                  + MakeDisplayPath(system_lyxdir)).c_str(),
1064                                 (_("User directory: ") 
1065                                  + MakeDisplayPath(user_lyxdir)).c_str());
1066                 AllowInput(owner->view());
1067                 break;
1068         }
1069         
1070                 // --- version control -------------------------------
1071         case LFUN_VC_REGISTER:
1072         {
1073                 if (!owner->buffer()->lyxvc.inUse())
1074                         owner->buffer()->lyxvc.registrer();
1075         }
1076         break;
1077                 
1078         case LFUN_VC_CHECKIN:
1079         {
1080                 if (owner->buffer()->lyxvc.inUse()
1081                     && !owner->buffer()->isReadonly())
1082                         owner->buffer()->lyxvc.checkIn();
1083         }
1084         break;
1085                 
1086         case LFUN_VC_CHECKOUT:
1087         {
1088                 if (owner->buffer()->lyxvc.inUse()
1089                     && owner->buffer()->isReadonly())
1090                         owner->buffer()->lyxvc.checkOut();
1091         }
1092         break;
1093         
1094         case LFUN_VC_REVERT:
1095         {
1096                 owner->buffer()->lyxvc.revert();
1097         }
1098         break;
1099                 
1100         case LFUN_VC_UNDO:
1101         {
1102                 owner->buffer()->lyxvc.undoLast();
1103         }
1104         break;
1105                 
1106         case LFUN_VC_HISTORY:
1107         {
1108                 owner->getDialogs()->showVCLogFile();
1109                 break;
1110         }
1111         
1112         // --- buffers ----------------------------------------
1113
1114         case LFUN_SWITCHBUFFER:
1115                 owner->view()->buffer(bufferlist.getBuffer(argument));
1116                 break;
1117
1118         case LFUN_FILE_NEW:
1119         {
1120                 // servercmd: argument must be <file>:<template>
1121                 Buffer * tmpbuf = NewLyxFile(argument);
1122                 if (tmpbuf)
1123                         owner->view()->buffer(tmpbuf);
1124         }
1125         break;
1126                         
1127         case LFUN_FILE_OPEN:
1128                 Open(argument);
1129                 break;
1130
1131         case LFUN_LATEX_LOG:
1132                 owner->getDialogs()->showLogFile();
1133                 break;
1134                 
1135         case LFUN_LAYOUTNO:
1136         {
1137                 lyxerr.debug() << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1138                 int sel = strToInt(argument);
1139                 lyxerr.debug() << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1140                 
1141                 // Should this give a setMessage instead?
1142                 if (sel == 0) 
1143                         return string(); // illegal argument
1144
1145                 --sel; // sel 1..., but layout 0...
1146
1147                 // Pretend we got the name instead.
1148                 Dispatch(int(LFUN_LAYOUT), 
1149                          textclasslist.NameOfLayout(owner->view()
1150                                                     ->buffer()->params.textclass,
1151                                                     sel));
1152                 return string();
1153         }
1154                 
1155         case LFUN_LAYOUT_DOCUMENT:
1156                 owner->getDialogs()->showLayoutDocument();
1157                 break;
1158                 
1159         case LFUN_LAYOUT_PARAGRAPH:
1160                 owner->getDialogs()->showLayoutParagraph();
1161                 break;
1162                 
1163         case LFUN_LAYOUT_CHARACTER:
1164                 owner->getDialogs()->showLayoutCharacter();
1165                 break;
1166
1167         case LFUN_LAYOUT_TABULAR:
1168             if (owner->view()->theLockingInset()) {
1169                 if (owner->view()->theLockingInset()->LyxCode()==Inset::TABULAR_CODE) {
1170                     InsetTabular * inset = static_cast<InsetTabular *>
1171                         (owner->view()->theLockingInset());
1172                     inset->OpenLayoutDialog(owner->view());
1173                 } else if (owner->view()->theLockingInset()->
1174                            GetFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1175                     InsetTabular * inset = static_cast<InsetTabular *>(
1176                         owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE));
1177                     inset->OpenLayoutDialog(owner->view());
1178                 }
1179             }
1180             break;
1181
1182         case LFUN_LAYOUT_PREAMBLE:
1183                 owner->getDialogs()->showPreamble();
1184                 break;
1185                 
1186         case LFUN_LAYOUT_SAVE_DEFAULT:
1187                 MenuLayoutSave(owner->view());
1188                 break;
1189                 
1190         case LFUN_DROP_LAYOUTS_CHOICE:
1191                 owner->getToolbar()->openLayoutList();
1192                 break;
1193
1194         case LFUN_MENU_OPEN_BY_NAME:
1195                 owner->getMenubar()->openByName(argument);
1196                 break; // RVDK_PATCH_5
1197                 
1198         case LFUN_SPELLCHECK:
1199                 if (lyxrc.isp_command != "none")
1200                         ShowSpellChecker(owner->view());
1201                 break; // RVDK_PATCH_5
1202                 
1203         // --- lyxserver commands ----------------------------
1204
1205
1206         case LFUN_GETNAME:
1207                 setMessage(owner->buffer()->fileName());
1208                 lyxerr.debug() << "FNAME["
1209                                << owner->buffer()->fileName()
1210                                << "] " << endl;
1211                 break;
1212                 
1213         case LFUN_NOTIFY:
1214         {
1215                 string buf;
1216                 keyseq.print(buf);
1217                 dispatch_buffer = buf;
1218                 lyxserver->notifyClient(dispatch_buffer);
1219         }
1220         break;
1221
1222         case LFUN_GOTOFILEROW:
1223         {
1224                 char file_name[100];
1225                 int row;
1226                 ::sscanf(argument.c_str(), " %s %d", file_name, &row);
1227
1228                 // Must replace extension of the file to be .lyx and get full path
1229                 string s = ChangeExtension(string(file_name), ".lyx");
1230
1231                 // Either change buffer or load the file
1232                 if (bufferlist.exists(s))
1233                         owner->view()->buffer(bufferlist.getBuffer(s));
1234                 else
1235                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1236
1237                 // Set the cursor  
1238                 owner->view()->setCursorFromRow(row);
1239
1240                 // Recenter screen
1241                 owner->view()->center();
1242         }
1243         break;
1244
1245         case LFUN_GOTO_PARAGRAPH:
1246         {
1247                 istringstream istr(argument.c_str());
1248
1249                 int id;
1250                 istr >> id;
1251                 LyXParagraph * par = TEXT()->GetParFromID(id);
1252                 if (par == 0)
1253                         break;
1254
1255                 // Set the cursor
1256                 TEXT()->SetCursor(owner->view(), par, 0);
1257                 owner->view()->setState();
1258                 owner->showState();
1259
1260                 // Recenter screen
1261                 owner->view()->center();
1262         }
1263         break;
1264
1265         case LFUN_APROPOS:
1266         case LFUN_GETTIP:
1267         {
1268                 int const qa = lyxaction.LookupFunc(argument);
1269                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1270         }
1271         break;
1272
1273         // --- toolbar ----------------------------------
1274         case LFUN_PUSH_TOOLBAR:
1275         {
1276                 int nth = strToInt(argument);
1277                 if (nth <= 0) {
1278                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1279                 } else {
1280                         owner->getToolbar()->push(nth);
1281                 }
1282         }
1283         break;
1284         
1285         case LFUN_ADD_TO_TOOLBAR:
1286         {
1287                 if (lyxerr.debugging(Debug::GUI)) {
1288                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1289                                 "argument = `" << argument << '\'' << endl;
1290                 }
1291                 string tmp(argument);
1292                 //lyxerr <<string("Argument: ") + argument);
1293                 //lyxerr <<string("Tmp     : ") + tmp);
1294                 if (tmp.empty()) {
1295                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1296                 } else {
1297                         owner->getToolbar()->add(argument, false);
1298                         owner->getToolbar()->set();
1299                 }
1300         }
1301         break;
1302         
1303         // --- insert characters ----------------------------------------
1304
1305         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1306         
1307         // Greek mode     
1308         case LFUN_GREEK:
1309         {
1310                 if (!greek_kb_flag) {
1311                         greek_kb_flag = 1;
1312                         setMessage(N_("Math greek mode on"));
1313                 } else
1314                         greek_kb_flag = 0;
1315         }  
1316         break;
1317       
1318         // Greek keyboard      
1319         case LFUN_GREEK_TOGGLE:
1320         {
1321                 greek_kb_flag = greek_kb_flag ? 0 : 2;
1322                 if (greek_kb_flag) {
1323                         setMessage(N_("Math greek keyboard on"));
1324                 } else {
1325                         setMessage(N_("Math greek keyboard off"));
1326                 }
1327         }
1328         break;
1329         
1330         case LFUN_MATH_EXTERN:
1331         case LFUN_MATH_NUMBER:
1332         case LFUN_MATH_LIMITS:
1333         {
1334                 setErrorMessage(N_("This is only allowed in math mode!"));
1335         }
1336         break;
1337
1338         case LFUN_MATH_PANEL:
1339                 owner->getDialogs()->showMathPanel();
1340                 break;
1341         
1342         case LFUN_CITATION_CREATE:
1343         {
1344                 InsetCommandParams p( "cite" );
1345                 
1346                 if (!argument.empty()) {
1347                         // This should be set at source, ie when typing
1348                         // "citation-insert foo" in the minibuffer.
1349                         // Question: would pybibliographer also need to be
1350                         // changed. Suspect so. Leave as-is therefore.
1351                         if (contains(argument, "|")) {
1352                                 p.setContents( token(argument, '|', 0) );
1353                                 p.setOptions(  token(argument, '|', 1) );
1354                         } else {
1355                                 p.setContents( argument );
1356                         }
1357                         Dispatch(LFUN_CITATION_INSERT, p.getAsString());
1358                 } else
1359                         owner->getDialogs()->createCitation( p.getAsString() );
1360         }
1361         break;
1362                     
1363         case LFUN_CHILDOPEN:
1364         {
1365                 string const filename =
1366                         MakeAbsPath(argument, 
1367                                     OnlyPath(owner->buffer()->fileName()));
1368                 setMessage(N_("Opening child document ") +
1369                            MakeDisplayPath(filename) + "...");
1370                 owner->view()->savePosition(0);
1371                 if (bufferlist.exists(filename))
1372                         owner->view()->buffer(bufferlist.getBuffer(filename));
1373                 else
1374                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1375         }
1376         break;
1377
1378         case LFUN_TOGGLECURSORFOLLOW:
1379                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1380                 break;
1381                 
1382         case LFUN_KMAP_OFF:             // keymap off
1383                 owner->getIntl()->KeyMapOn(false);
1384                 break;
1385                 
1386         case LFUN_KMAP_PRIM:    // primary keymap
1387                 owner->getIntl()->KeyMapPrim();
1388                 break;
1389                 
1390         case LFUN_KMAP_SEC:             // secondary keymap
1391                 owner->getIntl()->KeyMapSec();
1392                 break;
1393                 
1394         case LFUN_KMAP_TOGGLE:  // toggle keymap
1395                 owner->getIntl()->ToggleKeyMap();
1396                 break;
1397
1398         case LFUN_SEQUENCE: 
1399         {
1400                 // argument contains ';'-terminated commands
1401                 while (argument.find(';') != string::npos) {
1402                         string first;
1403                         argument = split(argument, first, ';');
1404                         Dispatch(first);
1405                 }
1406         }
1407         break;
1408
1409         case LFUN_DIALOG_PREFERENCES:
1410                 owner->getDialogs()->showPreferences();
1411                 break;
1412                 
1413         case LFUN_SAVEPREFERENCES:
1414         {
1415                 Path p(user_lyxdir);
1416                 lyxrc.write("preferences");
1417         }
1418         break;
1419
1420         case LFUN_SCREEN_FONT_UPDATE:
1421         {
1422                 // handle the screen font changes.
1423                 // 
1424                 lyxrc.set_font_norm_type();
1425                 fontloader.update();
1426                 // Of course we should only do the resize and the textcache.clear
1427                 // if values really changed...but not very important right now. (Lgb)
1428                 // All buffers will need resize
1429                 bufferlist.resize();
1430                 // We also need to empty the textcache so that
1431                 // the buffer will be formatted correctly after
1432                 // a zoom change.
1433                 textcache.clear();
1434         }
1435         break;
1436
1437         case LFUN_SET_COLOR:
1438         {
1439                 string lyx_name;
1440                 string const x11_name = split(argument, lyx_name, ' ');
1441                 if (lyx_name.empty() || x11_name.empty()) {
1442                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1443                                                 " <x11_name>"));
1444                         break;
1445                         }
1446
1447                 if (!lcolor.setColor(lyx_name, x11_name)) {
1448                         static string const err1 (N_("Set-color \""));
1449                         static string const err2 (
1450                                 N_("\" failed - color is undefined "
1451                                    "or may not be redefined"));
1452                         setErrorMessage(_(err1) + lyx_name + _(err2));
1453                         break;
1454                 }
1455                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1456                 owner->view()->redraw();
1457                 break;
1458         }
1459
1460         case LFUN_MESSAGE:
1461                 owner->message(argument);
1462                 break;
1463
1464         case LFUN_MESSAGE_PUSH:
1465                 owner->messagePush(argument);
1466                 break;
1467
1468         case LFUN_MESSAGE_POP:
1469                 owner->messagePop();
1470                 break;
1471
1472         default:
1473                 // Then if it was none of the above
1474                 if (!owner->view()->Dispatch(action, argument))
1475                         lyxerr << "A truly unknown func ["
1476                                << action << "]!" << endl;
1477                 break;
1478         } // end of switch
1479
1480 exit_with_message:
1481
1482         string const res = getMessage();
1483
1484         if (res.empty()) {
1485                 if (!commandshortcut.empty()) {
1486                         owner->getMiniBuffer()->addSet(commandshortcut);
1487                 }
1488         } else {
1489                 string const msg(_(res) + ' ' + commandshortcut);
1490                 owner->message(msg);
1491         }
1492
1493         return res;
1494 }
1495
1496
1497 void LyXFunc::setupLocalKeymap()
1498 {
1499         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1500         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1501 }
1502
1503
1504 void LyXFunc::MenuNew(bool fromTemplate)
1505 {
1506         string initpath = lyxrc.document_path;
1507
1508         if (owner->view()->available()) {
1509                 string const trypath = owner->buffer()->filepath;
1510                 // If directory is writeable, use this as default.
1511                 if (IsDirWriteable(trypath) == 1)
1512                         initpath = trypath;
1513         }
1514
1515         static int newfile_number;
1516         string s;
1517         
1518         if (lyxrc.new_ask_filename) {
1519                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1520                                    LFUN_SELECT_FILE_SYNC,
1521                         make_pair(string(_("Documents")),
1522                                   string(lyxrc.document_path)),
1523                         make_pair(string(_("Templates")),
1524                                   string(lyxrc.template_path)));
1525
1526                 FileDialog::Result result =
1527                         fileDlg.Select(initpath,
1528                                        _("*.lyx|LyX Documents (*.lyx)"),
1529                                        _("newfile"));
1530         
1531                 if (result.second.empty()) {
1532                         owner->message(_("Canceled."));
1533                         lyxerr.debug() << "New Document Cancelled." << endl;
1534                         return;
1535                 }
1536         
1537                 // get absolute path of file and make sure the filename ends
1538                 // with .lyx
1539                 s = MakeAbsPath(result.second);
1540                 if (!IsLyXFilename(s))
1541                         s += ".lyx";
1542
1543                 // Check if the document already is open
1544                 if (bufferlist.exists(s)) {
1545                         switch (AskConfirmation(_("Document is already open:"),
1546                                                 MakeDisplayPath(s, 50),
1547                                                 _("Do you want to close that document now?\n"
1548                                                   "('No' will just switch to the open version)")))
1549                         {
1550                         case 1: // Yes: close the document
1551                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1552                                 // If close is canceled, we cancel here too.
1553                                         return;
1554                                 break;
1555                         case 2: // No: switch to the open document
1556                                 owner->view()->buffer(bufferlist.getBuffer(s));
1557                                 return;
1558                         case 3: // Cancel: Do nothing
1559                                 owner->message(_("Canceled."));
1560                                 return;
1561                         }
1562                 }
1563                 // Check whether the file already exists
1564                 if (IsLyXFilename(s)) {
1565                         FileInfo fi(s);
1566                         if (fi.readable() &&
1567                             AskQuestion(_("File already exists:"), 
1568                                         MakeDisplayPath(s, 50),
1569                                         _("Do you want to open the document?"))) {
1570                                 // loads document
1571                                 owner->message(_("Opening document") + ' '
1572                                                + MakeDisplayPath(s) + "...");
1573                                 XFlush(fl_get_display());
1574                                 owner->view()->buffer(
1575                                         bufferlist.loadLyXFile(s));
1576                                 owner->message(_("Document") + ' '
1577                                                + MakeDisplayPath(s) + ' '
1578                                                + _("opened."));
1579                                 return;
1580                         }
1581                 }
1582         } else {
1583                 s = AddName(lyxrc.document_path,
1584                             "newfile" + tostr(++newfile_number) + ".lyx");
1585                 FileInfo fi(s);
1586                 while (bufferlist.exists(s) || fi.readable()) {
1587                         ++newfile_number;
1588                         s = AddName(lyxrc.document_path,
1589                                     "newfile" + tostr(newfile_number) +
1590                                     ".lyx");
1591                         fi.newFile(s);
1592                 }
1593         }
1594
1595         // The template stuff
1596         string templname;
1597         if (fromTemplate) {
1598                 FileDialog fileDlg(owner, _("Select template file"),
1599                         LFUN_SELECT_FILE_SYNC,
1600                         make_pair(string(_("Documents")),
1601                                   string(lyxrc.document_path)),
1602                         make_pair(string(_("Templates")),
1603                                   string(lyxrc.template_path)));
1604
1605                 FileDialog::Result result =
1606                         fileDlg.Select(initpath,
1607                                        _("*.lyx|LyX Documents (*.lyx)"));
1608         
1609                 if (result.first == FileDialog::Later)
1610                         return;
1611
1612                 string const fname = result.second;
1613
1614                 if (fname.empty()) 
1615                         return;
1616                 templname = fname;
1617         }
1618   
1619         // find a free buffer
1620         lyxerr.debug() << "Find a free buffer." << endl;
1621         owner->view()->buffer(bufferlist.newFile(s, templname));
1622 }
1623
1624
1625 void LyXFunc::Open(string const & fname)
1626 {
1627         string initpath = lyxrc.document_path;
1628   
1629         if (owner->view()->available()) {
1630                 string const trypath = owner->buffer()->filepath;
1631                 // If directory is writeable, use this as default.
1632                 if (IsDirWriteable(trypath) == 1)
1633                         initpath = trypath;
1634         }
1635
1636         string filename;
1637  
1638         if (fname.empty()) {
1639                 FileDialog fileDlg(owner, _("Select document to open"),
1640                         LFUN_FILE_OPEN,
1641                         make_pair(string(_("Documents")),
1642                                   string(lyxrc.document_path)),
1643                         make_pair(string(_("Examples")),
1644                                   string(AddPath(system_lyxdir, "examples"))));
1645
1646                 FileDialog::Result result =
1647                         fileDlg.Select(initpath,
1648                                        "*.lyx|LyX Documents (*.lyx)");
1649         
1650                 if (result.first == FileDialog::Later)
1651                         return;
1652
1653                 filename = result.second;
1654  
1655                 // check selected filename
1656                 if (filename.empty()) {
1657                         owner->message(_("Canceled."));
1658                         return;
1659                 }
1660         } else
1661                 filename = fname;
1662
1663         // get absolute path of file and make sure the filename ends
1664         // with .lyx
1665         filename = MakeAbsPath(filename);
1666         if (!IsLyXFilename(filename))
1667                 filename += ".lyx";
1668
1669         // loads document
1670         owner->message(_("Opening document") + ' '
1671                        + MakeDisplayPath(filename) + "...");
1672         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1673         if (openbuf) {
1674                 owner->view()->buffer(openbuf);
1675                 owner->message(_("Document") + ' '
1676                                + MakeDisplayPath(filename)
1677                                + ' ' + _("opened."));
1678         } else {
1679                 owner->message(_("Could not open document") + ' '
1680                                + MakeDisplayPath(filename));
1681         }
1682 }
1683
1684
1685 // checks for running without gui are missing.
1686 void LyXFunc::doImport(string const & argument)
1687 {
1688         string format;
1689         string filename = split(argument, format, ' ');
1690         lyxerr.debug() << "LyXFunc::doImport: " << format 
1691                        << " file: " << filename << endl;
1692
1693         if (filename.empty()) { // need user interaction
1694                 string initpath = lyxrc.document_path;
1695                 
1696                 if (owner->view()->available()) {
1697                         string const trypath = owner->buffer()->filepath;
1698                         // If directory is writeable, use this as default.
1699                         if (IsDirWriteable(trypath) == 1)
1700                                 initpath = trypath;
1701                 }
1702
1703                 string const text = _("Select ") + formats.PrettyName(format)
1704                         + _(" file to import");
1705
1706                 FileDialog fileDlg(owner, text, 
1707                         LFUN_IMPORT,
1708                         make_pair(string(_("Documents")),
1709                                   string(lyxrc.document_path)),
1710                         make_pair(string(_("Examples")),
1711                                   string(AddPath(system_lyxdir, "examples"))));
1712                         
1713                 string const extension = "*." + formats.Extension(format)
1714                         + "| " + formats.PrettyName(format)
1715                         + " (*." + formats.Extension(format) + ")";
1716
1717                 FileDialog::Result result = fileDlg.Select(initpath,
1718                                                            extension);
1719
1720                 if (result.first == FileDialog::Later)
1721                         return;
1722
1723                 filename = result.second;
1724  
1725                 // check selected filename
1726                 if (filename.empty())
1727                         owner->message(_("Canceled."));
1728         }
1729
1730         // still no filename? abort
1731         if (filename.empty()) 
1732                 return;
1733
1734         // get absolute path of file
1735         filename = MakeAbsPath(filename);
1736
1737         string const lyxfile = ChangeExtension(filename, ".lyx");
1738
1739         // Check if the document already is open
1740         if (bufferlist.exists(lyxfile)) {
1741                 switch (AskConfirmation(_("Document is already open:"), 
1742                                         MakeDisplayPath(lyxfile, 50),
1743                                         _("Do you want to close that document now?\n"
1744                                           "('No' will just switch to the open version)")))
1745                         {
1746                         case 1: // Yes: close the document
1747                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1748                                 // If close is canceled, we cancel here too.
1749                                         return;
1750                                 break;
1751                         case 2: // No: switch to the open document
1752                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1753                                 return;
1754                         case 3: // Cancel: Do nothing
1755                                 owner->message(_("Canceled."));
1756                                 return;
1757                         }
1758         }
1759
1760         // Check if a LyX document by the same root exists in filesystem
1761         FileInfo const f(lyxfile, true);
1762         if (f.exist() && !AskQuestion(_("A document by the name"), 
1763                                       MakeDisplayPath(lyxfile),
1764                                       _("already exists. Overwrite?"))) {
1765                 owner->message(_("Canceled"));
1766                 return;
1767         }
1768         // filename should be valid now
1769         
1770         Importer::Import(owner, filename, format);
1771 }
1772
1773
1774 void LyXFunc::reloadBuffer()
1775 {
1776         string const fn = owner->buffer()->fileName();
1777         if (bufferlist.close(owner->buffer()))
1778                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1779 }
1780
1781
1782 void LyXFunc::CloseBuffer()
1783 {
1784         if (bufferlist.close(owner->buffer()) && !quitting) {
1785                 if (bufferlist.empty()) {
1786                         // need this otherwise SEGV may occur while trying to
1787                         // set variables that don't exist
1788                         // since there's no current buffer
1789                         owner->getDialogs()->hideBufferDependent();
1790                 } else {
1791                         owner->view()->buffer(bufferlist.first());
1792                 }
1793         }
1794 }
1795
1796
1797 // Each "owner" should have it's own message method. lyxview and
1798 // the minibuffer would use the minibuffer, but lyxserver would
1799 // send an ERROR signal to its client.  Alejandro 970603
1800 // This func is bit problematic when it comes to NLS, to make the
1801 // lyx servers client be language indepenent we must not translate
1802 // strings sent to this func.
1803 void LyXFunc::setErrorMessage(string const & m) const
1804 {
1805         dispatch_buffer = m;
1806         errorstat = true;
1807 }
1808
1809
1810 void LyXFunc::setMessage(string const & m)
1811 {
1812         dispatch_buffer = m;
1813 }
1814
1815
1816 void LyXFunc::initMiniBuffer() 
1817 {
1818         string text = _("Welcome to LyX!");
1819         
1820         // When meta-fake key is pressed, show the key sequence so far + "M-".
1821         if (wasMetaKey()) {
1822                 keyseqStr();
1823                 text += "M-";
1824         }
1825
1826         // Else, when a non-complete key sequence is pressed,
1827         // show the available options.
1828         else if (keyseqUncomplete()) 
1829                 text = keyseqOptions();
1830    
1831         // Else, show the buffer state.
1832         else if (owner->view()->available()) {
1833                 Buffer * tmpbuf = owner->buffer();
1834                 
1835                 string const nicename = 
1836                         MakeDisplayPath(tmpbuf->fileName());
1837                 // Should we do this instead? (kindo like emacs)
1838                 // leaves more room for other information
1839                 text = "LyX: ";
1840                 text += nicename;
1841                 if (tmpbuf->lyxvc.inUse()) {
1842                         text += " [";
1843                         text += tmpbuf->lyxvc.version();
1844                         text += ' ';
1845                         text += tmpbuf->lyxvc.locker();
1846                         if (tmpbuf->isReadonly())
1847                                 text += " (RO)";
1848                         text += ']';
1849                 } else if (tmpbuf->isReadonly())
1850                         text += " [RO]";
1851                 if (!tmpbuf->isLyxClean())
1852                         text += _(" (Changed)");
1853         } else {
1854                 if (text != _("Welcome to LyX!")) // this is a hack
1855                         text = _("* No document open *");
1856         }
1857         
1858         owner->message(text);
1859 }
1860