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