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