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