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