]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
LyX Drinkers United: patch 2
[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 "figure_form.h"
36 #include "intl.h"
37 #include "lyx_main.h"
38 #include "lyx_cb.h"
39 #include "LyXAction.h"
40 #include "insets/inseturl.h"
41 #include "insets/insetlatexaccent.h"
42 #include "insets/insettoc.h"
43 #include "insets/insetref.h"
44 #include "insets/insetparent.h"
45 #include "insets/insetindex.h"
46 #include "insets/insetinclude.h"
47 #include "insets/insetbib.h"
48 #include "insets/insetcite.h"
49 #include "insets/insettext.h"
50 #include "insets/insetert.h"
51 #include "insets/insetexternal.h"
52 #include "insets/insetgraphics.h"
53 #include "insets/insetfoot.h"
54 #include "insets/insetmarginal.h"
55 #include "insets/insetminipage.h"
56 #include "insets/insetfloat.h"
57 #include "insets/insetlist.h"
58 #include "insets/insettabular.h"
59 #include "insets/insettheorem.h"
60 #include "insets/insetcaption.h"
61 #include "mathed/formulamacro.h"
62 #include "mathed/math_cursor.h"
63 #include "mathed/math_inset.h"
64 #include "spellchecker.h" 
65 #include "minibuffer.h"
66 #include "vspace.h"
67 #include "LyXView.h"
68 #include "lyx_gui_misc.h"
69 #include "support/filetools.h"
70 #include "support/FileInfo.h"
71 #include "support/syscall.h"
72 #include "support/lstrings.h"
73 #include "support/path.h"
74 #include "support/lyxfunctional.h"
75 #include "debug.h"
76 #include "lyxrc.h"
77 #include "lyxtext.h"
78 #include "gettext.h"
79 #include "trans_mgr.h"
80 #include "layout.h"
81 #include "WorkArea.h"
82 #include "bufferview_funcs.h"
83 #include "frontends/FileDialog.h"
84 #include "frontends/Dialogs.h"
85 #include "frontends/Toolbar.h"
86 #include "frontends/Menubar.h"
87 #include "FloatList.h"
88 #include "converter.h"
89 #include "exporter.h"
90 #include "importer.h"
91 #include "FontLoader.h"
92 #include "TextCache.h"
93 #include "lyxfind.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         case LFUN_MATH_VALIGN: {
495                 Inset * tli = owner->view()->theLockingInset();
496                 if (tli && (tli->LyxCode() == Inset::MATH_CODE 
497                             || tli->LyxCode() == Inset::MATHMACRO_CODE)) {
498                         char align = mathcursor->valign();
499                         if (align == '\0') {
500                                 disable = true;
501                                 break;
502                         }
503                         if (argument.empty()) {
504                                 flag = func_status::OK;
505                                 break;
506                         }
507                         if (!contains("tcb", argument[0])) {
508                                 disable = true;
509                                 break;
510                         }
511                         if (argument[0] == align) 
512                                 flag |= func_status::ToggleOn;
513                         else
514                                 flag |= func_status::ToggleOff;
515                 } else
516                         disable = true;
517                 break;
518         }
519         case LFUN_MATH_HALIGN: {
520                 Inset * tli = owner->view()->theLockingInset();
521                 if (tli && (tli->LyxCode() == Inset::MATH_CODE 
522                             || tli->LyxCode() == Inset::MATHMACRO_CODE)) {
523                         char align = mathcursor->halign();
524                         if (align == '\0') {
525                                 disable = true;
526                                 break;
527                         }
528                         if (argument.empty()) {
529                                 flag = func_status::OK;
530                                 break;
531                         }
532                         if (!contains("lcr", argument[0])) {
533                                 disable = true;
534                                 break;
535                         }
536                         if (argument[0] == align) 
537                                 flag |= func_status::ToggleOn;
538                         else
539                                 flag |= func_status::ToggleOff;
540                 } else
541                         disable = true;
542                 break;
543         }
544         case LFUN_MATH_MUTATE: {
545                 Inset * tli = owner->view()->theLockingInset();
546                 if (tli && (tli->LyxCode() == Inset::MATH_CODE)) {
547                         MathInsetTypes type = mathcursor->par()->GetType();
548                         func_status::value_type box = func_status::ToggleOff;
549                         if (argument == "inline") {
550                                 if (type == LM_OT_SIMPLE)
551                                         box = func_status::ToggleOn;
552                         } else if (argument == "display") {
553                                 if (type == LM_OT_EQUATION)
554                                         box = func_status::ToggleOn;
555                         } else if (argument == "eqnarray") {
556                                 if (type == LM_OT_EQNARRAY)
557                                         box = func_status::ToggleOn;
558                         } else if (argument == "align") {
559                                 if (type == LM_OT_ALIGN)
560                                         box = func_status::ToggleOn;
561                         } else {
562                                 box = func_status::OK;
563                                 disable = true;
564                         }
565                         flag |= box;
566                 } else
567                         disable = true;
568                 break;
569         }
570         default:
571                 break;
572         }
573         if (disable)
574                 flag |= func_status::Disabled;
575
576         if (buf) {
577                 func_status::value_type box = func_status::ToggleOff;
578                 LyXFont const & font =
579                         TEXT(false)->real_current_font;
580                 switch (action) {
581                 case LFUN_EMPH:
582                         if (font.emph() == LyXFont::ON)
583                                 box = func_status::ToggleOn;
584                         break;
585                 case LFUN_NOUN:
586                         if (font.noun() == LyXFont::ON)
587                                 box = func_status::ToggleOn;
588                         break;
589                 case LFUN_BOLD:
590                         if (font.series() == LyXFont::BOLD_SERIES)
591                                 box = func_status::ToggleOn;
592                         break;
593 #ifndef NO_LATEX
594                 case LFUN_TEX:
595                         if (font.latex() == LyXFont::ON)
596                                 box = func_status::ToggleOn;
597                         break;
598 #endif
599                 case LFUN_READ_ONLY_TOGGLE:
600                         if (buf->isReadonly())
601                                 box = func_status::ToggleOn;
602                         break;
603                 default:
604                         box = func_status::OK;
605                         break;
606                 }
607                 flag |= box;
608         }
609
610         return flag;
611 }
612
613
614 // temporary dispatch method
615 void LyXFunc::miniDispatch(string const & s) 
616 {
617         if (!s.empty()) {
618                 Dispatch(s);
619         }
620 }
621
622
623 string const LyXFunc::Dispatch(string const & s) 
624 {
625         // Split command string into command and argument
626         string cmd;
627         string line = frontStrip(s);
628         string const arg = strip(frontStrip(split(line, cmd, ' ')));
629
630         return Dispatch(lyxaction.LookupFunc(cmd), arg);
631 }
632
633
634 string const LyXFunc::Dispatch(int ac,
635                                string const & do_not_use_this_arg)
636 {
637         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << ac
638                               <<"] arg[" << do_not_use_this_arg << "]" << endl;
639         
640         string argument;
641         kb_action action;
642         
643         // we have not done anything wrong yet.
644         errorstat = false;
645         dispatch_buffer.erase();
646         
647         // if action is a pseudo-action, we need the real action
648         if (lyxaction.isPseudoAction(ac)) {
649                 string tmparg;
650                 action = static_cast<kb_action>
651                         (lyxaction.retrieveActionArg(ac, tmparg));
652                 if (!tmparg.empty())
653                         argument = tmparg;
654         } else {
655                 action = static_cast<kb_action>(ac);
656                 if (!do_not_use_this_arg.empty())
657                         argument = do_not_use_this_arg; // except here
658         }
659     
660         selection_possible = false;
661         
662         if (owner->view()->available())
663                 owner->view()->hideCursor();
664
665         // We cannot use this function here
666         if (getStatus(ac, do_not_use_this_arg) & func_status::Disabled)
667                 goto exit_with_message;
668
669
670         if (owner->view()->available() && owner->view()->theLockingInset()) {
671                 UpdatableInset::RESULT result;
672                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
673                                      (keyseq.length >= -1)))
674                 {
675                         if ((action==LFUN_UNKNOWN_ACTION) && argument.empty()){
676                                 argument = keyseq.getiso();
677                         }
678                         // Undo/Redo is a bit tricky for insets.
679                         if (action == LFUN_UNDO) {
680                                 int slx;
681                                 int sly;
682                                 UpdatableInset * inset = 
683                                         owner->view()->theLockingInset();
684                                 inset->GetCursorPos(owner->view(), slx, sly);
685                                 owner->view()->unlockInset(inset);
686                                 owner->view()->menuUndo();
687                                 if (TEXT()->cursor.par()->
688                                     isInset(TEXT()->cursor.pos())) {
689                                         inset = static_cast<UpdatableInset*>(
690                                                 TEXT()->cursor.par()->
691                                                 getInset(TEXT()->
692                                                          cursor.pos()));
693                                 } else {
694                                         inset = 0;
695                                 }
696                                 if (inset)
697                                         inset->Edit(owner->view(),slx,sly,0);
698                                 return string();
699                         } else if (action == LFUN_REDO) {
700                                 int slx;
701                                 int sly;
702                                 UpdatableInset * inset = owner->view()->
703                                         theLockingInset();
704                                 inset->GetCursorPos(owner->view(), slx, sly);
705                                 owner->view()->unlockInset(inset);
706                                 owner->view()->menuRedo();
707                                 inset = static_cast<UpdatableInset*>(
708                                         TEXT()->cursor.par()->
709                                         getInset(TEXT()->
710                                                  cursor.pos()));
711                                 if (inset)
712                                         inset->Edit(owner->view(),slx,sly,0); 
713                                 return string();
714                         } else if (((result=owner->view()->theLockingInset()->
715                                    LocalDispatch(owner->view(), action,
716                                                  argument)) ==
717                                    UpdatableInset::DISPATCHED) ||
718                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
719                                 return string();
720                         else {
721                                 //setMessage(N_("Text mode"));
722                                 switch (action) {
723                                 case LFUN_UNKNOWN_ACTION:
724                                 case LFUN_BREAKPARAGRAPH:
725                                 case LFUN_BREAKLINE:
726                                         TEXT()->cursorRight(owner->view());
727                                         owner->view()->setState();
728                                         owner->showState();
729                                         break;
730                                 case LFUN_RIGHT:
731                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
732                                                 TEXT()->cursorRight(owner->view());
733                                                 moveCursorUpdate(true, false);
734                                                 owner->showState();
735                                         }
736                                         return string();
737                                 case LFUN_LEFT: 
738                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
739                                                 TEXT()->cursorRight(owner->view());
740                                                 moveCursorUpdate(true, false);
741                                                 owner->showState();
742                                         }
743                                         return string();
744                                 case LFUN_DOWN:
745                                         if (TEXT()->cursor.row()->next())
746                                                 TEXT()->cursorDown(owner->view());
747                                         else
748                                                 TEXT()->cursorRight(owner->view());
749                                         moveCursorUpdate(true, false);
750                                         owner->showState();
751                                         return string();
752                                 default:
753                                         break;
754                                 }
755                         }
756                 }
757         }
758
759         lyx::Assert(action != LFUN_SELECT_FILE_SYNC);
760
761         switch (action) {
762                 
763         case LFUN_ESCAPE:
764         {
765                 if (!owner->view()->available()) break;
766                 
767                 // this function should be used always [asierra060396]
768                 UpdatableInset * tli =
769                         owner->view()->theLockingInset();
770                 if (tli) {
771                         UpdatableInset * lock = tli->GetLockingInset();
772                         
773                         if (tli == lock) {
774                                 owner->view()->unlockInset(tli);
775                                 TEXT()->cursorRight(owner->view());
776                                 moveCursorUpdate(true, false);
777                                 owner->showState();
778                         } else {
779                                 tli->UnlockInsetInInset(owner->view(),
780                                                         lock,
781                                                         true);
782                         }
783                 }
784         }
785         break;
786                         
787                 // --- Misc -------------------------------------------
788         case LFUN_WORDFINDFORWARD  : 
789         case LFUN_WORDFINDBACKWARD : {
790                 static string last_search;
791                 string searched_string;
792             
793                 if (!argument.empty()) {
794                         last_search = argument;
795                         searched_string = argument;
796                 } else {
797                         searched_string = last_search;
798                 }
799
800                 if (!searched_string.empty() &&
801                     ((action == LFUN_WORDFINDBACKWARD) ? 
802                      SearchBackward(owner->view(), searched_string) :
803                      SearchForward(owner->view(), searched_string))) {
804
805                         // ??? What is that ???
806                         owner->view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
807
808                         // ??? Needed ???
809                         // clear the selection (if there is any) 
810                         owner->view()->toggleSelection();
811                         TEXT()->clearSelection(owner->view());
812
813                         // Move cursor so that successive C-s 's will not stand in place. 
814                         if (action == LFUN_WORDFINDFORWARD ) 
815                                 TEXT()->cursorRightOneWord(owner->view());
816                         TEXT()->finishUndo();
817                         moveCursorUpdate(true, false);
818
819                         // ??? Needed ???
820                         // set the new selection 
821                         // SetSelectionOverLenChars(owner->view()->currentBuffer()->text, iLenSelected);
822                         owner->view()->toggleSelection(false);
823                 }
824          
825                 // REMOVED : if (owner->view()->getWorkArea()->focus)
826                 owner->view()->showCursor();
827         }
828         break;
829                 
830         case LFUN_PREFIX:
831         {
832                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
833                         owner->view()->update(TEXT(),
834                                               BufferView::SELECT|BufferView::FITCUR);
835                 }
836                 string buf;
837                 keyseq.print(buf, true);
838                 owner->message(buf);
839         }
840         break;
841
842         // --- Misc -------------------------------------------
843         case LFUN_EXEC_COMMAND:
844         {
845                 std::vector<string> allCmds;
846                 std::transform(lyxaction.func_begin(), lyxaction.func_end(),
847                                std::back_inserter(allCmds), lyx::firster());
848                 static std::vector<string> hist;
849                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
850                                                   allCmds, hist);
851         }
852         break;
853                 
854         case LFUN_CANCEL:                   // RVDK_PATCH_5
855                 keyseq.reset();
856                 meta_fake_bit = 0;
857                 if (owner->view()->available())
858                         // cancel any selection
859                         Dispatch(LFUN_MARK_OFF);
860                 setMessage(N_("Cancel"));
861                 break;
862
863         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
864         {
865                 meta_fake_bit = Mod1Mask;
866                 string buf;
867                 keyseq.print(buf, true);
868                 setMessage(buf); // RVDK_PATCH_5
869         }
870         break;  
871
872         case LFUN_READ_ONLY_TOGGLE:
873                 if (owner->buffer()->lyxvc.inUse()) {
874                         owner->buffer()->lyxvc.toggleReadOnly();
875                 } else {
876                         owner->buffer()->setReadonly(
877                                 !owner->buffer()->isReadonly());
878                 }
879                 break;
880                 
881         case LFUN_CENTER: // this is center and redraw.
882                 owner->view()->center();
883                 break;
884                 
885                 // --- Menus -----------------------------------------------
886         case LFUN_MENUNEW:
887                 MenuNew(false);
888                 break;
889                 
890         case LFUN_MENUNEWTMPLT:
891                 MenuNew(true);
892                 break;
893                 
894         case LFUN_CLOSEBUFFER:
895                 CloseBuffer();
896                 break;
897                 
898         case LFUN_MENUWRITE:
899                 if (!owner->buffer()->isUnnamed()) {
900                         ostringstream s1;
901                         s1 << _("Saving document") << ' '
902                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
903                         owner->message(s1.str().c_str());
904                         MenuWrite(owner->view(), owner->buffer());
905                 } else
906                         WriteAs(owner->view(), owner->buffer());
907                 break;
908                 
909         case LFUN_WRITEAS:
910                 WriteAs(owner->view(), owner->buffer(), argument);
911                 break;
912                 
913         case LFUN_MENURELOAD:
914                 reloadBuffer();
915                 break;
916                 
917         case LFUN_UPDATE:
918                 Exporter::Export(owner->buffer(), argument, true);
919                 break;
920
921         case LFUN_PREVIEW:
922                 Exporter::Preview(owner->buffer(), argument);
923                 break;
924                 
925         case LFUN_BUILDPROG:
926                 Exporter::Export(owner->buffer(), "program", true);
927                 break;
928                 
929         case LFUN_RUNCHKTEX:
930                 MenuRunChktex(owner->buffer());
931                 break;
932                                 
933         case LFUN_MENUPRINT:
934                 owner->getDialogs()->showPrint();
935                 break;
936
937         case LFUN_EXPORT:
938                 if (argument == "custom")
939                         MenuSendto();
940                 else
941                         Exporter::Export(owner->buffer(), argument, false);
942                 break;
943
944         case LFUN_IMPORT:
945                 doImport(argument);
946                 break;
947                 
948         case LFUN_QUIT:
949                 QuitLyX();
950                 break;
951                 
952         case LFUN_TOCVIEW:
953 #if 0
954         case LFUN_LOFVIEW:
955         case LFUN_LOTVIEW:
956         case LFUN_LOAVIEW:
957 #endif
958         {
959                 InsetCommandParams p;
960
961 #if 0
962                 if (action == LFUN_TOCVIEW)
963 #endif
964                         p.setCmdName("tableofcontents");
965 #if 0
966                 else if (action == LFUN_LOAVIEW )
967                         p.setCmdName("listof{algorithm}{List of Algorithms}");
968                 else if (action == LFUN_LOFVIEW)
969                         p.setCmdName("listoffigures");
970                 else
971                         p.setCmdName("listoftables");
972 #endif
973                 owner->getDialogs()->createTOC(p.getAsString());
974                 break;
975         }       
976
977         case LFUN_DIALOG_TABULAR_INSERT:
978                 owner->getDialogs()->showTabularCreate();
979                 break;
980                 
981         case LFUN_FIGURE:
982                 Figure();
983                 break;
984
985         case LFUN_AUTOSAVE:
986                 AutoSave(owner->view());
987                 break;
988                 
989         case LFUN_UNDO:
990                 owner->view()->menuUndo();
991                 break;
992                 
993         case LFUN_REDO:
994                 owner->view()->menuRedo();
995                 break;
996                 
997         case LFUN_MENUSEARCH:
998                 owner->getDialogs()->showSearch();
999                 break;
1000                 
1001         case LFUN_REMOVEERRORS:
1002                 if (owner->view()->removeAutoInsets()) {
1003                         owner->view()->redraw();
1004                         owner->view()->fitCursor(TEXT());
1005                 }
1006                 break;
1007
1008         case LFUN_DEPTH:
1009                 changeDepth(owner->view(), TEXT(false), 0);
1010                 break;
1011                 
1012         case LFUN_DEPTH_MIN:
1013                 changeDepth(owner->view(), TEXT(false), -1);
1014                 break;
1015                 
1016         case LFUN_DEPTH_PLUS:
1017                 changeDepth(owner->view(), TEXT(false), 1);
1018                 break;
1019                 
1020         case LFUN_FREE:
1021                 owner->getDialogs()->setUserFreeFont();
1022                 break;
1023
1024 #ifndef NO_LATEX
1025         case LFUN_TEX:
1026                 Tex(owner->view());
1027                 owner->view()->setState();
1028                 owner->showState();
1029                 break;
1030 #endif
1031                 
1032         case LFUN_RECONFIGURE:
1033                 Reconfigure(owner->view());
1034                 break;
1035
1036 #if 0
1037         case LFUN_FLOATSOPERATE:
1038                 if (argument == "openfoot")
1039                         owner->view()->allFloats(1,0);
1040                 else if (argument == "closefoot")
1041                         owner->view()->allFloats(0,0);
1042                 else if (argument == "openfig")
1043                         owner->view()->allFloats(1,1);
1044                 else if (argument == "closefig")
1045                         owner->view()->allFloats(0,1);
1046                 break;
1047 #else
1048 #ifdef WITH_WARNINGS
1049 #warning Find another implementation here (or another lyxfunc)!
1050 #endif
1051 #endif
1052         case LFUN_HELP_COPYRIGHT:
1053                 owner->getDialogs()->showCopyright();
1054                 break;
1055
1056         case LFUN_HELP_CREDITS:
1057                 owner->getDialogs()->showCredits();
1058                 break;
1059
1060         case LFUN_HELP_OPEN:
1061         {
1062                 string const arg = argument;
1063                 if (arg.empty()) {
1064                         setErrorMessage(N_("Missing argument"));
1065                         break;
1066                 }
1067                 ProhibitInput(owner->view());
1068                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1069                 if (fname.empty()) {
1070                         lyxerr << "LyX: unable to find documentation file `"
1071                                << arg << "'. Bad installation?" << endl;
1072                         AllowInput(owner->view());
1073                         break;
1074                 }
1075                 ostringstream str;
1076                 str << _("Opening help file") << ' '
1077                     << MakeDisplayPath(fname) << "...";
1078                 owner->message(str.str().c_str());
1079                 owner->view()->buffer(bufferlist.loadLyXFile(fname,false));
1080                 AllowInput(owner->view());
1081                 break;
1082         }
1083
1084         case LFUN_HELP_VERSION: {
1085                 ProhibitInput(owner->view());
1086                 string msg(_("LyX Version "));
1087                 msg += LYX_VERSION;
1088                 msg += " of ";
1089                 msg += LYX_RELEASE;
1090                 fl_show_message(msg.c_str(),
1091                                 (_("Library directory: ")
1092                                  + MakeDisplayPath(system_lyxdir)).c_str(),
1093                                 (_("User directory: ") 
1094                                  + MakeDisplayPath(user_lyxdir)).c_str());
1095                 AllowInput(owner->view());
1096                 break;
1097         }
1098         
1099                 // --- version control -------------------------------
1100         case LFUN_VC_REGISTER:
1101         {
1102                 if (!owner->buffer()->lyxvc.inUse())
1103                         owner->buffer()->lyxvc.registrer();
1104         }
1105         break;
1106                 
1107         case LFUN_VC_CHECKIN:
1108         {
1109                 if (owner->buffer()->lyxvc.inUse()
1110                     && !owner->buffer()->isReadonly())
1111                         owner->buffer()->lyxvc.checkIn();
1112         }
1113         break;
1114                 
1115         case LFUN_VC_CHECKOUT:
1116         {
1117                 if (owner->buffer()->lyxvc.inUse()
1118                     && owner->buffer()->isReadonly())
1119                         owner->buffer()->lyxvc.checkOut();
1120         }
1121         break;
1122         
1123         case LFUN_VC_REVERT:
1124         {
1125                 owner->buffer()->lyxvc.revert();
1126         }
1127         break;
1128                 
1129         case LFUN_VC_UNDO:
1130         {
1131                 owner->buffer()->lyxvc.undoLast();
1132         }
1133         break;
1134                 
1135         case LFUN_VC_HISTORY:
1136         {
1137                 owner->getDialogs()->showVCLogFile();
1138                 break;
1139         }
1140         
1141         // --- buffers ----------------------------------------
1142
1143         case LFUN_SWITCHBUFFER:
1144                 owner->view()->buffer(bufferlist.getBuffer(argument));
1145                 break;
1146
1147         case LFUN_FILE_NEW:
1148         {
1149                 // servercmd: argument must be <file>:<template>
1150                 Buffer * tmpbuf = NewLyxFile(argument);
1151                 if (tmpbuf)
1152                         owner->view()->buffer(tmpbuf);
1153         }
1154         break;
1155                         
1156         case LFUN_FILE_OPEN:
1157                 Open(argument);
1158                 break;
1159
1160         case LFUN_LATEX_LOG:
1161                 owner->getDialogs()->showLogFile();
1162                 break;
1163                 
1164         case LFUN_LAYOUTNO:
1165         {
1166                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1167                 int sel = strToInt(argument);
1168                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1169                 
1170                 // Should this give a setMessage instead?
1171                 if (sel == 0) 
1172                         return string(); // illegal argument
1173
1174                 --sel; // sel 1..., but layout 0...
1175
1176                 // Pretend we got the name instead.
1177                 Dispatch(int(LFUN_LAYOUT), 
1178                          textclasslist.NameOfLayout(owner->view()
1179                                                     ->buffer()->params.textclass,
1180                                                     sel));
1181                 return string();
1182         }
1183                 
1184         case LFUN_LAYOUT_DOCUMENT:
1185                 owner->getDialogs()->showDocument();
1186                 break;
1187                 
1188         case LFUN_LAYOUT_PARAGRAPH:
1189                 owner->getDialogs()->showParagraph();
1190                 break;
1191                 
1192         case LFUN_LAYOUT_CHARACTER:
1193                 owner->getDialogs()->showCharacter();
1194                 break;
1195
1196         case LFUN_LAYOUT_TABULAR:
1197             if (owner->view()->theLockingInset()) {
1198                 if (owner->view()->theLockingInset()->LyxCode()==Inset::TABULAR_CODE) {
1199                     InsetTabular * inset = static_cast<InsetTabular *>
1200                         (owner->view()->theLockingInset());
1201                     inset->OpenLayoutDialog(owner->view());
1202                 } else if (owner->view()->theLockingInset()->
1203                            GetFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1204                     InsetTabular * inset = static_cast<InsetTabular *>(
1205                         owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE));
1206                     inset->OpenLayoutDialog(owner->view());
1207                 }
1208             }
1209             break;
1210
1211         case LFUN_LAYOUT_PREAMBLE:
1212                 owner->getDialogs()->showPreamble();
1213                 break;
1214                 
1215         case LFUN_LAYOUT_SAVE_DEFAULT:
1216                 MenuLayoutSave(owner->view());
1217                 break;
1218                 
1219         case LFUN_DROP_LAYOUTS_CHOICE:
1220                 owner->getToolbar()->openLayoutList();
1221                 break;
1222
1223         case LFUN_MENU_OPEN_BY_NAME:
1224                 owner->getMenubar()->openByName(argument);
1225                 break; // RVDK_PATCH_5
1226                 
1227         case LFUN_SPELLCHECK:
1228                 if (lyxrc.isp_command != "none")
1229                         ShowSpellChecker(owner->view());
1230                 break; // RVDK_PATCH_5
1231                 
1232         // --- lyxserver commands ----------------------------
1233
1234
1235         case LFUN_GETNAME:
1236                 setMessage(owner->buffer()->fileName());
1237                 lyxerr[Debug::INFO] << "FNAME["
1238                                << owner->buffer()->fileName()
1239                                << "] " << endl;
1240                 break;
1241                 
1242         case LFUN_NOTIFY:
1243         {
1244                 string buf;
1245                 keyseq.print(buf);
1246                 dispatch_buffer = buf;
1247                 lyxserver->notifyClient(dispatch_buffer);
1248         }
1249         break;
1250
1251         case LFUN_GOTOFILEROW:
1252         {
1253                 char file_name[100];
1254                 int row;
1255                 ::sscanf(argument.c_str(), " %s %d", file_name, &row);
1256
1257                 // Must replace extension of the file to be .lyx and get full path
1258                 string s = ChangeExtension(string(file_name), ".lyx");
1259
1260                 // Either change buffer or load the file
1261                 if (bufferlist.exists(s))
1262                         owner->view()->buffer(bufferlist.getBuffer(s));
1263                 else
1264                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1265
1266                 // Set the cursor  
1267                 owner->view()->setCursorFromRow(row);
1268
1269                 // Recenter screen
1270                 owner->view()->center();
1271         }
1272         break;
1273
1274         case LFUN_GOTO_PARAGRAPH:
1275         {
1276                 istringstream istr(argument.c_str());
1277
1278                 int id;
1279                 istr >> id;
1280                 Paragraph * par = TEXT()->getParFromID(id);
1281                 if (par == 0)
1282                         break;
1283
1284                 // Set the cursor
1285                 TEXT()->setCursor(owner->view(), par, 0);
1286                 owner->view()->setState();
1287                 owner->showState();
1288
1289                 // Recenter screen
1290                 owner->view()->center();
1291         }
1292         break;
1293
1294         case LFUN_APROPOS:
1295         case LFUN_GETTIP:
1296         {
1297                 int const qa = lyxaction.LookupFunc(argument);
1298                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1299         }
1300         break;
1301
1302         // --- toolbar ----------------------------------
1303         case LFUN_PUSH_TOOLBAR:
1304         {
1305                 int nth = strToInt(argument);
1306                 if (nth <= 0) {
1307                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1308                 } else {
1309                         owner->getToolbar()->push(nth);
1310                 }
1311         }
1312         break;
1313         
1314         case LFUN_ADD_TO_TOOLBAR:
1315         {
1316                 if (lyxerr.debugging(Debug::GUI)) {
1317                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1318                                 "argument = `" << argument << '\'' << endl;
1319                 }
1320                 string tmp(argument);
1321                 //lyxerr <<string("Argument: ") + argument);
1322                 //lyxerr <<string("Tmp     : ") + tmp);
1323                 if (tmp.empty()) {
1324                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1325                 } else {
1326                         owner->getToolbar()->add(argument, false);
1327                         owner->getToolbar()->set();
1328                 }
1329         }
1330         break;
1331         
1332         // --- insert characters ----------------------------------------
1333
1334         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1335         
1336         // Greek mode     
1337         case LFUN_GREEK:
1338         {
1339                 if (!greek_kb_flag) {
1340                         greek_kb_flag = 1;
1341                         setMessage(N_("Math greek mode on"));
1342                 } else
1343                         greek_kb_flag = 0;
1344         }  
1345         break;
1346       
1347         // Greek keyboard      
1348         case LFUN_GREEK_TOGGLE:
1349         {
1350                 greek_kb_flag = greek_kb_flag ? 0 : 2;
1351                 if (greek_kb_flag) {
1352                         setMessage(N_("Math greek keyboard on"));
1353                 } else {
1354                         setMessage(N_("Math greek keyboard off"));
1355                 }
1356         }
1357         break;
1358         
1359         case LFUN_MATH_EXTERN:
1360         case LFUN_MATH_NUMBER:
1361         case LFUN_MATH_NONUMBER:
1362         case LFUN_MATH_LIMITS:
1363         {
1364                 setErrorMessage(N_("This is only allowed in math mode!"));
1365         }
1366         break;
1367
1368         case LFUN_MATH_PANEL:
1369                 owner->getDialogs()->showMathPanel();
1370                 break;
1371         
1372         case LFUN_CITATION_CREATE:
1373         {
1374                 InsetCommandParams p( "cite" );
1375                 
1376                 if (!argument.empty()) {
1377                         // This should be set at source, ie when typing
1378                         // "citation-insert foo" in the minibuffer.
1379                         // Question: would pybibliographer also need to be
1380                         // changed. Suspect so. Leave as-is therefore.
1381                         if (contains(argument, "|")) {
1382                                 p.setContents( token(argument, '|', 0) );
1383                                 p.setOptions(  token(argument, '|', 1) );
1384                         } else {
1385                                 p.setContents( argument );
1386                         }
1387                         Dispatch(LFUN_CITATION_INSERT, p.getAsString());
1388                 } else
1389                         owner->getDialogs()->createCitation( p.getAsString() );
1390         }
1391         break;
1392                     
1393         case LFUN_CHILDOPEN:
1394         {
1395                 string const filename =
1396                         MakeAbsPath(argument, 
1397                                     OnlyPath(owner->buffer()->fileName()));
1398                 setMessage(N_("Opening child document ") +
1399                            MakeDisplayPath(filename) + "...");
1400                 owner->view()->savePosition(0);
1401                 if (bufferlist.exists(filename))
1402                         owner->view()->buffer(bufferlist.getBuffer(filename));
1403                 else
1404                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1405         }
1406         break;
1407
1408         case LFUN_TOGGLECURSORFOLLOW:
1409                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1410                 break;
1411                 
1412         case LFUN_KMAP_OFF:             // keymap off
1413                 owner->getIntl()->KeyMapOn(false);
1414                 break;
1415                 
1416         case LFUN_KMAP_PRIM:    // primary keymap
1417                 owner->getIntl()->KeyMapPrim();
1418                 break;
1419                 
1420         case LFUN_KMAP_SEC:             // secondary keymap
1421                 owner->getIntl()->KeyMapSec();
1422                 break;
1423                 
1424         case LFUN_KMAP_TOGGLE:  // toggle keymap
1425                 owner->getIntl()->ToggleKeyMap();
1426                 break;
1427
1428         case LFUN_SEQUENCE: 
1429         {
1430                 // argument contains ';'-terminated commands
1431                 while (argument.find(';') != string::npos) {
1432                         string first;
1433                         argument = split(argument, first, ';');
1434                         Dispatch(first);
1435                 }
1436         }
1437         break;
1438
1439         case LFUN_DIALOG_PREFERENCES:
1440                 owner->getDialogs()->showPreferences();
1441                 break;
1442                 
1443         case LFUN_SAVEPREFERENCES:
1444         {
1445                 Path p(user_lyxdir);
1446                 lyxrc.write("preferences");
1447         }
1448         break;
1449
1450         case LFUN_SCREEN_FONT_UPDATE:
1451         {
1452                 // handle the screen font changes.
1453                 // 
1454                 lyxrc.set_font_norm_type();
1455                 fontloader.update();
1456                 // Of course we should only do the resize and the textcache.clear
1457                 // if values really changed...but not very important right now. (Lgb)
1458                 // All visible buffers will need resize
1459                 owner->resize();
1460                 // We also need to empty the textcache so that
1461                 // the buffer will be formatted correctly after
1462                 // a zoom change.
1463                 textcache.clear();
1464         }
1465         break;
1466
1467         case LFUN_SET_COLOR:
1468         {
1469                 string lyx_name;
1470                 string const x11_name = split(argument, lyx_name, ' ');
1471                 if (lyx_name.empty() || x11_name.empty()) {
1472                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1473                                                 " <x11_name>"));
1474                         break;
1475                         }
1476
1477                 if (!lcolor.setColor(lyx_name, x11_name)) {
1478                         static string const err1 (N_("Set-color \""));
1479                         static string const err2 (
1480                                 N_("\" failed - color is undefined "
1481                                    "or may not be redefined"));
1482                         setErrorMessage(_(err1) + lyx_name + _(err2));
1483                         break;
1484                 }
1485                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1486                 owner->view()->redraw();
1487                 break;
1488         }
1489
1490         case LFUN_MESSAGE:
1491                 owner->message(argument);
1492                 break;
1493
1494         case LFUN_MESSAGE_PUSH:
1495                 owner->messagePush(argument);
1496                 break;
1497
1498         case LFUN_MESSAGE_POP:
1499                 owner->messagePop();
1500                 break;
1501
1502         default:
1503                 // Then if it was none of the above
1504                 if (!owner->view()->Dispatch(action, argument))
1505                         lyxerr << "A truly unknown func ["
1506                                << action << "]!" << endl;
1507                 break;
1508         } // end of switch
1509
1510 exit_with_message:
1511
1512         commandshortcut.erase();
1513         
1514         if (lyxrc.display_shortcuts && show_sc) {
1515                 if (action != LFUN_SELFINSERT) {
1516                         // Put name of command and list of shortcuts
1517                         // for it in minibuffer
1518                         string comname = lyxaction.getActionName(action);
1519
1520                         int pseudoaction = action;
1521                         bool argsadded = false;
1522
1523                         if (!argument.empty()) {
1524                                 // If we have the command with argument, 
1525                                 // this is better
1526                                 pseudoaction = 
1527                                         lyxaction.searchActionArg(action,
1528                                                                   argument);
1529
1530                                 if (pseudoaction == -1) {
1531                                         pseudoaction = action;
1532                                 } else {
1533                                         comname += " " + argument;
1534                                         argsadded = true;
1535                                 }
1536                         }
1537
1538                         string const shortcuts =
1539                                 toplevel_keymap->findbinding(pseudoaction);
1540
1541                         if (!shortcuts.empty()) {
1542                                 comname += ": " + shortcuts;
1543                         } else if (!argsadded) {
1544                                 comname += " " + argument;
1545                         }
1546
1547                         if (!comname.empty()) {
1548                                 comname = strip(comname);
1549                                 commandshortcut = "(" + comname + ')';
1550
1551                                 // Here we could even add a small pause,
1552                                 // to annoy the user and make him learn
1553                                 // the shortcuts.
1554                                 // No! That will just annoy, not teach
1555                                 // anything. The user will read the messages
1556                                 // if they are interested. (Asger)
1557                         }
1558                 }
1559         }
1560
1561         string const res = getMessage();
1562
1563         if (res.empty()) {
1564                 if (!commandshortcut.empty()) {
1565                         owner->getMiniBuffer()->addSet(commandshortcut);
1566                 }
1567         } else {
1568                 string const msg(_(res) + ' ' + commandshortcut);
1569                 owner->message(msg);
1570         }
1571
1572         return res;
1573 }
1574
1575
1576 void LyXFunc::setupLocalKeymap()
1577 {
1578         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1579         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1580 }
1581
1582
1583 void LyXFunc::MenuNew(bool fromTemplate)
1584 {
1585         string initpath = lyxrc.document_path;
1586
1587         if (owner->view()->available()) {
1588                 string const trypath = owner->buffer()->filepath;
1589                 // If directory is writeable, use this as default.
1590                 if (IsDirWriteable(trypath) == 1)
1591                         initpath = trypath;
1592         }
1593
1594         static int newfile_number;
1595         string s;
1596         
1597         if (lyxrc.new_ask_filename) {
1598                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1599                                    LFUN_SELECT_FILE_SYNC,
1600                         make_pair(string(_("Documents")),
1601                                   string(lyxrc.document_path)),
1602                         make_pair(string(_("Templates")),
1603                                   string(lyxrc.template_path)));
1604
1605                 FileDialog::Result result =
1606                         fileDlg.Select(initpath,
1607                                        _("*.lyx|LyX Documents (*.lyx)"),
1608                                        _("newfile"));
1609         
1610                 if (result.second.empty()) {
1611                         owner->message(_("Canceled."));
1612                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1613                         return;
1614                 }
1615         
1616                 // get absolute path of file and make sure the filename ends
1617                 // with .lyx
1618                 s = MakeAbsPath(result.second);
1619                 if (!IsLyXFilename(s))
1620                         s += ".lyx";
1621
1622                 // Check if the document already is open
1623                 if (bufferlist.exists(s)) {
1624                         switch (AskConfirmation(_("Document is already open:"),
1625                                                 MakeDisplayPath(s, 50),
1626                                                 _("Do you want to close that document now?\n"
1627                                                   "('No' will just switch to the open version)")))
1628                         {
1629                         case 1: // Yes: close the document
1630                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1631                                 // If close is canceled, we cancel here too.
1632                                         return;
1633                                 break;
1634                         case 2: // No: switch to the open document
1635                                 owner->view()->buffer(bufferlist.getBuffer(s));
1636                                 return;
1637                         case 3: // Cancel: Do nothing
1638                                 owner->message(_("Canceled."));
1639                                 return;
1640                         }
1641                 }
1642                 // Check whether the file already exists
1643                 FileInfo fi(s);
1644                 if (fi.readable() &&
1645                     AskQuestion(_("File already exists:"), 
1646                                 MakeDisplayPath(s, 50),
1647                                 _("Do you want to open the document?"))) {
1648                                 // loads document
1649                         string const disp_fn(MakeDisplayPath(s));
1650                         
1651                         ostringstream str;
1652                         str << _("Opening  document") << ' '
1653                             << disp_fn << "...";
1654                         
1655                         owner->message(str.str().c_str());
1656                         //XFlush(fl_get_display());
1657                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1658                         ostringstream str2;
1659                         str2 << _("Document") << ' '
1660                              << disp_fn << ' ' << _("opened.");
1661                         
1662                         owner->message(str2.str().c_str());
1663                         
1664                         return;
1665                 }
1666         } else {
1667                 s = AddName(lyxrc.document_path,
1668                             "newfile" + tostr(++newfile_number) + ".lyx");
1669                 FileInfo fi(s);
1670                 while (bufferlist.exists(s) || fi.readable()) {
1671                         ++newfile_number;
1672                         s = AddName(lyxrc.document_path,
1673                                     "newfile" + tostr(newfile_number) +
1674                                     ".lyx");
1675                         fi.newFile(s);
1676                 }
1677         }
1678
1679         // The template stuff
1680         string templname;
1681         if (fromTemplate) {
1682                 FileDialog fileDlg(owner, _("Select template file"),
1683                         LFUN_SELECT_FILE_SYNC,
1684                         make_pair(string(_("Documents")),
1685                                   string(lyxrc.document_path)),
1686                         make_pair(string(_("Templates")),
1687                                   string(lyxrc.template_path)));
1688
1689                 FileDialog::Result result =
1690                         fileDlg.Select(lyxrc.template_path,
1691                                        _("*.lyx|LyX Documents (*.lyx)"));
1692         
1693                 if (result.first == FileDialog::Later)
1694                         return;
1695
1696                 string const fname = result.second;
1697
1698                 if (fname.empty()) 
1699                         return;
1700                 templname = fname;
1701         }
1702   
1703         // find a free buffer
1704         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1705         owner->view()->buffer(bufferlist.newFile(s, templname));
1706 }
1707
1708
1709 void LyXFunc::Open(string const & fname)
1710 {
1711         string initpath = lyxrc.document_path;
1712   
1713         if (owner->view()->available()) {
1714                 string const trypath = owner->buffer()->filepath;
1715                 // If directory is writeable, use this as default.
1716                 if (IsDirWriteable(trypath) == 1)
1717                         initpath = trypath;
1718         }
1719
1720         string filename;
1721  
1722         if (fname.empty()) {
1723                 FileDialog fileDlg(owner, _("Select document to open"),
1724                         LFUN_FILE_OPEN,
1725                         make_pair(string(_("Documents")),
1726                                   string(lyxrc.document_path)),
1727                         make_pair(string(_("Examples")),
1728                                   string(AddPath(system_lyxdir, "examples"))));
1729
1730                 FileDialog::Result result =
1731                         fileDlg.Select(initpath,
1732                                        "*.lyx|LyX Documents (*.lyx)");
1733         
1734                 if (result.first == FileDialog::Later)
1735                         return;
1736
1737                 filename = result.second;
1738  
1739                 // check selected filename
1740                 if (filename.empty()) {
1741                         owner->message(_("Canceled."));
1742                         return;
1743                 }
1744         } else
1745                 filename = fname;
1746
1747         // get absolute path of file and add ".lyx" to the filename if
1748         // necessary
1749         filename = FileSearch(string(), filename, "lyx");
1750
1751         // loads document
1752         string const disp_fn(MakeDisplayPath(filename));
1753
1754         ostringstream str;
1755         str << _("Opening document") << ' ' << disp_fn << "...";
1756         
1757         owner->message(str.str().c_str());
1758
1759         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1760         if (openbuf) {
1761                 owner->view()->buffer(openbuf);
1762                 ostringstream str;
1763                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1764                 owner->message(str.str().c_str());
1765         } else {
1766                 ostringstream str;
1767                 str << _("Could not open docuent") << ' ' << disp_fn;
1768                 owner->message(str.str().c_str());
1769         }
1770 }
1771
1772
1773 // checks for running without gui are missing.
1774 void LyXFunc::doImport(string const & argument)
1775 {
1776         string format;
1777         string filename = split(argument, format, ' ');
1778         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format 
1779                             << " file: " << filename << endl;
1780
1781         if (filename.empty()) { // need user interaction
1782                 string initpath = lyxrc.document_path;
1783                 
1784                 if (owner->view()->available()) {
1785                         string const trypath = owner->buffer()->filepath;
1786                         // If directory is writeable, use this as default.
1787                         if (IsDirWriteable(trypath) == 1)
1788                                 initpath = trypath;
1789                 }
1790
1791                 string const text = _("Select ") + formats.PrettyName(format)
1792                         + _(" file to import");
1793
1794                 FileDialog fileDlg(owner, text, 
1795                         LFUN_IMPORT,
1796                         make_pair(string(_("Documents")),
1797                                   string(lyxrc.document_path)),
1798                         make_pair(string(_("Examples")),
1799                                   string(AddPath(system_lyxdir, "examples"))));
1800                         
1801                 string const extension = "*." + formats.Extension(format)
1802                         + "| " + formats.PrettyName(format)
1803                         + " (*." + formats.Extension(format) + ")";
1804
1805                 FileDialog::Result result = fileDlg.Select(initpath,
1806                                                            extension);
1807
1808                 if (result.first == FileDialog::Later)
1809                         return;
1810
1811                 filename = result.second;
1812  
1813                 // check selected filename
1814                 if (filename.empty())
1815                         owner->message(_("Canceled."));
1816         }
1817
1818         // still no filename? abort
1819         if (filename.empty()) 
1820                 return;
1821
1822         // get absolute path of file
1823         filename = MakeAbsPath(filename);
1824
1825         string const lyxfile = ChangeExtension(filename, ".lyx");
1826
1827         // Check if the document already is open
1828         if (bufferlist.exists(lyxfile)) {
1829                 switch (AskConfirmation(_("Document is already open:"), 
1830                                         MakeDisplayPath(lyxfile, 50),
1831                                         _("Do you want to close that document now?\n"
1832                                           "('No' will just switch to the open version)")))
1833                         {
1834                         case 1: // Yes: close the document
1835                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1836                                 // If close is canceled, we cancel here too.
1837                                         return;
1838                                 break;
1839                         case 2: // No: switch to the open document
1840                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1841                                 return;
1842                         case 3: // Cancel: Do nothing
1843                                 owner->message(_("Canceled."));
1844                                 return;
1845                         }
1846         }
1847
1848         // Check if a LyX document by the same root exists in filesystem
1849         FileInfo const f(lyxfile, true);
1850         if (f.exist() && !AskQuestion(_("A document by the name"), 
1851                                       MakeDisplayPath(lyxfile),
1852                                       _("already exists. Overwrite?"))) {
1853                 owner->message(_("Canceled"));
1854                 return;
1855         }
1856         // filename should be valid now
1857         
1858         Importer::Import(owner, filename, format);
1859 }
1860
1861
1862 void LyXFunc::reloadBuffer()
1863 {
1864         string const fn = owner->buffer()->fileName();
1865         if (bufferlist.close(owner->buffer()))
1866                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1867 }
1868
1869
1870 void LyXFunc::CloseBuffer()
1871 {
1872         if (bufferlist.close(owner->buffer()) && !quitting) {
1873                 if (bufferlist.empty()) {
1874                         // need this otherwise SEGV may occur while trying to
1875                         // set variables that don't exist
1876                         // since there's no current buffer
1877                         owner->getDialogs()->hideBufferDependent();
1878                 } else {
1879                         owner->view()->buffer(bufferlist.first());
1880                 }
1881         }
1882 }
1883
1884
1885 // Each "owner" should have it's own message method. lyxview and
1886 // the minibuffer would use the minibuffer, but lyxserver would
1887 // send an ERROR signal to its client.  Alejandro 970603
1888 // This func is bit problematic when it comes to NLS, to make the
1889 // lyx servers client be language indepenent we must not translate
1890 // strings sent to this func.
1891 void LyXFunc::setErrorMessage(string const & m) const
1892 {
1893         dispatch_buffer = m;
1894         errorstat = true;
1895 }
1896
1897
1898 void LyXFunc::setMessage(string const & m)
1899 {
1900         dispatch_buffer = m;
1901 }
1902
1903
1904 void LyXFunc::initMiniBuffer() 
1905 {
1906         string text = _("Welcome to LyX!");
1907         
1908         // When meta-fake key is pressed, show the key sequence so far + "M-".
1909         if (wasMetaKey()) {
1910                 keyseqStr();
1911                 text += "M-";
1912         }
1913
1914         // Else, when a non-complete key sequence is pressed,
1915         // show the available options.
1916         else if (keyseqUncomplete()) 
1917                 text = keyseqOptions();
1918    
1919         // Else, show the buffer state.
1920         else if (owner->view()->available()) {
1921                 Buffer * tmpbuf = owner->buffer();
1922                 
1923                 string const nicename = 
1924                         MakeDisplayPath(tmpbuf->fileName());
1925                 // Should we do this instead? (kindo like emacs)
1926                 // leaves more room for other information
1927                 text = "LyX: ";
1928                 text += nicename;
1929                 if (tmpbuf->lyxvc.inUse()) {
1930                         text += " [";
1931                         text += tmpbuf->lyxvc.version();
1932                         text += ' ';
1933                         text += tmpbuf->lyxvc.locker();
1934                         if (tmpbuf->isReadonly())
1935                                 text += " (RO)";
1936                         text += ']';
1937                 } else if (tmpbuf->isReadonly())
1938                         text += " [RO]";
1939                 if (!tmpbuf->isLyxClean())
1940                         text += _(" (Changed)");
1941         } else {
1942                 if (text != _("Welcome to LyX!")) // this is a hack
1943                         text = _("* No document open *");
1944         }
1945         
1946         owner->message(text);
1947 }
1948