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