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