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