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