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