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