]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Minor code shuffle.
[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_ABOUTLYX:
1094                 owner->getDialogs()->showAboutlyx();
1095                 break;
1096
1097         case LFUN_HELP_COPYRIGHT:
1098         case LFUN_HELP_CREDITS:
1099                 
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         
1127                 // --- version control -------------------------------
1128         case LFUN_VC_REGISTER:
1129         {
1130                 if (!owner->buffer()->lyxvc.inUse())
1131                         owner->buffer()->lyxvc.registrer();
1132         }
1133         break;
1134                 
1135         case LFUN_VC_CHECKIN:
1136         {
1137                 if (owner->buffer()->lyxvc.inUse()
1138                     && !owner->buffer()->isReadonly())
1139                         owner->buffer()->lyxvc.checkIn();
1140         }
1141         break;
1142                 
1143         case LFUN_VC_CHECKOUT:
1144         {
1145                 if (owner->buffer()->lyxvc.inUse()
1146                     && owner->buffer()->isReadonly())
1147                         owner->buffer()->lyxvc.checkOut();
1148         }
1149         break;
1150         
1151         case LFUN_VC_REVERT:
1152         {
1153                 owner->buffer()->lyxvc.revert();
1154         }
1155         break;
1156                 
1157         case LFUN_VC_UNDO:
1158         {
1159                 owner->buffer()->lyxvc.undoLast();
1160         }
1161         break;
1162                 
1163         case LFUN_VC_HISTORY:
1164         {
1165                 owner->getDialogs()->showVCLogFile();
1166                 break;
1167         }
1168         
1169         // --- buffers ----------------------------------------
1170
1171         case LFUN_SWITCHBUFFER:
1172                 owner->view()->buffer(bufferlist.getBuffer(argument));
1173                 break;
1174
1175         case LFUN_FILE_NEW:
1176         {
1177                 // servercmd: argument must be <file>:<template>
1178                 Buffer * tmpbuf = NewLyxFile(argument);
1179                 if (tmpbuf)
1180                         owner->view()->buffer(tmpbuf);
1181         }
1182         break;
1183                         
1184         case LFUN_FILE_OPEN:
1185                 open(argument);
1186                 break;
1187
1188         case LFUN_LATEX_LOG:
1189                 owner->getDialogs()->showLogFile();
1190                 break;
1191                 
1192         case LFUN_LAYOUTNO:
1193         {
1194                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1195                 int sel = strToInt(argument);
1196                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1197                 
1198                 // Should this give a setMessage instead?
1199                 if (sel == 0) 
1200                         return string(); // illegal argument
1201
1202                 --sel; // sel 1..., but layout 0...
1203
1204                 // Pretend we got the name instead.
1205                 dispatch(int(LFUN_LAYOUT), 
1206                          textclasslist.NameOfLayout(owner->view()
1207                                                     ->buffer()->params.textclass,
1208                                                     sel));
1209                 return string();
1210         }
1211                 
1212         case LFUN_LAYOUT_DOCUMENT:
1213                 owner->getDialogs()->showDocument();
1214                 break;
1215                 
1216         case LFUN_LAYOUT_PARAGRAPH:
1217                 owner->getDialogs()->showParagraph();
1218                 break;
1219                 
1220         case LFUN_LAYOUT_CHARACTER:
1221                 owner->getDialogs()->showCharacter();
1222                 break;
1223
1224         case LFUN_LAYOUT_TABULAR:
1225             if (owner->view()->theLockingInset()) {
1226                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1227                     InsetTabular * inset = static_cast<InsetTabular *>
1228                         (owner->view()->theLockingInset());
1229                     inset->openLayoutDialog(owner->view());
1230                 } else if (owner->view()->theLockingInset()->
1231                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1232                     InsetTabular * inset = static_cast<InsetTabular *>(
1233                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1234                     inset->openLayoutDialog(owner->view());
1235                 }
1236             }
1237             break;
1238
1239         case LFUN_LAYOUT_PREAMBLE:
1240                 owner->getDialogs()->showPreamble();
1241                 break;
1242                 
1243         case LFUN_LAYOUT_SAVE_DEFAULT:
1244                 MenuLayoutSave(owner->view());
1245                 break;
1246                 
1247         case LFUN_DROP_LAYOUTS_CHOICE:
1248                 owner->getToolbar()->openLayoutList();
1249                 break;
1250
1251         case LFUN_MENU_OPEN_BY_NAME:
1252                 owner->getMenubar()->openByName(argument);
1253                 break; // RVDK_PATCH_5
1254                 
1255         case LFUN_SPELLCHECK:
1256                 if (lyxrc.isp_command != "none")
1257                         owner->getDialogs()->showSpellchecker();
1258                 break;
1259                 
1260         // --- lyxserver commands ----------------------------
1261
1262
1263         case LFUN_GETNAME:
1264                 setMessage(owner->buffer()->fileName());
1265                 lyxerr[Debug::INFO] << "FNAME["
1266                                << owner->buffer()->fileName()
1267                                << "] " << endl;
1268                 break;
1269                 
1270         case LFUN_NOTIFY:
1271         {
1272                 string buf;
1273                 keyseq.print(buf);
1274                 dispatch_buffer = buf;
1275                 lyxserver->notifyClient(dispatch_buffer);
1276         }
1277         break;
1278
1279         case LFUN_GOTOFILEROW:
1280         {
1281 #if 0
1282                 char file_name[100];
1283                 int row;
1284                 ::sscanf(argument.c_str(), " %s %d", file_name, &row);
1285 #else
1286                 string file_name;
1287                 int row;
1288                 istringstream istr(argument.c_str());
1289                 istr >> file_name >> row;
1290 #endif
1291                 // Must replace extension of the file to be .lyx and get full path
1292                 string const s(ChangeExtension(file_name, ".lyx"));
1293
1294                 // Either change buffer or load the file
1295                 if (bufferlist.exists(s)) {
1296                         owner->view()->buffer(bufferlist.getBuffer(s));
1297                 } else {
1298                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1299                 }
1300                 
1301                 // Set the cursor  
1302                 owner->view()->setCursorFromRow(row);
1303
1304                 // Recenter screen
1305                 owner->view()->center();
1306         }
1307         break;
1308
1309         case LFUN_GOTO_PARAGRAPH:
1310         {
1311                 istringstream istr(argument.c_str());
1312
1313                 int id;
1314                 istr >> id;
1315                 Paragraph * par = owner->buffer()->getParFromID(id);
1316                 if (par == 0) {
1317                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1318                                             << id << "]" << std::endl;
1319                         break;
1320                 }
1321
1322                 // Set the cursor
1323                 TEXT()->setCursor(owner->view(), par, 0);
1324                 owner->view()->setState();
1325                 owner->showState();
1326
1327                 // Recenter screen
1328                 owner->view()->center();
1329         }
1330         break;
1331
1332         case LFUN_APROPOS:
1333         case LFUN_GETTIP:
1334         {
1335                 int const qa = lyxaction.LookupFunc(argument);
1336                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1337         }
1338         break;
1339
1340         // --- toolbar ----------------------------------
1341         case LFUN_PUSH_TOOLBAR:
1342         {
1343                 int nth = strToInt(argument);
1344                 if (nth <= 0) {
1345                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1346                 } else {
1347                         owner->getToolbar()->push(nth);
1348                 }
1349         }
1350         break;
1351         
1352         case LFUN_ADD_TO_TOOLBAR:
1353         {
1354                 if (lyxerr.debugging(Debug::GUI)) {
1355                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1356                                 "argument = `" << argument << '\'' << endl;
1357                 }
1358                 string tmp(argument);
1359                 //lyxerr <<string("Argument: ") + argument);
1360                 //lyxerr <<string("Tmp     : ") + tmp);
1361                 if (tmp.empty()) {
1362                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1363                 } else {
1364                         owner->getToolbar()->add(argument, false);
1365                         owner->getToolbar()->set();
1366                 }
1367         }
1368         break;
1369         
1370         // --- insert characters ----------------------------------------
1371
1372         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1373         
1374         // Greek mode     
1375         case LFUN_GREEK:
1376         {
1377                 if (!greek_kb_flag) {
1378                         greek_kb_flag = 1;
1379                         setMessage(N_("Math greek mode on"));
1380                 } else
1381                         greek_kb_flag = 0;
1382         }  
1383         break;
1384       
1385         // Greek keyboard      
1386         case LFUN_GREEK_TOGGLE:
1387         {
1388                 greek_kb_flag = greek_kb_flag ? 0 : 2;
1389                 if (greek_kb_flag) {
1390                         setMessage(N_("Math greek keyboard on"));
1391                 } else {
1392                         setMessage(N_("Math greek keyboard off"));
1393                 }
1394         }
1395         break;
1396         
1397         case LFUN_MATH_EXTERN:
1398         case LFUN_MATH_NUMBER:
1399         case LFUN_MATH_NONUMBER:
1400         case LFUN_MATH_LIMITS:
1401         {
1402                 setErrorMessage(N_("This is only allowed in math mode!"));
1403         }
1404         break;
1405
1406         case LFUN_MATH_PANEL:
1407                 owner->getDialogs()->showMathPanel();
1408                 break;
1409         
1410         case LFUN_CITATION_CREATE:
1411         {
1412                 InsetCommandParams p( "cite" );
1413                 
1414                 if (!argument.empty()) {
1415                         // This should be set at source, ie when typing
1416                         // "citation-insert foo" in the minibuffer.
1417                         // Question: would pybibliographer also need to be
1418                         // changed. Suspect so. Leave as-is therefore.
1419                         if (contains(argument, "|")) {
1420                                 p.setContents( token(argument, '|', 0) );
1421                                 p.setOptions(  token(argument, '|', 1) );
1422                         } else {
1423                                 p.setContents( argument );
1424                         }
1425                         dispatch(LFUN_CITATION_INSERT, p.getAsString());
1426                 } else
1427                         owner->getDialogs()->createCitation( p.getAsString() );
1428         }
1429         break;
1430                     
1431         case LFUN_CHILDOPEN:
1432         {
1433                 string const filename =
1434                         MakeAbsPath(argument, 
1435                                     OnlyPath(owner->buffer()->fileName()));
1436                 setMessage(N_("Opening child document ") +
1437                            MakeDisplayPath(filename) + "...");
1438                 owner->view()->savePosition(0);
1439                 if (bufferlist.exists(filename))
1440                         owner->view()->buffer(bufferlist.getBuffer(filename));
1441                 else
1442                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1443         }
1444         break;
1445
1446         case LFUN_TOGGLECURSORFOLLOW:
1447                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1448                 break;
1449                 
1450         case LFUN_KMAP_OFF:             // keymap off
1451                 owner->getIntl()->KeyMapOn(false);
1452                 break;
1453                 
1454         case LFUN_KMAP_PRIM:    // primary keymap
1455                 owner->getIntl()->KeyMapPrim();
1456                 break;
1457                 
1458         case LFUN_KMAP_SEC:             // secondary keymap
1459                 owner->getIntl()->KeyMapSec();
1460                 break;
1461                 
1462         case LFUN_KMAP_TOGGLE:  // toggle keymap
1463                 owner->getIntl()->ToggleKeyMap();
1464                 break;
1465
1466         case LFUN_SEQUENCE: 
1467         {
1468                 // argument contains ';'-terminated commands
1469                 while (argument.find(';') != string::npos) {
1470                         string first;
1471                         argument = split(argument, first, ';');
1472                         dispatch(first);
1473                 }
1474         }
1475         break;
1476
1477         case LFUN_DIALOG_PREFERENCES:
1478                 owner->getDialogs()->showPreferences();
1479                 break;
1480                 
1481         case LFUN_SAVEPREFERENCES:
1482         {
1483                 Path p(user_lyxdir);
1484                 lyxrc.write("preferences");
1485         }
1486         break;
1487
1488         case LFUN_SCREEN_FONT_UPDATE:
1489         {
1490                 // handle the screen font changes.
1491                 // 
1492                 lyxrc.set_font_norm_type();
1493                 fontloader.update();
1494                 // Of course we should only do the resize and the textcache.clear
1495                 // if values really changed...but not very important right now. (Lgb)
1496                 // All visible buffers will need resize
1497                 owner->resize();
1498                 // We also need to empty the textcache so that
1499                 // the buffer will be formatted correctly after
1500                 // a zoom change.
1501                 textcache.clear();
1502         }
1503         break;
1504
1505         case LFUN_SET_COLOR:
1506         {
1507                 string lyx_name;
1508                 string const x11_name = split(argument, lyx_name, ' ');
1509                 if (lyx_name.empty() || x11_name.empty()) {
1510                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1511                                                 " <x11_name>"));
1512                         break;
1513                         }
1514
1515                 if (!lcolor.setColor(lyx_name, x11_name)) {
1516                         static string const err1 (N_("Set-color \""));
1517                         static string const err2 (
1518                                 N_("\" failed - color is undefined "
1519                                    "or may not be redefined"));
1520                         setErrorMessage(_(err1) + lyx_name + _(err2));
1521                         break;
1522                 }
1523                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1524                 owner->view()->redraw();
1525                 break;
1526         }
1527
1528         case LFUN_MESSAGE:
1529                 owner->message(argument);
1530                 break;
1531
1532         case LFUN_MESSAGE_PUSH:
1533                 owner->messagePush(argument);
1534                 break;
1535
1536         case LFUN_MESSAGE_POP:
1537                 owner->messagePop();
1538                 break;
1539
1540         default:
1541                 // Then if it was none of the above
1542                 if (!owner->view()->Dispatch(action, argument))
1543                         lyxerr << "A truly unknown func ["
1544                                << lyxaction.getActionName(action) << "]!"
1545                                << endl;
1546                 break;
1547         } // end of switch
1548
1549 exit_with_message:
1550
1551         commandshortcut.erase();
1552         
1553         if (lyxrc.display_shortcuts && show_sc) {
1554                 if (action != LFUN_SELFINSERT) {
1555                         // Put name of command and list of shortcuts
1556                         // for it in minibuffer
1557                         string comname = lyxaction.getActionName(action);
1558
1559                         int pseudoaction = action;
1560                         bool argsadded = false;
1561
1562                         if (!argument.empty()) {
1563                                 // If we have the command with argument, 
1564                                 // this is better
1565                                 pseudoaction = 
1566                                         lyxaction.searchActionArg(action,
1567                                                                   argument);
1568
1569                                 if (pseudoaction == -1) {
1570                                         pseudoaction = action;
1571                                 } else {
1572                                         comname += " " + argument;
1573                                         argsadded = true;
1574                                 }
1575                         }
1576
1577                         string const shortcuts =
1578                                 toplevel_keymap->findbinding(pseudoaction);
1579
1580                         if (!shortcuts.empty()) {
1581                                 comname += ": " + shortcuts;
1582                         } else if (!argsadded) {
1583                                 comname += " " + argument;
1584                         }
1585
1586                         if (!comname.empty()) {
1587                                 comname = strip(comname);
1588                                 commandshortcut = "(" + comname + ')';
1589
1590                                 // Here we could even add a small pause,
1591                                 // to annoy the user and make him learn
1592                                 // the shortcuts.
1593                                 // No! That will just annoy, not teach
1594                                 // anything. The user will read the messages
1595                                 // if they are interested. (Asger)
1596                         }
1597                 }
1598         }
1599
1600         string const res = getMessage();
1601
1602         if (res.empty()) {
1603                 if (!commandshortcut.empty()) {
1604                         owner->getMiniBuffer()->addSet(commandshortcut);
1605                 }
1606         } else {
1607                 string const msg(_(res) + ' ' + commandshortcut);
1608                 owner->message(msg);
1609         }
1610
1611         return res;
1612 }
1613
1614
1615 void LyXFunc::setupLocalKeymap()
1616 {
1617         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1618         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1619 }
1620
1621
1622 void LyXFunc::menuNew(bool fromTemplate)
1623 {
1624         string initpath = lyxrc.document_path;
1625
1626         if (owner->view()->available()) {
1627                 string const trypath = owner->buffer()->filepath;
1628                 // If directory is writeable, use this as default.
1629                 if (IsDirWriteable(trypath) == 1)
1630                         initpath = trypath;
1631         }
1632
1633         static int newfile_number;
1634         string s;
1635         
1636         if (lyxrc.new_ask_filename) {
1637                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1638                                    LFUN_SELECT_FILE_SYNC,
1639                         make_pair(string(_("Documents")),
1640                                   string(lyxrc.document_path)),
1641                         make_pair(string(_("Templates")),
1642                                   string(lyxrc.template_path)));
1643
1644                 FileDialog::Result result =
1645                         fileDlg.Select(initpath,
1646                                        _("*.lyx|LyX Documents (*.lyx)"),
1647                                        _("newfile"));
1648         
1649                 if (result.second.empty()) {
1650                         owner->message(_("Canceled."));
1651                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1652                         return;
1653                 }
1654         
1655                 // get absolute path of file and make sure the filename ends
1656                 // with .lyx
1657                 s = MakeAbsPath(result.second);
1658                 if (!IsLyXFilename(s))
1659                         s += ".lyx";
1660
1661                 // Check if the document already is open
1662                 if (bufferlist.exists(s)) {
1663                         switch (AskConfirmation(_("Document is already open:"),
1664                                                 MakeDisplayPath(s, 50),
1665                                                 _("Do you want to close that document now?\n"
1666                                                   "('No' will just switch to the open version)")))
1667                         {
1668                         case 1: // Yes: close the document
1669                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1670                                 // If close is canceled, we cancel here too.
1671                                         return;
1672                                 break;
1673                         case 2: // No: switch to the open document
1674                                 owner->view()->buffer(bufferlist.getBuffer(s));
1675                                 return;
1676                         case 3: // Cancel: Do nothing
1677                                 owner->message(_("Canceled."));
1678                                 return;
1679                         }
1680                 }
1681                 // Check whether the file already exists
1682                 FileInfo fi(s);
1683                 if (fi.readable() &&
1684                     AskQuestion(_("File already exists:"), 
1685                                 MakeDisplayPath(s, 50),
1686                                 _("Do you want to open the document?"))) {
1687                                 // loads document
1688                         string const disp_fn(MakeDisplayPath(s));
1689                         
1690                         ostringstream str;
1691                         str << _("Opening  document") << ' '
1692                             << disp_fn << "...";
1693                         
1694                         owner->message(str.str().c_str());
1695                         //XFlush(fl_get_display());
1696                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1697                         ostringstream str2;
1698                         str2 << _("Document") << ' '
1699                              << disp_fn << ' ' << _("opened.");
1700                         
1701                         owner->message(str2.str().c_str());
1702                         
1703                         return;
1704                 }
1705         } else {
1706                 s = AddName(lyxrc.document_path,
1707                             "newfile" + tostr(++newfile_number) + ".lyx");
1708                 FileInfo fi(s);
1709                 while (bufferlist.exists(s) || fi.readable()) {
1710                         ++newfile_number;
1711                         s = AddName(lyxrc.document_path,
1712                                     "newfile" + tostr(newfile_number) +
1713                                     ".lyx");
1714                         fi.newFile(s);
1715                 }
1716         }
1717
1718         // The template stuff
1719         string templname;
1720         if (fromTemplate) {
1721                 FileDialog fileDlg(owner, _("Select template file"),
1722                         LFUN_SELECT_FILE_SYNC,
1723                         make_pair(string(_("Documents")),
1724                                   string(lyxrc.document_path)),
1725                         make_pair(string(_("Templates")),
1726                                   string(lyxrc.template_path)));
1727
1728                 FileDialog::Result result =
1729                         fileDlg.Select(lyxrc.template_path,
1730                                        _("*.lyx|LyX Documents (*.lyx)"));
1731         
1732                 if (result.first == FileDialog::Later)
1733                         return;
1734
1735                 string const fname = result.second;
1736
1737                 if (fname.empty()) 
1738                         return;
1739                 templname = fname;
1740         }
1741   
1742         // find a free buffer
1743         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1744         owner->view()->buffer(bufferlist.newFile(s, templname));
1745 }
1746
1747
1748 void LyXFunc::open(string const & fname)
1749 {
1750         string initpath = lyxrc.document_path;
1751   
1752         if (owner->view()->available()) {
1753                 string const trypath = owner->buffer()->filepath;
1754                 // If directory is writeable, use this as default.
1755                 if (IsDirWriteable(trypath) == 1)
1756                         initpath = trypath;
1757         }
1758
1759         string filename;
1760  
1761         if (fname.empty()) {
1762                 FileDialog fileDlg(owner, _("Select document to open"),
1763                         LFUN_FILE_OPEN,
1764                         make_pair(string(_("Documents")),
1765                                   string(lyxrc.document_path)),
1766                         make_pair(string(_("Examples")),
1767                                   string(AddPath(system_lyxdir, "examples"))));
1768
1769                 FileDialog::Result result =
1770                         fileDlg.Select(initpath,
1771                                        "*.lyx|LyX Documents (*.lyx)");
1772         
1773                 if (result.first == FileDialog::Later)
1774                         return;
1775
1776                 filename = result.second;
1777  
1778                 // check selected filename
1779                 if (filename.empty()) {
1780                         owner->message(_("Canceled."));
1781                         return;
1782                 }
1783         } else
1784                 filename = fname;
1785
1786         // get absolute path of file and add ".lyx" to the filename if
1787         // necessary
1788         filename = FileSearch(string(), filename, "lyx");
1789
1790         // loads document
1791         string const disp_fn(MakeDisplayPath(filename));
1792
1793         ostringstream str;
1794         str << _("Opening document") << ' ' << disp_fn << "...";
1795         
1796         owner->message(str.str().c_str());
1797
1798         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1799         if (openbuf) {
1800                 owner->view()->buffer(openbuf);
1801                 ostringstream str;
1802                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1803                 owner->message(str.str().c_str());
1804         } else {
1805                 ostringstream str;
1806                 str << _("Could not open docuent") << ' ' << disp_fn;
1807                 owner->message(str.str().c_str());
1808         }
1809 }
1810
1811
1812 // checks for running without gui are missing.
1813 void LyXFunc::doImport(string const & argument)
1814 {
1815         string format;
1816         string filename = split(argument, format, ' ');
1817         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format 
1818                             << " file: " << filename << endl;
1819
1820         if (filename.empty()) { // need user interaction
1821                 string initpath = lyxrc.document_path;
1822                 
1823                 if (owner->view()->available()) {
1824                         string const trypath = owner->buffer()->filepath;
1825                         // If directory is writeable, use this as default.
1826                         if (IsDirWriteable(trypath) == 1)
1827                                 initpath = trypath;
1828                 }
1829
1830                 string const text = _("Select ") + formats.PrettyName(format)
1831                         + _(" file to import");
1832
1833                 FileDialog fileDlg(owner, text, 
1834                         LFUN_IMPORT,
1835                         make_pair(string(_("Documents")),
1836                                   string(lyxrc.document_path)),
1837                         make_pair(string(_("Examples")),
1838                                   string(AddPath(system_lyxdir, "examples"))));
1839                         
1840                 string const extension = "*." + formats.Extension(format)
1841                         + "| " + formats.PrettyName(format)
1842                         + " (*." + formats.Extension(format) + ")";
1843
1844                 FileDialog::Result result = fileDlg.Select(initpath,
1845                                                            extension);
1846
1847                 if (result.first == FileDialog::Later)
1848                         return;
1849
1850                 filename = result.second;
1851  
1852                 // check selected filename
1853                 if (filename.empty())
1854                         owner->message(_("Canceled."));
1855         }
1856
1857         // still no filename? abort
1858         if (filename.empty()) 
1859                 return;
1860
1861         // get absolute path of file
1862         filename = MakeAbsPath(filename);
1863
1864         string const lyxfile = ChangeExtension(filename, ".lyx");
1865
1866         // Check if the document already is open
1867         if (bufferlist.exists(lyxfile)) {
1868                 switch (AskConfirmation(_("Document is already open:"), 
1869                                         MakeDisplayPath(lyxfile, 50),
1870                                         _("Do you want to close that document now?\n"
1871                                           "('No' will just switch to the open version)")))
1872                         {
1873                         case 1: // Yes: close the document
1874                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1875                                 // If close is canceled, we cancel here too.
1876                                         return;
1877                                 break;
1878                         case 2: // No: switch to the open document
1879                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1880                                 return;
1881                         case 3: // Cancel: Do nothing
1882                                 owner->message(_("Canceled."));
1883                                 return;
1884                         }
1885         }
1886
1887         // Check if a LyX document by the same root exists in filesystem
1888         FileInfo const f(lyxfile, true);
1889         if (f.exist() && !AskQuestion(_("A document by the name"), 
1890                                       MakeDisplayPath(lyxfile),
1891                                       _("already exists. Overwrite?"))) {
1892                 owner->message(_("Canceled"));
1893                 return;
1894         }
1895         // filename should be valid now
1896         
1897         Importer::Import(owner, filename, format);
1898 }
1899
1900
1901 void LyXFunc::reloadBuffer()
1902 {
1903         string const fn = owner->buffer()->fileName();
1904         if (bufferlist.close(owner->buffer()))
1905                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1906 }
1907
1908
1909 void LyXFunc::closeBuffer()
1910 {
1911         if (bufferlist.close(owner->buffer()) && !quitting) {
1912                 if (bufferlist.empty()) {
1913                         // need this otherwise SEGV may occur while trying to
1914                         // set variables that don't exist
1915                         // since there's no current buffer
1916                         owner->getDialogs()->hideBufferDependent();
1917                 } else {
1918                         owner->view()->buffer(bufferlist.first());
1919                 }
1920         }
1921 }
1922
1923
1924 // Each "owner" should have it's own message method. lyxview and
1925 // the minibuffer would use the minibuffer, but lyxserver would
1926 // send an ERROR signal to its client.  Alejandro 970603
1927 // This func is bit problematic when it comes to NLS, to make the
1928 // lyx servers client be language indepenent we must not translate
1929 // strings sent to this func.
1930 void LyXFunc::setErrorMessage(string const & m) const
1931 {
1932         dispatch_buffer = m;
1933         errorstat = true;
1934 }
1935
1936
1937 void LyXFunc::setMessage(string const & m)
1938 {
1939         dispatch_buffer = m;
1940 }
1941
1942
1943 void LyXFunc::initMiniBuffer() 
1944 {
1945         string text = _("Welcome to LyX!");
1946         
1947         // When meta-fake key is pressed, show the key sequence so far + "M-".
1948         if (wasMetaKey()) {
1949                 keyseqStr();
1950                 text += "M-";
1951         }
1952
1953         // Else, when a non-complete key sequence is pressed,
1954         // show the available options.
1955         else if (keyseqUncomplete()) 
1956                 text = keyseqOptions();
1957    
1958         // Else, show the buffer state.
1959         else if (owner->view()->available()) {
1960                 Buffer * tmpbuf = owner->buffer();
1961                 
1962                 string const nicename = 
1963                         MakeDisplayPath(tmpbuf->fileName());
1964                 // Should we do this instead? (kindo like emacs)
1965                 // leaves more room for other information
1966                 text = "LyX: ";
1967                 text += nicename;
1968                 if (tmpbuf->lyxvc.inUse()) {
1969                         text += " [";
1970                         text += tmpbuf->lyxvc.version();
1971                         text += ' ';
1972                         text += tmpbuf->lyxvc.locker();
1973                         if (tmpbuf->isReadonly())
1974                                 text += " (RO)";
1975                         text += ']';
1976                 } else if (tmpbuf->isReadonly())
1977                         text += " [RO]";
1978                 if (!tmpbuf->isLyxClean())
1979                         text += _(" (Changed)");
1980         } else {
1981                 if (text != _("Welcome to LyX!")) // this is a hack
1982                         text = _("* No document open *");
1983         }
1984         
1985         owner->message(text);
1986 }
1987