]> git.lyx.org Git - features.git/blob - src/lyxfunc.C
New citation popup from Angus
[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-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef HAVE_SSTREAM
14 #include <sstream>
15 using std::istringstream;
16 #else
17 #include <strstream>
18 #endif
19
20 #include <time.h>
21 #include <locale.h>
22
23 #include <cstdlib>
24 #include <cctype>
25 #include <cstring>
26
27 #ifdef __GNUG__
28 #pragma implementation
29 #endif
30
31 #include "lyxlookup.h"
32 #include "kbmap.h"
33 #include "lyxfunc.h"
34 #include "bufferlist.h"
35 #include "lyxserver.h"
36 #include "lyx.h"
37 #include "intl.h"
38 #include "lyx_main.h"
39 #include "lyx_cb.h"
40 #include "LyXAction.h"
41 #include "insets/inseturl.h"
42 #include "insets/insetlatexaccent.h"
43 #include "insets/insettoc.h"
44 #include "insets/insetlof.h"
45 #include "insets/insetloa.h"
46 #include "insets/insetlot.h"
47 #include "insets/insetref.h"
48 #include "insets/insetparent.h"
49 #include "insets/insetindex.h"
50 #include "insets/insetinclude.h"
51 #include "insets/insetbib.h"
52 #include "insets/insetcite.h"
53 #include "insets/insettext.h"
54 #include "insets/insetert.h"
55 #include "insets/insetgraphics.h"
56 #include "insets/insetfoot.h"
57 #include "insets/insettabular.h"
58 #include "mathed/formulamacro.h"
59 #include "toolbar.h"
60 #include "spellchecker.h" // RVDK_PATCH_5
61 #include "minibuffer.h"
62 #include "vspace.h"
63 #include "LyXView.h"
64 #include "filedlg.h"
65 #include "lyx_gui_misc.h"
66 #include "support/filetools.h"
67 #include "support/FileInfo.h"
68 #include "support/syscall.h"
69 #include "support/lstrings.h"
70 #include "support/path.h"
71 #include "debug.h"
72 #include "lyxrc.h"
73 #include "lyxtext.h"
74 #include "gettext.h"
75 #include "trans_mgr.h"
76 #include "ImportLaTeX.h"
77 #include "ImportNoweb.h"
78 #include "layout.h"
79 #include "WorkArea.h"
80 #include "lyxfr1.h"
81 #include "menus.h"
82 #include "bufferview_funcs.h"
83
84 using std::pair;
85 using std::endl;
86
87 extern bool cursor_follows_scrollbar;
88
89 extern void InsertAsciiFile(BufferView *, string const &, bool);
90 extern void math_insert_symbol(char const *);
91 extern Bool math_insert_greek(char const); // why "Bool"?
92 extern BufferList bufferlist;
93 extern LyXServer * lyxserver;
94 extern short greek_kb_flag;
95 extern FD_form_toc * fd_form_toc;
96 extern bool selection_possible;
97
98 extern kb_keymap * toplevel_keymap;
99
100 extern void MenuWrite(Buffer *);
101 extern void MenuWriteAs(Buffer *);
102 extern int  MenuRunLaTeX(Buffer *);
103 extern int  MenuBuildProg(Buffer *);
104 extern int  MenuRunChktex(Buffer *);
105 extern bool CreatePostscript(Buffer *, bool);
106 extern void MenuPrint(Buffer *);
107 extern void MenuSendto();
108 extern void QuitLyX();
109 extern void MenuFax(Buffer *);
110 extern void MenuExport(Buffer *, string const &);
111
112 #define XFORMS_CLIPBOARD 1
113
114 #ifndef XFORMS_CLIPBOARD
115 extern void MenuPasteSelection(char at);
116 #endif
117
118 extern LyXAction lyxaction;
119 // (alkis)
120 extern tex_accent_struct get_accent(kb_action action);
121
122 extern void AutoSave(BufferView *);
123 extern void SetUpdateTimer(float timer = 0.3);
124 extern void FreeUpdateTimer();
125 extern bool PreviewDVI(Buffer *);
126 extern bool PreviewPostscript(Buffer *);
127 extern void MenuInsertLabel(char const *);
128 extern void MenuInsertRef();
129 extern void MenuLayoutCharacter();
130 extern void MenuLayoutParagraph();
131 extern void MenuLayoutDocument();
132 extern void MenuLayoutPaper();
133 extern void MenuLayoutTable(int flag);
134 extern void MenuLayoutQuotes();
135 extern void MenuLayoutPreamble();
136 extern void MenuLayoutSave();
137 extern void bulletForm();
138
139 extern Buffer * NewLyxFile(string const &);
140 extern void LoadLyXFile(string const &);
141 extern void Reconfigure(BufferView *);
142
143 extern LyXTextClass::size_type current_layout;
144 extern int getISOCodeFromLaTeX(char *);
145
146 extern void ShowLatexLog();
147
148 /* === globals =========================================================== */
149
150 bool LyXFunc::show_sc = true;
151
152
153 LyXFunc::LyXFunc(LyXView * o)
154         : owner(o)
155 {
156         meta_fake_bit = 0;
157         lyx_dead_action = LFUN_NOACTION;
158         lyx_calling_dead_action = LFUN_NOACTION;
159         setupLocalKeymap();
160 }
161
162
163 // I changed this func slightly. I commented out the ...FinishUndo(),
164 // this means that all places that used to have a moveCursorUpdate, now
165 // have a ...FinishUndo() as the preceeding statement. I have also added
166 // a moveCursorUpdate to some of the functions that updated the cursor, but
167 // that did not show its new position.
168 inline
169 void LyXFunc::moveCursorUpdate(bool selecting)
170 {
171         if (selecting || owner->view()->text->mark_set) {
172                 owner->view()->text->SetSelection();
173                 owner->view()->toggleToggle();
174                 //owner->view()->update(0);
175                 //} else {
176                 //owner->view()->update(-2); // this IS necessary
177                 // (Matthias) 
178         }
179         owner->view()->update(0);
180         owner->view()->showCursor();
181         
182         /* ---> Everytime the cursor is moved, show the current font state. */
183         // should this too me moved out of this func?
184         //owner->getMiniBuffer()->Set(CurrentState());
185         owner->view()->setState();
186 }
187
188
189 int LyXFunc::processKeyEvent(XEvent * ev)
190 {
191         char s_r[10];
192         string argument;
193         XKeyEvent * keyevent = &ev->xkey;
194         KeySym keysym_return = 0;
195
196         int num_bytes = LyXLookupString(ev, s_r, 10, &keysym_return);
197         s_r[num_bytes] = '\0';
198
199         if (lyxerr.debugging(Debug::KEY)) {
200                 char * tmp = XKeysymToString(keysym_return);
201                 string stm = (tmp ? tmp : "");
202                 lyxerr << "KeySym is "
203                        << stm
204                        << "["
205                        << keysym_return << "]"
206                        << " and num_bytes is "
207                        << num_bytes
208                        << " the string returned is \""
209                        << s_r << '\"' << endl;
210         }
211         // Do nothing if we have nothing (JMarc)
212         if (num_bytes == 0 && keysym_return == NoSymbol) {
213                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
214                                    << endl;
215                 return 0;
216         }
217         
218         // this function should be used always [asierra060396]
219         UpdatableInset * tli = owner->view()->the_locking_inset;
220         if (owner->view()->available() && tli && (keysym_return==XK_Escape)) {
221                 if (tli == tli->GetLockingInset()) {
222                         owner->view()->unlockInset(tli);
223                         owner->view()->text->CursorRight();
224                         moveCursorUpdate(false);
225                         owner->getMiniBuffer()->Set(CurrentState(owner->view()));
226                 } else {
227                         tli->UnlockInsetInInset(owner->view(),
228                                                 tli->GetLockingInset());
229                 }
230                 return 0;
231         }
232
233         // Can we be sure that this will work for all X-Windows
234         // implementations? (Lgb)
235         // This code snippet makes lyx ignore some keys. Perhaps
236         // all of them should be explictly mentioned?
237         if((keysym_return >= XK_Shift_L && keysym_return <= XK_Hyper_R)
238            || keysym_return == XK_Mode_switch || keysym_return == 0x0)
239                 return 0;
240
241         // Do a one-deep top-level lookup for
242         // cancel and meta-fake keys. RVDK_PATCH_5
243         cancel_meta_seq.reset();
244
245         int action = cancel_meta_seq.addkey(keysym_return, keyevent->state
246                                             &(ShiftMask|ControlMask
247                                               |Mod1Mask)); 
248
249         // When not cancel or meta-fake, do the normal lookup. 
250         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
251         // Mostly, meta_fake_bit = 0. RVDK_PATCH_5.
252         if ( (action != LFUN_CANCEL) && (action != LFUN_META_FAKE) ) {
253
254                 // remove Caps Lock and Mod2 as a modifiers
255                 action = keyseq.addkey(keysym_return,
256                                        (keyevent->state | meta_fake_bit)
257                                        &(ShiftMask|ControlMask
258                                          |Mod1Mask));      
259         }
260         // Dont remove this unless you know what you are doing.
261         meta_fake_bit = 0;
262                 
263         if (action == 0) action = LFUN_PREFIX;
264
265         if (lyxerr.debugging(Debug::KEY)) {
266                 string buf;
267                 keyseq.print(buf);
268                 lyxerr << "Key ["
269                        << action << "]["
270                        << buf << "]["
271                        << num_bytes << "]" << endl;
272         }
273
274         // already here we know if it any point in going further
275         // why not return already here if action == -1 and
276         // num_bytes == 0? (Lgb)
277
278         if(keyseq.length > 1 || keyseq.length < -1) {
279                 string buf;
280                 keyseq.print(buf);
281                 owner->getMiniBuffer()->Set(buf);
282         }
283
284         if (action == -1) {
285                 if (keyseq.length < -1) { // unknown key sequence...
286                         string buf;
287                         LyXBell();
288                         keyseq.print(buf);
289                         owner->getMiniBuffer()->Set(_("Unknown sequence:"), buf);
290                         return 0;
291                 }
292         
293                 char isochar = keyseq.getiso();
294                 if (!(keyevent->state&ControlMask) &&
295                     !(keyevent->state&Mod1Mask) &&
296                     (isochar && keysym_return < 0xF000)) {
297                         argument += isochar;
298                 }
299                 if (argument.empty()) {
300                         lyxerr.debug() << "Empty argument!" << endl;
301                         // This can`t possibly be of any use
302                         // so we`ll skip the dispatch.
303                         return 0;
304                 }
305         } else
306                 if (action == LFUN_SELFINSERT) {
307                         argument = s_r[0];
308                 }
309     
310         bool tmp_sc = show_sc;
311         show_sc = false;
312         Dispatch(action, argument.c_str());
313         show_sc = tmp_sc;
314         
315         return 0;
316
317
318
319 LyXFunc::func_status LyXFunc::getStatus(int ac) const
320 {
321         kb_action action;
322         func_status flag = LyXFunc::OK;
323         string argument;
324         Buffer * buf = owner->buffer();
325         
326         if (lyxaction.isPseudoAction(ac)) 
327                 action = lyxaction.retrieveActionArg(ac, argument);
328         else 
329                 action = static_cast<kb_action>(ac);
330         
331         if (action == LFUN_UNKNOWN_ACTION) {
332                 setErrorMessage(N_("Unknown action"));
333                 return LyXFunc::Unknown;
334         } 
335         
336         // Check whether we need a buffer
337         if (!lyxaction.funcHasFlag(action, LyXAction::NoBuffer)) {
338                 // Yes we need a buffer, do we have one?
339                 if (buf) {
340                         // yes
341                         // Can we use a readonly buffer?
342                         if (buf->isReadonly() && 
343                             !lyxaction.funcHasFlag(action,
344                                                    LyXAction::ReadOnly)) {
345                                 // no
346                                 setErrorMessage(N_("Document is read-only"));
347                                 flag |= LyXFunc::Disabled;
348                         }
349                 } else {
350                         // no
351                         setErrorMessage(N_("Command not allowed with"
352                                            "out any document open"));
353                         flag |= LyXFunc::Disabled;
354                 }
355         }
356
357         if (flag & LyXFunc::Disabled)
358                 return flag;
359
360         // I would really like to avoid having this switch and rather try to
361         // encode this in the function itself.
362         static bool noLaTeX = lyxrc.latex_command == "none";
363         bool disable = false;
364         switch (action) {
365         case LFUN_PREVIEW:
366                 disable = noLaTeX || lyxrc.view_dvi_command == "none";
367                 break;  
368         case LFUN_PREVIEWPS: 
369                 disable = noLaTeX || lyxrc.view_ps_command == "none";
370                 break;
371         case LFUN_RUNLATEX:
372         case LFUN_RUNDVIPS:
373                 disable = noLaTeX;
374                 break;
375         case LFUN_MENUPRINT:
376                 disable = noLaTeX || lyxrc.print_command == "none";
377                 break;
378         case LFUN_FAX:
379                 disable = noLaTeX || lyxrc.fax_command == "none"; 
380                 break;
381         case LFUN_IMPORT:
382                 if (argument == "latex")
383                         disable = lyxrc.relyx_command == "none";
384                 if (argument == "linuxdoc")
385                         disable = lyxrc.linuxdoc_to_lyx_command == "none";
386                 break;
387         case LFUN_EXPORT:
388                 if (argument == "dvi" || argument == "postscript")
389                         disable = noLaTeX;
390                 if (argument == "html")
391                         disable = lyxrc.html_command == "none";
392                 if (argument == "html-linuxdoc")
393                         disable = lyxrc.linuxdoc_to_html_command == "none";
394                 if (argument == "html-docbook")
395                         disable = lyxrc.docbook_to_html_command == "none";
396                 break;
397         case LFUN_UNDO:
398                 disable = buf->undostack.empty();
399                 break;
400         case LFUN_REDO:
401                 disable = buf->redostack.empty();
402                 break;
403         case LFUN_SPELLCHECK:
404                 disable = lyxrc.isp_command == "none";
405                 break;
406         case LFUN_RUNCHKTEX:
407                 disable = lyxrc.chktex_command == "none";
408                 break;
409         case LFUN_LAYOUT_TABLE:
410                 disable = ! owner->view()->text->cursor.par->table;
411                 break;
412         default:
413                 break;
414         }
415         if (disable)
416                 flag |= LyXFunc::Disabled;
417
418         if (buf) {
419                 func_status box = LyXFunc::ToggleOff;
420                 LyXFont font = owner->view()->text->real_current_font;
421                 switch (action) {
422                 case LFUN_EMPH:
423                         if (font.emph() == LyXFont::ON)
424                                 box = LyXFunc::ToggleOn;
425                         break;
426                 case LFUN_NOUN:
427                         if (font.noun() == LyXFont::ON)
428                                 box = LyXFunc::ToggleOn;
429                         break;
430                 case LFUN_BOLD:
431                         if (font.series() == LyXFont::BOLD_SERIES)
432                                 box = LyXFunc::ToggleOn;
433                         break;
434                 case LFUN_TEX:
435                         if (font.latex() == LyXFont::ON)
436                                 box = LyXFunc::ToggleOn;
437                         break;
438                 default:
439                         box = LyXFunc::OK;
440                         break;
441                 }
442                 flag |= box;
443         }
444
445         return flag;
446 }
447
448
449 string LyXFunc::Dispatch(string const & s) 
450 {
451         // Split command string into command and argument
452         string cmd, line = frontStrip(s);
453         string arg = strip(frontStrip(split(line, cmd, ' ')));
454
455         return Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
456 }
457
458
459 string LyXFunc::Dispatch(int ac,
460                          char const * do_not_use_this_arg)
461 {
462         string argument;
463         kb_action action;
464         
465         // we have not done anything wrong yet.
466         errorstat = false;
467         dispatch_buffer.erase();
468         
469         // if action is a pseudo-action, we need the real action
470         if (lyxaction.isPseudoAction(ac)) {
471                 string tmparg;
472                 action = static_cast<kb_action>
473                         (lyxaction.retrieveActionArg(ac, tmparg));
474                 if (!tmparg.empty())
475                         argument = tmparg;
476         } else {
477                 action = static_cast<kb_action>(ac);
478                 if (do_not_use_this_arg)
479                         argument = do_not_use_this_arg; // except here
480         }
481     
482         selection_possible = false;
483         
484         if (owner->view()->available())
485                 owner->view()->hideCursor();
486
487         // We cannot use this function here
488         if (getStatus(action) & Disabled)
489                 goto exit_with_message;
490
491         commandshortcut.erase();
492         
493         if (lyxrc.display_shortcuts && show_sc) {
494                 if (action != LFUN_SELFINSERT) {
495                         // Put name of command and list of shortcuts
496                         // for it in minibuffer
497                         string comname = lyxaction.getActionName(action);
498
499                         int pseudoaction = action;
500                         bool argsadded = false;
501
502                         if (!argument.empty()) {
503                                 // If we have the command with argument, 
504                                 // this is better
505                                 pseudoaction = 
506                                         lyxaction.searchActionArg(action,
507                                                                   argument.c_str());
508
509                                 if (pseudoaction == -1) {
510                                         pseudoaction = action;
511                                 } else {
512                                         comname += " " + argument;
513                                         argsadded = true;
514                                 }
515                         }
516
517                         string shortcuts = toplevel_keymap->findbinding(pseudoaction);
518
519                         if (!shortcuts.empty()) {
520                                 comname += ": " + shortcuts;
521                         } else if (!argsadded) {
522                                 comname += " " + argument;
523                         }
524
525                         if (!comname.empty()) {
526                                 comname = strip(comname);
527                                 commandshortcut = "(" + comname + ')';
528                                 owner->getMiniBuffer()->Set(commandshortcut);
529                                 // Here we could even add a small pause,
530                                 // to annoy the user and make him learn
531                                 // the shortcuts.
532                                 // No! That will just annoy, not teach
533                                 // anything. The user will read the messages
534                                 // if they are interested. (Asger)
535                         }
536                 }
537         }
538
539         // If in math mode pass the control to
540         // the math inset [asierra060396]
541         if (owner->view()->available() &&
542             owner->view()->the_locking_inset) {
543                 UpdatableInset::RESULT result;
544                 if (action > 1
545                     || (action == LFUN_UNKNOWN_ACTION
546                         && keyseq.length >= -1)) {
547                         if (action == LFUN_UNKNOWN_ACTION
548                             && argument.empty()) {
549                                 argument = keyseq.getiso();
550                         }
551                         // Undo/Redo pre 0.13 is a bit tricky for insets.
552                         if (action == LFUN_UNDO) {
553                                 int slx, sly;
554                                 UpdatableInset * inset = 
555                                         owner->view()->the_locking_inset;
556                                 inset->GetCursorPos(slx, sly);
557                                 owner->view()->unlockInset(inset);
558                                 owner->view()->menuUndo();
559                                 if (owner->view()->text->cursor.par->
560                                     IsInset(owner->view()->text->cursor.pos)) {
561                                         inset = static_cast<UpdatableInset*>(
562                                                 owner->view()->text->cursor.par->
563                                                 GetInset(owner->view()->text->
564                                                          cursor.pos));
565                                 } else {
566                                         inset = 0;
567                                 }
568                                 if (inset)
569                                         inset->Edit(owner->view(),slx,sly,0);
570                                 return string();
571                         } else if (action == LFUN_REDO) {
572                                 int slx, sly;
573                                 UpdatableInset * inset = owner->view()->
574                                         the_locking_inset;
575                                 inset->GetCursorPos(slx, sly);
576                                 owner->view()->unlockInset(inset);
577                                 owner->view()->menuRedo();
578                                 inset = static_cast<UpdatableInset*>(
579                                         owner->view()->text->cursor.par->
580                                         GetInset(owner->view()->text->
581                                                  cursor.pos));
582                                 if (inset)
583                                         inset->Edit(owner->view(),slx,sly,0); 
584                                 return string();
585                         } else if (((result=owner->view()->the_locking_inset->
586                                    LocalDispatch(owner->view(), action,
587                                                  argument)) ==
588                                    UpdatableInset::DISPATCHED) ||
589                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
590                                 return string();
591                         else {
592                                 setMessage(N_("Text mode"));
593                                 switch(action) {
594                                 case LFUN_UNKNOWN_ACTION:
595                                 case LFUN_BREAKPARAGRAPH:
596                                 case LFUN_BREAKLINE:
597                                         owner->view()->text->CursorRight();
598                                         owner->view()->setState();
599                                         owner->getMiniBuffer()->Set(CurrentState(owner->view()));
600                                         break;
601                                 case LFUN_RIGHT:
602                                         if (!owner->view()->text->cursor.par->isRightToLeftPar()) {
603                                                 owner->view()->text->CursorRight();
604                                                 moveCursorUpdate(false);
605                                                 owner->getMiniBuffer()->
606                                                         Set(CurrentState(owner->view()));
607                                         }
608                                         return string();
609                                 case LFUN_LEFT: 
610                                         if (owner->view()->text->cursor.par->isRightToLeftPar()) {
611                                                 owner->view()->text->CursorRight();
612                                                 moveCursorUpdate(false);
613                                                 owner->getMiniBuffer()->
614                                                         Set(CurrentState(owner->view()));
615                                         }
616                                         return string();
617                                 case LFUN_DOWN:
618                                         owner->view()->text->CursorDown();
619                                         moveCursorUpdate(false);
620                                         owner->getMiniBuffer()->
621                                                 Set(CurrentState(owner->view()));
622                                         return string();
623                                 default:
624                                         break;
625                                 }
626                         }
627                 }
628         }
629
630         switch(action) {
631                 // --- Misc -------------------------------------------
632         case LFUN_WORDFINDFORWARD  : 
633         case LFUN_WORDFINDBACKWARD : {
634                 static string last_search;
635                 string searched_string;
636             
637                 if (!argument.empty()) {
638                         last_search = argument;
639                         searched_string = argument;
640                 } else {
641                         searched_string = last_search;
642                 }
643
644                 LyXText * ltCur = owner->view()->text ;
645
646                 if (!searched_string.empty() &&
647                     ((action == LFUN_WORDFINDBACKWARD) ? 
648                      ltCur->SearchBackward(searched_string.c_str()) :
649                      ltCur->SearchForward(searched_string.c_str()))) {
650
651                         // ??? What is that ???
652                         owner->view()->update(-2);
653
654                         // ??? Needed ???
655                         // clear the selection (if there is any) 
656                         owner->view()->toggleSelection();
657                         owner->view()->text->ClearSelection();
658
659                         // Move cursor so that successive C-s 's will not stand in place. 
660                         if( action == LFUN_WORDFINDFORWARD ) 
661                                 owner->view()->text->CursorRightOneWord();
662                         owner->view()->text->FinishUndo();
663                         moveCursorUpdate(false);
664
665                         // ??? Needed ???
666                         // set the new selection 
667                         // SetSelectionOverLenChars(owner->view()->currentBuffer()->text, iLenSelected);
668                         owner->view()->toggleSelection(false);
669                 } else 
670                         LyXBell();      
671          
672                 // REMOVED : if (owner->view()->getWorkArea()->focus)
673                 owner->view()->showCursor();
674         }
675         break;
676
677         case LFUN_PREFIX:
678         {
679                 if (owner->view()->available()) {
680                         owner->view()->update(-2);
681                 }
682                 string buf;
683                 keyseq.print(buf, true);
684                 owner->getMiniBuffer()->Set(buf, string(), string(), 1);
685         }
686         break;
687
688         // --- Misc -------------------------------------------
689         case LFUN_EXEC_COMMAND:
690                 owner->getMiniBuffer()->ExecCommand(); 
691                 break;
692                 
693         case LFUN_CANCEL:                   // RVDK_PATCH_5
694                 keyseq.reset();
695                 meta_fake_bit = 0;
696                 if(owner->view()->available())
697                         // cancel any selection
698                         Dispatch(LFUN_MARK_OFF, 0);
699                 setMessage(N_("Cancel"));
700                 break;
701
702         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
703         {
704                 meta_fake_bit = Mod1Mask;
705                 string buf;
706                 keyseq.print(buf, true);
707                 string res = string("M-") + buf;
708                 setMessage(buf); // RVDK_PATCH_5
709         }
710         break;  
711
712         case LFUN_READ_ONLY_TOGGLE:
713                 if (owner->buffer()->lyxvc.inUse()) {
714                         owner->buffer()->lyxvc.toggleReadOnly();
715                 } else {
716                         owner->buffer()->setReadonly(
717                                 !owner->buffer()->isReadonly());
718                 }
719                 break;
720                 
721         case LFUN_CENTER: // this is center and redraw.
722                 owner->view()->center();
723                 break;
724                 
725         case LFUN_APPENDIX:
726                 if (owner->view()->available()) {
727                         owner->view()->text->toggleAppendix();
728                         owner->view()->update(1);
729                 }
730                 break;
731
732                 // --- Menus -----------------------------------------------
733         case LFUN_MENUNEW:
734                 MenuNew(false);
735                 break;
736                 
737         case LFUN_MENUNEWTMPLT:
738                 MenuNew(true);
739                 break;
740                 
741         case LFUN_MENUOPEN:
742                 MenuOpen();
743                 break;
744                 
745         case LFUN_CLOSEBUFFER:
746                 CloseBuffer();
747                 break;
748                 
749         case LFUN_MENUWRITE:
750                 owner->getMiniBuffer()->Set(_("Saving document"),
751                                             MakeDisplayPath(owner->buffer()->fileName()),
752                                             "...");
753                 MenuWrite(owner->buffer());
754                 //owner->getMiniBuffer()-> {
755                 //      Set(_("Document saved as"),
756                 //          MakeDisplayPath(owner->buffer()->fileName()));
757                 //} else {
758                 //owner->getMiniBuffer()->Set(_("Save failed!"));
759                 //}
760                 break;
761                 
762         case LFUN_MENUWRITEAS:
763                 MenuWriteAs(owner->buffer());
764                 break;
765                 
766         case LFUN_MENURELOAD:
767                 reloadBuffer();
768                 break;
769                 
770         case LFUN_PREVIEW:
771                 PreviewDVI(owner->buffer());
772                 break;
773                         
774         case LFUN_PREVIEWPS:
775                 PreviewPostscript(owner->buffer());
776                 break;
777                 
778         case LFUN_RUNLATEX:
779                 MenuRunLaTeX(owner->buffer());
780                 break;
781                 
782         case LFUN_BUILDPROG:
783                 MenuBuildProg(owner->buffer());
784                 break;
785                 
786         case LFUN_RUNCHKTEX:
787                 MenuRunChktex(owner->buffer());
788                 break;
789                 
790         case LFUN_RUNDVIPS:
791                 CreatePostscript(owner->buffer(), false);
792                 break;
793                 
794         case LFUN_MENUPRINT:
795                 MenuPrint(owner->buffer());
796                 break;
797                 
798         case LFUN_FAX:
799                 MenuFax(owner->buffer());
800                 break;
801                         
802         case LFUN_EXPORT:
803                 MenuExport(owner->buffer(), argument);
804                 break;
805
806         case LFUN_IMPORT:
807                 doImport(argument);
808                 break;
809                 
810         case LFUN_QUIT:
811                 QuitLyX();
812                 break;
813                 
814         case LFUN_TOCVIEW:
815         case LFUN_LOFVIEW:
816         case LFUN_LOTVIEW:
817         case LFUN_LOAVIEW:
818         {
819                 Buffer::TocType type = Buffer::TOC_TOC;
820                 if (action == LFUN_LOFVIEW)
821                         type = Buffer::TOC_LOF;
822                 else if (action == LFUN_LOTVIEW)
823                         type = Buffer::TOC_LOT;
824                 else if (action == LFUN_LOAVIEW)
825                         type = Buffer::TOC_LOA;
826                 fl_set_choice(fd_form_toc->toctype,type + 1);
827                 TocUpdateCB(0, 0);
828                 if (fd_form_toc->form_toc->visible) {
829                         fl_raise_form(fd_form_toc->form_toc);
830                 } else {
831                         static int ow = -1, oh;
832                         fl_show_form(fd_form_toc->form_toc,
833                                      FL_PLACE_MOUSE |
834                                      FL_FREE_SIZE, FL_FULLBORDER,
835                                      _("Table of Contents"));
836                         if (ow < 0) {
837                                 ow = fd_form_toc->form_toc->w;
838                                 oh = fd_form_toc->form_toc->h;
839                         }
840                         fl_set_form_minsize(fd_form_toc->form_toc, ow, oh);
841                 }
842                 break;
843         }       
844         case LFUN_TOC_INSERT:
845         {
846                 Inset * new_inset = new InsetTOC(owner->buffer());
847                 if (!owner->view()->insertInset(new_inset, "Standard", true))
848                         delete new_inset;
849                 break;
850         }
851         
852         case LFUN_LOF_INSERT:
853         {
854                 Inset * new_inset = new InsetLOF(owner->buffer());
855                 if (!owner->view()->insertInset(new_inset, "Standard", true))
856                         delete new_inset;
857                 break;
858         }
859         
860         case LFUN_LOA_INSERT:
861         {
862                 Inset * new_inset = new InsetLOA(owner->buffer());
863                 if (!owner->view()->insertInset(new_inset, "Standard", true))
864                         delete new_inset;
865                 break;
866         }
867
868         case LFUN_LOT_INSERT:
869         {
870                 Inset * new_inset = new InsetLOT(owner->buffer());
871                 if (!owner->view()->insertInset(new_inset, "Standard", true))
872                         delete new_inset;
873                 break;
874         }
875                 
876         case LFUN_TABLE:
877                 Table();
878                 break;
879                 
880         case LFUN_FIGURE:
881                 Figure();
882                 break;
883
884         case LFUN_INSERT_GRAPHICS:
885         {
886                 Inset * new_inset = new InsetGraphics;
887                 if (!owner->view()->insertInset(new_inset))
888                         delete new_inset;
889                 break;
890         }
891         
892         case LFUN_AUTOSAVE:
893                 AutoSave(owner->view());
894                 break;
895                 
896         case LFUN_UNDO:
897                 owner->view()->menuUndo();
898                 break;
899                 
900         case LFUN_REDO:
901                 owner->view()->menuRedo();
902                 break;
903                 
904         case LFUN_MENUSEARCH:
905         {
906                 // Ok this is one _very_ bad solution, but I think that some
907                 // of this will be rewritten as part of GUI indep anyway.
908                 // Lgb
909                 static LyXFindReplace FR_;
910                 FR_.StartSearch(owner->view());
911         }
912         break;
913                 
914         case LFUN_PASTE:
915                 owner->view()->paste();
916                 owner->view()->setState();
917                 break;
918                 
919         case LFUN_PASTESELECTION:
920         {
921                 bool asPara = false;
922                 if (argument == "paragraph") asPara = true;
923 #ifdef XFORMS_CLIPBOARD
924                 owner->view()->pasteClipboard(asPara);
925 #else
926                 MenuPasteSelection(asPara);
927 #endif
928         }
929         break;
930         
931         case LFUN_CUT:
932                 owner->view()->cut();
933                 break;
934                 
935         case LFUN_COPY:
936                 owner->view()->copy();
937                 break;
938                 
939         case LFUN_LAYOUT_COPY:
940                 owner->view()->copyEnvironment();
941                 break;
942                 
943         case LFUN_LAYOUT_PASTE:
944                 owner->view()->pasteEnvironment();
945                 owner->view()->setState();
946                 break;
947                 
948         case LFUN_GOTOERROR:
949                 owner->view()->gotoError();
950                 break;
951                 
952         case LFUN_REMOVEERRORS:
953                 if (owner->view()->removeAutoInsets()) {
954                         owner->view()->redraw();
955                         owner->view()->fitCursor();
956                         //owner->view()->updateScrollbar();
957                 }
958                 break;
959                 
960         case LFUN_GOTONOTE:
961                 owner->view()->gotoNote();
962                 break;
963                 
964         case LFUN_OPENSTUFF:
965                 owner->view()->openStuff();
966                 break;
967                 
968         case LFUN_HYPHENATION:
969                 owner->view()->hyphenationPoint();
970                 break;
971                 
972         case LFUN_LDOTS:
973                 owner->view()->ldots();
974                 break;
975                 
976         case LFUN_END_OF_SENTENCE:
977                 owner->view()->endOfSentenceDot();
978                 break;
979
980         case LFUN_MENU_SEPARATOR:
981                 owner->view()->menuSeparator();
982                 break;
983                 
984         case LFUN_HFILL:
985                 owner->view()->hfill();
986                 break;
987                 
988         case LFUN_DEPTH:
989                 changeDepth(owner->view(), 0);
990                 break;
991                 
992         case LFUN_DEPTH_MIN:
993                 changeDepth(owner->view(), -1);
994                 break;
995                 
996         case LFUN_DEPTH_PLUS:
997                 changeDepth(owner->view(), 1);
998                 break;
999                 
1000         case LFUN_FREE:
1001                 Free(owner->view());
1002                 owner->view()->setState();
1003                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1004                 break;
1005                 
1006         case LFUN_TEX:
1007                 Tex(owner->view());
1008                 owner->view()->setState();
1009                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1010                 break;
1011                 
1012         case LFUN_MELT:
1013                 Melt(owner->view());
1014                 break;
1015                 
1016         case LFUN_RECONFIGURE:
1017                 Reconfigure(owner->view());
1018                 break;
1019
1020         case LFUN_FOOTMELT:
1021                 if (owner->view()->available()
1022                     && !owner->view()->text->selection
1023                     && owner->view()->text->cursor.par->footnoteflag
1024                     != LyXParagraph::NO_FOOTNOTE)
1025                         { // only melt footnotes with FOOTMELT, not margins etc
1026                                 if(owner->view()->text->cursor.par->footnotekind == LyXParagraph::FOOTNOTE)
1027                                         Melt(owner->view());
1028                         }
1029                 else
1030                         Foot(owner->view()); 
1031                 owner->view()->setState();
1032                 break;
1033
1034         case LFUN_MARGINMELT:
1035                 if (owner->view()->available()
1036                     && !owner->view()->text->selection
1037                     && owner->view()->text->cursor.par->footnoteflag
1038                     != LyXParagraph::NO_FOOTNOTE) {
1039                         // only melt margins
1040                         if(owner->view()->text->cursor.par->footnotekind == LyXParagraph::MARGIN)
1041                                 Melt(owner->view());
1042                 } else
1043                         Margin(owner->view()); 
1044                 owner->view()->setState();
1045                 break;
1046                 
1047                 // --- version control -------------------------------
1048         case LFUN_VC_REGISTER:
1049         {
1050                 if (!owner->buffer()->lyxvc.inUse())
1051                         owner->buffer()->lyxvc.registrer();
1052         }
1053         break;
1054                 
1055         case LFUN_VC_CHECKIN:
1056         {
1057                 if (owner->buffer()->lyxvc.inUse()
1058                     && !owner->buffer()->isReadonly())
1059                         owner->buffer()->lyxvc.checkIn();
1060         }
1061         break;
1062                 
1063         case LFUN_VC_CHECKOUT:
1064         {
1065                 if (owner->buffer()->lyxvc.inUse()
1066                     && owner->buffer()->isReadonly())
1067                         owner->buffer()->lyxvc.checkOut();
1068         }
1069         break;
1070         
1071         case LFUN_VC_REVERT:
1072         {
1073                 owner->buffer()->lyxvc.revert();
1074         }
1075         break;
1076                 
1077         case LFUN_VC_UNDO:
1078         {
1079                 owner->buffer()->lyxvc.undoLast();
1080         }
1081         break;
1082                 
1083         case LFUN_VC_HISTORY:
1084         {
1085                 owner->buffer()->lyxvc.showLog();
1086                 break;
1087         }
1088         
1089         // --- buffers ----------------------------------------
1090
1091         case LFUN_FILE_INSERT:
1092         {
1093                 MenuInsertLyXFile(argument);
1094         }
1095         break;
1096         
1097         case LFUN_FILE_INSERT_ASCII:
1098         {
1099                 bool asPara = (argument == "paragraph");
1100                 InsertAsciiFile(owner->view(), string(), asPara);
1101         }
1102         break;
1103         
1104         case LFUN_FILE_NEW:
1105         {
1106                 // servercmd: argument must be <file>:<template>
1107                 Buffer * tmpbuf = NewLyxFile(argument);
1108                 if (tmpbuf)
1109                         owner->view()->buffer(tmpbuf);
1110         }
1111         break;
1112                         
1113         case LFUN_FILE_OPEN:
1114                 owner->view()->buffer(bufferlist.loadLyXFile(argument));
1115                 break;
1116
1117         case LFUN_LATEX_LOG:
1118                 ShowLatexLog();
1119                 break;
1120                 
1121         case LFUN_LAYOUTNO:
1122         {
1123                 lyxerr.debug() << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1124                 int sel = strToInt(argument);
1125                 lyxerr.debug() << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1126                 
1127                 // Should this give a setMessage instead?
1128                 if (sel == 0) 
1129                         return string(); // illegal argument
1130
1131                 --sel; // sel 1..., but layout 0...
1132
1133                 // Pretend we got the name instead.
1134                 Dispatch(int(LFUN_LAYOUT), 
1135                          textclasslist.NameOfLayout(owner->view()
1136                                                     ->buffer()->params.textclass,
1137                                                     sel).c_str());
1138                 return string();
1139         }
1140                 
1141         case LFUN_LAYOUT:
1142         {
1143                 lyxerr.debug() << "LFUN_LAYOUT: (arg) "
1144                                << argument << endl;
1145                 
1146                 // Derive layout number from given argument (string)
1147                 // and current buffer's textclass (number). */    
1148                 LyXTextClassList::ClassList::size_type tclass =
1149                         owner->view()->buffer()->params.textclass;
1150                 pair <bool, LyXTextClass::size_type> layout = 
1151                         textclasslist.NumberOfLayout(tclass, argument);
1152
1153                 // If the entry is obsolete, use the new one instead.
1154                 if (layout.first) {
1155                         string obs = textclasslist.Style(tclass,layout.second)
1156                               .obsoleted_by();
1157                         if (!obs.empty()) 
1158                                 layout = 
1159                                   textclasslist.NumberOfLayout(tclass, obs);
1160                 }
1161
1162                 // see if we found the layout number:
1163                 if (!layout.first) {
1164                         setErrorMessage(string(N_("Layout ")) + argument + 
1165                                         N_(" not known"));
1166                         break;
1167                 }
1168
1169                 if (current_layout != layout.second) {
1170                         owner->view()->hideCursor();
1171                         current_layout = layout.second;
1172                         owner->view()->update(-2);
1173                         owner->view()->text->
1174                                 SetLayout(layout.second);
1175                         owner->getToolbar()->combox->
1176                                 select(owner->view()->
1177                                        text->cursor.par->
1178                                        GetLayout() + 1);
1179                         owner->view()->update(1);
1180                         owner->view()->setState();
1181                 }
1182         }
1183         break;
1184
1185         case LFUN_LAYOUT_DOCUMENT:
1186                 MenuLayoutDocument();
1187                 break;
1188                 
1189         case LFUN_LAYOUT_PARAGRAPH:
1190                 MenuLayoutParagraph();
1191                 break;
1192                 
1193         case LFUN_LAYOUT_CHARACTER:
1194                 MenuLayoutCharacter();
1195                 break;
1196                 
1197         case LFUN_LAYOUT_TABLE:
1198         {
1199                 int flag = 0;
1200                 if (argument == "true") flag = 1;
1201                 MenuLayoutTable(flag);
1202         }
1203         break;
1204                 
1205         case LFUN_LAYOUT_PAPER:
1206                 MenuLayoutPaper();
1207                 break;
1208                 
1209         case LFUN_LAYOUT_QUOTES:
1210                 MenuLayoutQuotes();
1211                 break;
1212                 
1213         case LFUN_LAYOUT_PREAMBLE:
1214                 MenuLayoutPreamble();
1215                 break;
1216                 
1217         case LFUN_LAYOUT_SAVE_DEFAULT:
1218                 MenuLayoutSave();
1219                 break;
1220                 
1221         case LFUN_DROP_LAYOUTS_CHOICE:
1222                 owner->getToolbar()->combox->Show();
1223                 break;
1224
1225         case LFUN_LANGUAGE:
1226                 Lang(owner->view(), argument);
1227                 owner->view()->setState();
1228                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1229                 break;
1230
1231         case LFUN_EMPH:
1232                 Emph(owner->view());
1233                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1234                 break;
1235
1236         case LFUN_BOLD:
1237                 Bold(owner->view());
1238                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1239                 break;
1240                 
1241         case LFUN_NOUN:
1242                 Noun(owner->view());
1243                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1244                 break;
1245                 
1246         case LFUN_CODE:
1247                 Code(owner->view());
1248                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1249                 break;
1250                 
1251         case LFUN_SANS:
1252                 Sans(owner->view());
1253                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1254                 break;
1255                 
1256         case LFUN_ROMAN:
1257                 Roman(owner->view());
1258                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1259                 break;
1260                 
1261         case LFUN_DEFAULT:
1262                 StyleReset(owner->view());
1263                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1264                 break;
1265                 
1266         case LFUN_UNDERLINE:
1267                 Underline(owner->view());
1268                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1269                 break;
1270                 
1271         case LFUN_FONT_SIZE:
1272                 FontSize(owner->view(), argument);
1273                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1274                 break;
1275                 
1276         case LFUN_FONT_STATE:
1277                 setMessage(CurrentState(owner->view()));
1278                 break;
1279                 
1280         case LFUN_UPCASE_WORD:
1281                 owner->view()->update(-2);
1282                 FreeUpdateTimer();
1283                 owner->view()->text->ChangeWordCase(LyXText::text_uppercase);
1284                 owner->view()->update(1);
1285                 SetUpdateTimer();
1286                 break;
1287                 
1288         case LFUN_LOWCASE_WORD:
1289                 owner->view()->update(-2);
1290                 FreeUpdateTimer();
1291                 owner->view()->text->ChangeWordCase(LyXText::text_lowercase);
1292                 owner->view()->update(1);
1293                 SetUpdateTimer();
1294                 break;
1295                 
1296         case LFUN_CAPITALIZE_WORD:
1297                 owner->view()->update(-2);
1298                 FreeUpdateTimer();
1299                 owner->view()->text->ChangeWordCase(LyXText::text_capitalization);
1300                 owner->view()->update(1);
1301                 SetUpdateTimer();
1302                 break;
1303                 
1304         case LFUN_INSERT_LABEL:
1305                 MenuInsertLabel(argument.c_str());
1306                 break;
1307                 
1308         case LFUN_INSERT_REF:
1309                 MenuInsertRef();
1310                 break;
1311                 
1312         case LFUN_REFTOGGLE:
1313         {
1314                 InsetRef * inset = 
1315                         static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1316                 if (inset) {
1317                         inset->Toggle();
1318                         owner->view()->updateInset(inset, true);
1319                 } else {
1320                         setErrorMessage(N_("No cross-reference to toggle"));
1321                 }
1322         }
1323         break;
1324         
1325         case LFUN_REFBACK:
1326         {
1327                 owner->view()->restorePosition();
1328         }
1329         break;
1330
1331         case LFUN_REFGOTO:
1332         {
1333                 string label(argument);
1334                 if (label.empty()) {
1335                         InsetRef * inset = 
1336                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1337                         if (inset)
1338                                 label = inset->getContents();
1339                 }
1340                 
1341                 if (!label.empty()) {
1342                         owner->view()->savePosition();
1343                         if (!owner->view()->gotoLabel(label))
1344                                 WriteAlert(_("Error"), 
1345                                            _("Couldn't find this label"), 
1346                                            _("in current document."));
1347                 }
1348         }
1349         break;
1350                 
1351         case LFUN_MENU_OPEN_BY_NAME:
1352                 owner->getMenus()->openByName(argument);
1353                 break; // RVDK_PATCH_5
1354                 
1355         case LFUN_SPELLCHECK:
1356                 if (lyxrc.isp_command != "none")
1357                         ShowSpellChecker(owner->view());
1358                 break; // RVDK_PATCH_5
1359                 
1360                 // --- Cursor Movements -----------------------------
1361         case LFUN_RIGHT:
1362         {
1363                 LyXText * tmptext = owner->view()->text;
1364                 bool is_rtl = tmptext->cursor.par->isRightToLeftPar();
1365                 if(!tmptext->mark_set)
1366                         owner->view()->beforeChange();
1367                 owner->view()->update(-2);
1368                 if (is_rtl)
1369                         tmptext->CursorLeft(false);
1370                 if (tmptext->cursor.pos < tmptext->cursor.par->Last()
1371                     && tmptext->cursor.par->GetChar(tmptext->cursor.pos)
1372                     == LyXParagraph::META_INSET
1373                     && tmptext->cursor.par->GetInset(tmptext->cursor.pos)
1374                     && tmptext->cursor.par->GetInset(tmptext->cursor.pos)->Editable() == Inset::HIGHLY_EDITABLE){
1375                         Inset * tmpinset = tmptext->cursor.par->GetInset(tmptext->cursor.pos);
1376                         setMessage(tmpinset->EditMessage());
1377                         tmpinset->Edit(owner->view(), 0, 0, 0);
1378                         break;
1379                 }
1380                 if (!is_rtl)
1381                         tmptext->CursorRight(false);
1382                 owner->view()->text->FinishUndo();
1383                 moveCursorUpdate(false);
1384                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1385         }
1386         break;
1387                 
1388         case LFUN_LEFT:
1389         {
1390                 // This is soooo ugly. Isn`t it possible to make
1391                 // it simpler? (Lgb)
1392                 LyXText * txt = owner->view()->text;
1393                 bool is_rtl = txt->cursor.par->isRightToLeftPar();
1394                 if(!txt->mark_set) owner->view()->beforeChange();
1395                 owner->view()->update(-2);
1396                 if (!is_rtl)
1397                         txt->CursorLeft(false);
1398                 if (txt->cursor.pos < txt->cursor.par->Last()
1399                     && txt->cursor.par->GetChar(txt->cursor.pos)
1400                     == LyXParagraph::META_INSET
1401                     && txt->cursor.par->GetInset(txt->cursor.pos)
1402                     && txt->cursor.par->GetInset(txt->cursor.pos)->Editable() == Inset::HIGHLY_EDITABLE) {
1403                         Inset * tmpinset = txt->cursor.par->GetInset(txt->cursor.pos);
1404                         setMessage(tmpinset->EditMessage());
1405                         LyXFont font = txt->GetFont(txt->cursor.par,
1406                                                     txt->cursor.pos);
1407                         tmpinset->Edit(owner->view(),
1408                                        tmpinset->x() + tmpinset->width(owner->view()->painter(),font),
1409                                        tmpinset->descent(owner->view()->painter(),font),
1410                                        0);
1411                         break;
1412                 }
1413                 if  (is_rtl)
1414                         txt->CursorRight(false);
1415
1416                 owner->view()->text->FinishUndo();
1417                 moveCursorUpdate(false);
1418                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1419         }
1420         break;
1421                 
1422         case LFUN_UP:
1423                 if(!owner->view()->text->mark_set) owner->view()->beforeChange();
1424                 owner->view()->update(-3);
1425                 owner->view()->text->CursorUp();
1426                 owner->view()->text->FinishUndo();
1427                 moveCursorUpdate(false);
1428                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1429                 break;
1430                 
1431         case LFUN_DOWN:
1432                 if(!owner->view()->text->mark_set)
1433                         owner->view()->beforeChange();
1434                 owner->view()->update(-3);
1435                 owner->view()->text->CursorDown();
1436                 owner->view()->text->FinishUndo();
1437                 moveCursorUpdate(false);
1438                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1439                 break;
1440
1441         case LFUN_UP_PARAGRAPH:
1442                 if(!owner->view()->text->mark_set)
1443                         owner->view()->beforeChange();
1444                 owner->view()->update(-3);
1445                 owner->view()->text->CursorUpParagraph();
1446                 owner->view()->text->FinishUndo();
1447                 moveCursorUpdate(false);
1448                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1449                 break;
1450                 
1451         case LFUN_DOWN_PARAGRAPH:
1452                 if(!owner->view()->text->mark_set)
1453                         owner->view()->beforeChange();
1454                 owner->view()->update(-3);
1455                 owner->view()->text->CursorDownParagraph();
1456                 owner->view()->text->FinishUndo();
1457                 moveCursorUpdate(false);
1458                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1459                 break;
1460                 
1461         case LFUN_PRIOR:
1462                 if(!owner->view()->text->mark_set)
1463                         owner->view()->beforeChange();
1464                 owner->view()->update(-3);
1465                 owner->view()->cursorPrevious();
1466                 owner->view()->text->FinishUndo();
1467                 moveCursorUpdate(false);
1468                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1469                 break;
1470                 
1471         case LFUN_NEXT:
1472                 if(!owner->view()->text->mark_set)
1473                         owner->view()->beforeChange();
1474                 owner->view()->update(-3);
1475                 owner->view()->cursorNext();
1476                 owner->view()->text->FinishUndo();
1477                 moveCursorUpdate(false);
1478                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1479                 break;
1480                 
1481         case LFUN_HOME:
1482                 if(!owner->view()->text->mark_set)
1483                         owner->view()->beforeChange();
1484                 owner->view()->update(-2);
1485                 owner->view()->text->CursorHome();
1486                 owner->view()->text->FinishUndo();
1487                 moveCursorUpdate(false);
1488                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1489                 break;
1490                 
1491         case LFUN_END:
1492                 if(!owner->view()->text->mark_set)
1493                         owner->view()->beforeChange();
1494                 owner->view()->update(-2);
1495                 owner->view()->text->CursorEnd();
1496                 owner->view()->text->FinishUndo();
1497                 moveCursorUpdate(false);
1498                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1499                 break;
1500                 
1501         case LFUN_SHIFT_TAB:
1502         case LFUN_TAB:
1503                 if(!owner->view()->text->mark_set)
1504                         owner->view()->beforeChange();
1505                 owner->view()->update(-2);
1506                 owner->view()->text->CursorTab();
1507                 owner->view()->text->FinishUndo();
1508                 moveCursorUpdate(false);
1509                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1510                 break;
1511                 
1512         case LFUN_WORDRIGHT:
1513                 if(!owner->view()->text->mark_set)
1514                         owner->view()->beforeChange();
1515                 owner->view()->update(-2);
1516                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1517                         owner->view()->text->CursorLeftOneWord();
1518                 else
1519                         owner->view()->text->CursorRightOneWord();
1520                 owner->view()->text->FinishUndo();
1521                 moveCursorUpdate(false);
1522                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1523                 break;
1524                 
1525         case LFUN_WORDLEFT:
1526                 if(!owner->view()->text->mark_set)
1527                         owner->view()->beforeChange();
1528                 owner->view()->update(-2);
1529                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1530                         owner->view()->text->CursorRightOneWord();
1531                 else
1532                         owner->view()->text->CursorLeftOneWord();
1533                 owner->view()->text->FinishUndo();
1534                 moveCursorUpdate(false);
1535                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1536                 break;
1537                 
1538         case LFUN_BEGINNINGBUF:
1539                 if(!owner->view()->text->mark_set)
1540                         owner->view()->beforeChange();
1541                 owner->view()->update(-2);
1542                 owner->view()->text->CursorTop();
1543                 owner->view()->text->FinishUndo();
1544                 moveCursorUpdate(false);
1545                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1546                 break;
1547                 
1548         case LFUN_ENDBUF:
1549                 if(!owner->view()->text->mark_set)
1550                         owner->view()->beforeChange();
1551                 owner->view()->update(-2);
1552                 owner->view()->text->CursorBottom();
1553                 owner->view()->text->FinishUndo();
1554                 moveCursorUpdate(false);
1555                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1556                 break;
1557
1558       
1559                 /* cursor selection ---------------------------- */
1560         case LFUN_RIGHTSEL:
1561                 owner->view()->update(-2);
1562                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1563                         owner->view()->text->CursorLeft();
1564                 else
1565                         owner->view()->text->CursorRight();
1566                 owner->view()->text->FinishUndo();
1567                 moveCursorUpdate(true);
1568                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1569                 break;
1570                 
1571         case LFUN_LEFTSEL:
1572                 owner->view()->update(-2);
1573                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1574                         owner->view()->text->CursorRight();
1575                 else
1576                         owner->view()->text->CursorLeft();
1577                 owner->view()->text->FinishUndo();
1578                 moveCursorUpdate(true);
1579                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1580                 break;
1581                 
1582         case LFUN_UPSEL:
1583                 owner->view()->update(-2);
1584                 owner->view()->text->CursorUp();
1585                 owner->view()->text->FinishUndo();
1586                 moveCursorUpdate(true);
1587                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1588                 break;
1589                 
1590         case LFUN_DOWNSEL:
1591                 owner->view()->update(-2);
1592                 owner->view()->text->CursorDown();
1593                 owner->view()->text->FinishUndo();
1594                 moveCursorUpdate(true);
1595                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1596                 break;
1597
1598         case LFUN_UP_PARAGRAPHSEL:
1599                 owner->view()->update(-2);
1600                 owner->view()->text->CursorUpParagraph();
1601                 owner->view()->text->FinishUndo();
1602                 moveCursorUpdate(true);
1603                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1604                 break;
1605                 
1606         case LFUN_DOWN_PARAGRAPHSEL:
1607                 owner->view()->update(-2);
1608                 owner->view()->text->CursorDownParagraph();
1609                 owner->view()->text->FinishUndo();
1610                 moveCursorUpdate(true);
1611                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1612                 break;
1613                 
1614         case LFUN_PRIORSEL:
1615                 owner->view()->update(-2);
1616                 owner->view()->cursorPrevious();
1617                 owner->view()->text->FinishUndo();
1618                 moveCursorUpdate(true);
1619                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1620                 break;
1621                 
1622         case LFUN_NEXTSEL:
1623                 owner->view()->update(-2);
1624                 owner->view()->cursorNext();
1625                 owner->view()->text->FinishUndo();
1626                 moveCursorUpdate(true);
1627                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1628                 break;
1629                 
1630         case LFUN_HOMESEL:
1631                 owner->view()->update(-2);
1632                 owner->view()->text->CursorHome();
1633                 owner->view()->text->FinishUndo();
1634                 moveCursorUpdate(true);
1635                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1636                 break;
1637                 
1638         case LFUN_ENDSEL:
1639                 owner->view()->update(-2);
1640                 owner->view()->text->CursorEnd();
1641                 owner->view()->text->FinishUndo();
1642                 moveCursorUpdate(true);
1643                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1644                 break;
1645                 
1646         case LFUN_WORDRIGHTSEL:
1647                 owner->view()->update(-2);
1648                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1649                         owner->view()->text->CursorLeftOneWord();
1650                 else
1651                         owner->view()->text->CursorRightOneWord();
1652                 owner->view()->text->FinishUndo();
1653                 moveCursorUpdate(true);
1654                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1655                 break;
1656                 
1657         case LFUN_WORDLEFTSEL:
1658                 owner->view()->update(-2);
1659                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1660                         owner->view()->text->CursorRightOneWord();
1661                 else
1662                         owner->view()->text->CursorLeftOneWord();
1663                 owner->view()->text->FinishUndo();
1664                 moveCursorUpdate(true);
1665                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1666                 break;
1667                 
1668         case LFUN_BEGINNINGBUFSEL:
1669                 owner->view()->update(-2);
1670                 owner->view()->text->CursorTop();
1671                 owner->view()->text->FinishUndo();
1672                 moveCursorUpdate(true);
1673                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1674                 break;
1675                 
1676         case LFUN_ENDBUFSEL:
1677                 owner->view()->update(-2);
1678                 owner->view()->text->CursorBottom();
1679                 owner->view()->text->FinishUndo();
1680                 moveCursorUpdate(true);
1681                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1682                 break;
1683
1684                 // --- text changing commands ------------------------
1685         case LFUN_BREAKLINE:
1686                 owner->view()->beforeChange();
1687                 owner->view()->text->InsertChar(LyXParagraph::META_NEWLINE);
1688                 owner->view()->update(1);
1689                 SetUpdateTimer(0.01);
1690                 moveCursorUpdate(false);
1691                 break;
1692                 
1693         case LFUN_PROTECTEDSPACE:
1694         {
1695                 LyXLayout const & style =
1696                         textclasslist.Style(owner->view()->buffer()->params.textclass,
1697                                             owner->view()->text->cursor.par->GetLayout());
1698
1699                 if (style.free_spacing) {
1700                         owner->view()->text->InsertChar(' ');
1701                         owner->view()->update(-1);
1702                 } else {
1703                         owner->view()->protectedBlank();
1704                 }
1705                 moveCursorUpdate(false);
1706         }
1707         break;
1708                 
1709         case LFUN_SETMARK:
1710                 if(owner->view()->text->mark_set) {
1711                         owner->view()->beforeChange();
1712                         owner->view()->update(0);
1713                         setMessage(N_("Mark removed"));
1714                 } else {
1715                         owner->view()->beforeChange();
1716                         owner->view()->text->mark_set = 1;
1717                         owner->view()->update(0);
1718                         setMessage(N_("Mark set"));
1719                 }
1720                 owner->view()->text->sel_cursor = 
1721                         owner->view()->text->cursor;
1722                 break;
1723                 
1724         case LFUN_DELETE:
1725                 FreeUpdateTimer();
1726                 if (!owner->view()->text->selection) {
1727                         owner->view()->text->Delete();
1728                         owner->view()->text->sel_cursor = 
1729                                 owner->view()->text->cursor;
1730                         owner->view()->update(1);
1731                         // It is possible to make it a lot faster still
1732                         // just comment out the lone below...
1733                         owner->view()->showCursor();
1734                 } else {
1735                         owner->view()->cut();
1736                 }
1737                 SetUpdateTimer();
1738                 moveCursorUpdate(false);
1739                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1740                 owner->view()->setState();
1741                 break;
1742
1743         case LFUN_DELETE_SKIP:
1744         {
1745                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
1746                 
1747                 LyXCursor cursor = owner->view()->text->cursor;
1748
1749                 FreeUpdateTimer();
1750                 if (!owner->view()->text->selection) {
1751                         if (cursor.pos == cursor.par->Last()) {
1752                                 owner->view()->text->CursorRight();
1753                                 cursor = owner->view()->text->cursor;
1754                                 if (cursor.pos == 0
1755                                     && !(cursor.par->added_space_top 
1756                                          == VSpace (VSpace::NONE))) {
1757                                         owner->view()->text->SetParagraph
1758                                                 (cursor.par->line_top,
1759                                                  cursor.par->line_bottom,
1760                                                  cursor.par->pagebreak_top, 
1761                                                  cursor.par->pagebreak_bottom,
1762                                                  VSpace(VSpace::NONE), 
1763                                                  cursor.par->added_space_bottom,
1764                                                  cursor.par->align, 
1765                                                  cursor.par->labelwidthstring, 0);
1766                                         owner->view()->text->CursorLeft();
1767                                         owner->view()->update (1);
1768                                 } else {
1769                                         owner->view()->text->CursorLeft();
1770                                         owner->view()->text->Delete();
1771                                         owner->view()->text->sel_cursor = 
1772                                                 owner->view()->text->cursor;
1773                                         owner->view()->update(1);
1774                                 }
1775                         } else {
1776                                 owner->view()->text->Delete();
1777                                 owner->view()->text->sel_cursor = 
1778                                         owner->view()->text->cursor;
1779                                 owner->view()->update(1);
1780                         }
1781                 } else {
1782                         owner->view()->cut();
1783                 }
1784                 SetUpdateTimer();
1785         }
1786         break;
1787
1788         /* -------> Delete word forward. */
1789         case LFUN_DELETE_WORD_FORWARD:
1790                 owner->view()->update(-2);
1791                 FreeUpdateTimer();
1792                 owner->view()->text->DeleteWordForward();
1793                 owner->view()->update( 1 );
1794                 SetUpdateTimer();
1795                 moveCursorUpdate(false);
1796                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1797                 break;
1798
1799                 /* -------> Delete word backward. */
1800         case LFUN_DELETE_WORD_BACKWARD:
1801                 owner->view()->update(-2);
1802                 FreeUpdateTimer();
1803                 owner->view()->text->DeleteWordBackward();
1804                 owner->view()->update( 1 );
1805                 SetUpdateTimer();
1806                 moveCursorUpdate(false);
1807                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1808                 break;
1809                 
1810                 /* -------> Kill to end of line. */
1811         case LFUN_DELETE_LINE_FORWARD:
1812                 FreeUpdateTimer();
1813                 owner->view()->update(-2);
1814                 owner->view()->text->DeleteLineForward();
1815                 owner->view()->update( 1 );
1816                 SetUpdateTimer();
1817                 moveCursorUpdate(false);
1818                 break;
1819                 
1820                 /* -------> Set mark off. */
1821         case LFUN_MARK_OFF:
1822                 owner->view()->beforeChange();
1823                 owner->view()->update(0);
1824                 owner->view()->text->sel_cursor = 
1825                         owner->view()->text->cursor;
1826                 setMessage(N_("Mark off"));
1827                 break;
1828
1829                 /* -------> Set mark on. */
1830         case LFUN_MARK_ON:
1831                 owner->view()->beforeChange();
1832                 owner->view()->text->mark_set = 1;
1833                 owner->view()->update( 0 );
1834                 owner->view()->text->sel_cursor = 
1835                         owner->view()->text->cursor;
1836                 setMessage(N_("Mark on"));
1837                 break;
1838                 
1839         case LFUN_BACKSPACE:
1840         {
1841                 FreeUpdateTimer();
1842                 if (!owner->view()->text->selection) {
1843                         if (owner->getIntl()->getTrans()->backspace()) {
1844                                 owner->view()->text->Backspace();
1845                                 owner->view()->text->sel_cursor = 
1846                                         owner->view()->text->cursor;
1847                                 owner->view()->update(1);
1848                                 // It is possible to make it a lot faster still
1849                                 // just comment out the lone below...
1850                                 owner->view()->showCursor();
1851                         }
1852                 } else {
1853                         owner->view()->cut();
1854                 }
1855                 SetUpdateTimer();
1856                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1857                 owner->view()->setState();
1858         }
1859         break;
1860
1861         case LFUN_BACKSPACE_SKIP:
1862         {
1863                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
1864                 
1865                 LyXCursor cursor = owner->view()->text->cursor;
1866                 
1867                 FreeUpdateTimer();
1868                 if (!owner->view()->text->selection) {
1869                         if (cursor.pos == 0 
1870                             && !(cursor.par->added_space_top 
1871                                  == VSpace (VSpace::NONE))) {
1872                                 owner->view()->text->SetParagraph 
1873                                         (cursor.par->line_top,      
1874                                          cursor.par->line_bottom,
1875                                          cursor.par->pagebreak_top, 
1876                                          cursor.par->pagebreak_bottom,
1877                                          VSpace(VSpace::NONE), cursor.par->added_space_bottom,
1878                                          cursor.par->align, 
1879                                          cursor.par->labelwidthstring, 0);
1880                                 owner->view()->update (1);
1881                         } else {
1882                                 owner->view()->text->Backspace();
1883                                 owner->view()->text->sel_cursor 
1884                                         = cursor;
1885                                 owner->view()->update(1);
1886                         }
1887                 } else
1888                         owner->view()->cut();
1889                 SetUpdateTimer();
1890         }
1891         break;
1892
1893         case LFUN_BREAKPARAGRAPH:
1894         {
1895                 owner->view()->beforeChange();
1896                 owner->view()->text->BreakParagraph(0);
1897                 owner->view()->update(1);
1898                 SetUpdateTimer(0.01);
1899                 owner->view()->text->sel_cursor = 
1900                         owner->view()->text->cursor;
1901                 owner->view()->setState();
1902                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1903                 break;
1904         }
1905
1906         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1907         {
1908                 owner->view()->beforeChange();
1909                 owner->view()->text->BreakParagraph(1);
1910                 owner->view()->update(1);
1911                 SetUpdateTimer(0.01);
1912                 owner->view()->text->sel_cursor = 
1913                         owner->view()->text->cursor;
1914                 owner->view()->setState();
1915                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1916                 break;
1917         }
1918         
1919         case LFUN_BREAKPARAGRAPH_SKIP:
1920         {
1921                 // When at the beginning of a paragraph, remove
1922                 // indentation and add a "defskip" at the top.
1923                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
1924                 
1925                 LyXCursor cursor = owner->view()->text->cursor;
1926                 
1927                 owner->view()->beforeChange();
1928                 if (cursor.pos == 0) {
1929                         if (cursor.par->added_space_top == VSpace(VSpace::NONE)) {
1930                                 owner->view()->text->SetParagraph
1931                                         (cursor.par->line_top,      
1932                                          cursor.par->line_bottom,
1933                                          cursor.par->pagebreak_top, 
1934                                          cursor.par->pagebreak_bottom,
1935                                          VSpace(VSpace::DEFSKIP), cursor.par->added_space_bottom,
1936                                          cursor.par->align, 
1937                                          cursor.par->labelwidthstring, 1);
1938                                 owner->view()->update(1);
1939                         } 
1940                 }
1941                 else {
1942                         owner->view()->text->BreakParagraph(0);
1943                         owner->view()->update(1);
1944                 }
1945                 SetUpdateTimer(0.01);
1946                 owner->view()->text->sel_cursor = cursor;
1947                 owner->view()->setState();
1948                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1949         }
1950         break;
1951
1952         case LFUN_PARAGRAPH_SPACING:
1953         {
1954                 LyXParagraph * par = owner->view()->text->cursor.par;
1955                 Spacing::Space cur_spacing = par->spacing.getSpace();
1956                 float cur_value = 1.0;
1957                 if (cur_spacing == Spacing::Other) {
1958                         cur_value = par->spacing.getValue();
1959                 }
1960                 
1961 #ifdef HAVE_SSTREAM
1962                 istringstream istr(argument);
1963 #else
1964                 istrstream istr(argument.c_str());
1965 #endif
1966                 string tmp;
1967                 istr >> tmp;
1968                 Spacing::Space new_spacing = cur_spacing;
1969                 float new_value = cur_value;
1970                 if (tmp.empty()) {
1971                         lyxerr << "Missing argument to `paragraph-spacing'"
1972                                << endl;
1973                 } else if (tmp == "single") {
1974                         new_spacing = Spacing::Single;
1975                 } else if (tmp == "onehalf") {
1976                         new_spacing = Spacing::Onehalf;
1977                 } else if (tmp == "double") {
1978                         new_spacing = Spacing::Double;
1979                 } else if (tmp == "other") {
1980                         new_spacing = Spacing::Other;
1981                         float tmpval = 0.0;
1982                         istr >> tmpval;
1983                         lyxerr << "new_value = " << tmpval << endl;
1984                         if (tmpval != 0.0)
1985                                 new_value = tmpval;
1986                 } else if (tmp == "default") {
1987                         new_spacing = Spacing::Default;
1988                 } else {
1989                         lyxerr << _("Unknown spacing argument: ")
1990                                << argument << endl;
1991                 }
1992                 if (cur_spacing != new_spacing || cur_value != new_value) {
1993                         par->spacing.set(new_spacing, new_value);
1994                         owner->view()->text->RedoParagraph();
1995                         owner->view()->update(-1);
1996                 }
1997         }
1998         break;
1999         
2000         case LFUN_QUOTE:
2001                 owner->view()->beforeChange();
2002                 owner->view()->text->InsertChar('\"');  // This " matches the single quote in the code
2003                 owner->view()->update(1);
2004                 SetUpdateTimer();
2005                 moveCursorUpdate(false);
2006                 break;
2007
2008         case LFUN_HTMLURL:
2009         case LFUN_URL:
2010         {
2011                 InsetCommand * new_inset;
2012                 if (action == LFUN_HTMLURL)
2013                         new_inset = new InsetUrl("htmlurl", "", "");
2014                 else
2015                         new_inset = new InsetUrl("url", "", "");
2016                 if (owner->view()->insertInset(new_inset))
2017                         new_inset->Edit(owner->view(), 0, 0, 0);
2018                 else
2019                         delete new_inset;
2020         }
2021         break;
2022         
2023         case LFUN_INSET_TEXT:
2024         {
2025                 InsetText * new_inset = new InsetText(owner->buffer());
2026                 if (owner->view()->insertInset(new_inset))
2027                         new_inset->Edit(owner->view(), 0, 0, 0);
2028                 else
2029                         delete new_inset;
2030         }
2031         break;
2032         case LFUN_INSET_ERT:
2033         {
2034                 InsetERT * new_inset = new InsetERT(owner->buffer());
2035                 if (owner->view()->insertInset(new_inset))
2036                         new_inset->Edit(owner->view(), 0, 0, 0);
2037                 else
2038                         delete new_inset;
2039         }
2040         break;
2041         
2042         case LFUN_INSET_FOOTNOTE:
2043         {
2044                 InsetFoot * new_inset = new InsetFoot(owner->buffer());
2045                 if (owner->view()->insertInset(new_inset))
2046                         new_inset->Edit(owner->view(), 0, 0, 0);
2047                 else
2048                         delete new_inset;
2049         }
2050         break;
2051
2052         case LFUN_INSET_TABULAR:
2053         {
2054                 int r = 2, c = 2;
2055                 if (!argument.empty())
2056                         sscanf(argument.c_str(),"%d%d",&r,&c);
2057                 InsetTabular * new_inset = new InsetTabular(owner->buffer(),r,c);
2058                 if (owner->view()->insertInset(new_inset))
2059                         new_inset->Edit(owner->view(), 0, 0, 0);
2060                 else
2061                         delete new_inset;
2062         }
2063         break;
2064
2065         // --- lyxserver commands ----------------------------
2066
2067         case LFUN_CHARATCURSOR:
2068         {
2069                 LyXParagraph::size_type pos = 
2070                         owner->view()->text->cursor.pos;
2071                 if(pos < owner->view()->text->cursor.par->size())
2072                         //dispatch_buffer = owner->view()->text->
2073                         //      cursor.par->text[pos];
2074                         dispatch_buffer =
2075                                 owner->view()->text->
2076                                 cursor.par->GetChar(pos);
2077                 else
2078                         dispatch_buffer = "EOF";
2079         }
2080         break;
2081         
2082         case LFUN_GETXY:
2083                 dispatch_buffer = 
2084                         tostr(owner->view()->text->cursor.x) + ' '
2085                         + tostr(owner->view()->text->cursor.y);
2086                 break;
2087                 
2088         case LFUN_SETXY:
2089         {
2090                 int  x;
2091                 long y;
2092                 sscanf(argument.c_str(), " %d %ld", &x, &y);
2093                 owner->view()->text->SetCursorFromCoordinates(x, y);
2094         }
2095         break;
2096         
2097         case LFUN_GETLAYOUT:
2098                 dispatch_buffer =  
2099                         tostr(owner->view()->text->cursor.par->layout);
2100                 break;
2101                         
2102         case LFUN_GETFONT:
2103         {
2104                 LyXFont & font = owner->view()->text->current_font;
2105                 if(font.shape() == LyXFont::ITALIC_SHAPE)
2106                         dispatch_buffer = 'E';
2107                 else if(font.shape() == LyXFont::SMALLCAPS_SHAPE)
2108                         dispatch_buffer = 'N';
2109                 else
2110                         dispatch_buffer = '0';
2111
2112         }
2113         break;
2114
2115         case LFUN_GETLATEX:
2116         {
2117                 LyXFont & font = owner->view()->text->current_font;
2118                 if(font.latex() == LyXFont::ON)
2119                         dispatch_buffer = 'L';
2120                 else
2121                         dispatch_buffer = '0';
2122         }
2123         break;
2124
2125         case LFUN_GETNAME:
2126                 setMessage(owner->buffer()->fileName());
2127                 lyxerr.debug() << "FNAME["
2128                                << owner->buffer()->fileName()
2129                                << "] " << endl;
2130                 break;
2131                 
2132         case LFUN_NOTIFY:
2133         {
2134                 string buf;
2135                 keyseq.print(buf);
2136                 dispatch_buffer = buf;
2137                 lyxserver->notifyClient(dispatch_buffer);
2138         }
2139         break;
2140
2141         case LFUN_GOTOFILEROW:
2142         {
2143                 char file_name[100];
2144                 int  row;
2145                 sscanf(argument.c_str(), " %s %d", file_name, &row);
2146
2147                 // Must replace extension of the file to be .lyx and get full path
2148                 string s = ChangeExtension(string(file_name), ".lyx");
2149
2150                 // Either change buffer or load the file
2151                 if (bufferlist.exists(s))
2152                         owner->view()->buffer(bufferlist.getBuffer(s));
2153                 else
2154                         owner->view()->buffer(bufferlist.loadLyXFile(s));
2155
2156                 // Set the cursor  
2157                 owner->view()->setCursorFromRow(row);
2158
2159                 // Recenter screen
2160                 owner->view()->center();
2161         }
2162         break;
2163
2164         case LFUN_APROPOS:
2165         case LFUN_GETTIP:
2166         {
2167                 int qa = lyxaction.LookupFunc(argument.c_str());
2168                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
2169         }
2170         break;
2171
2172         // --- accented characters ---------------------------
2173                 
2174         case LFUN_UMLAUT:
2175         case LFUN_CIRCUMFLEX:
2176         case LFUN_GRAVE:
2177         case LFUN_ACUTE:
2178         case LFUN_TILDE:
2179         case LFUN_CEDILLA:
2180         case LFUN_MACRON:
2181         case LFUN_DOT:
2182         case LFUN_UNDERDOT:
2183         case LFUN_UNDERBAR:
2184         case LFUN_CARON:
2185         case LFUN_SPECIAL_CARON:
2186         case LFUN_BREVE:
2187         case LFUN_TIE:
2188         case LFUN_HUNG_UMLAUT:
2189         case LFUN_CIRCLE:
2190         case LFUN_OGONEK:
2191         {
2192                 char c = 0;
2193                 
2194                 if (keyseq.length == -1 && keyseq.getiso() != 0) 
2195                         c = keyseq.getiso();
2196                 
2197                 owner->getIntl()->getTrans()->
2198                         deadkey(c, get_accent(action).accent, 
2199                                 owner->view()->text);
2200                 
2201                 // Need to reset, in case the minibuffer calls these
2202                 // actions
2203                 keyseq.reset();
2204                 keyseq.length = 0;
2205                 
2206                 // copied verbatim from do_accent_char
2207                 owner->view()->update(1);
2208
2209                 SetUpdateTimer();
2210                 owner->view()->text->sel_cursor = 
2211                         owner->view()->text->cursor;
2212         }   
2213         break;
2214         
2215         // --- toolbar ----------------------------------
2216         case LFUN_PUSH_TOOLBAR:
2217         {
2218                 int nth = strToInt(argument);
2219                 if (lyxerr.debugging(Debug::TOOLBAR)) {
2220                         lyxerr << "LFUN_PUSH_TOOLBAR: argument = `"
2221                                << argument << "'\n"
2222                                << "LFUN_PUSH_TOOLBAR: nth = `"
2223                                << nth << "'" << endl;
2224                 }
2225                 
2226                 if (nth <= 0) {
2227                         LyXBell();
2228                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
2229                 } else {
2230                         owner->getToolbar()->push(nth);
2231                 }
2232         }
2233         break;
2234         
2235         case LFUN_ADD_TO_TOOLBAR:
2236         {
2237                 if (lyxerr.debugging(Debug::TOOLBAR)) {
2238                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
2239                                 "argument = `" << argument << '\'' << endl;
2240                 }
2241                 string tmp(argument);
2242                 //lyxerr <<string("Argument: ") + argument);
2243                 //lyxerr <<string("Tmp     : ") + tmp);
2244                 if (tmp.empty()) {
2245                         LyXBell();
2246                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
2247                 } else {
2248                         owner->getToolbar()->add(argument, false);
2249                         owner->getToolbar()->set();
2250                 }
2251         }
2252         break;
2253         
2254         // --- insert characters ----------------------------------------
2255
2256         // ---  Mathed stuff. If we are here, there is no locked inset yet.
2257         
2258         // Greek mode     
2259         case LFUN_GREEK:
2260         {
2261                 if (!greek_kb_flag) {
2262                         greek_kb_flag = 1;
2263                         setMessage(N_("Math greek mode on"));
2264                 } else
2265                         greek_kb_flag = 0;
2266         }  
2267         break;
2268       
2269         // Greek keyboard      
2270         case LFUN_GREEK_TOGGLE:
2271         {
2272                 greek_kb_flag = greek_kb_flag ? 0 : 2;
2273                 if (greek_kb_flag) {
2274                         setMessage(N_("Math greek keyboard on"));
2275                 } else {
2276                         setMessage(N_("Math greek keyboard off"));
2277                 }
2278         }
2279         break;
2280         
2281         case LFUN_MATH_DELIM:     
2282         case LFUN_INSERT_MATRIX:
2283         {          
2284                 if (owner->view()->available()) { 
2285                         owner->view()->
2286                                 open_new_inset(new InsetFormula(false));
2287                         owner->view()
2288                                 ->the_locking_inset
2289                                 ->LocalDispatch(owner->view(),
2290                                                 action,
2291                                                 argument);
2292                 }
2293         }          
2294         break;
2295                
2296         case LFUN_INSERT_MATH:
2297         {
2298                 math_insert_symbol(argument.c_str());
2299         }
2300         break;
2301         
2302         case LFUN_MATH_DISPLAY:
2303         {
2304                 if (owner->view()->available())
2305                         owner->view()->open_new_inset(new InsetFormula(true));
2306                 break;
2307         }
2308                     
2309         case LFUN_MATH_MACRO:
2310         {
2311                 if (owner->view()->available()) {
2312                         string s(argument);
2313                         if (s.empty())
2314                                 setErrorMessage(N_("Missing argument"));
2315                         else {
2316                                 string s1 = token(s, ' ', 1);
2317                                 int na = s1.empty() ? 0: atoi(s1.c_str());
2318                                 owner->view()->
2319                                         open_new_inset(new InsetFormulaMacro(token(s, ' ', 0), na));
2320                         }
2321                 }
2322         }
2323         break;
2324
2325         case LFUN_MATH_MODE:   // Open or create a math inset
2326         {
2327                 
2328                 if (owner->view()->available())
2329                         owner->view()->open_new_inset(new InsetFormula);
2330                 setMessage(N_("Math editor mode"));
2331         }
2332         break;
2333           
2334         case LFUN_MATH_NUMBER:
2335         case LFUN_MATH_LIMITS:
2336         {
2337                 setErrorMessage(N_("This is only allowed in math mode!"));
2338         }
2339         break;
2340         
2341         case LFUN_INSERT_CITATION:
2342         {   
2343                 InsetCitation * new_inset = new InsetCitation();
2344                 // ale970405
2345                 // The note, if any, must be after the key, delimited
2346                 // by a | so both key and remark can have spaces.
2347                 if (!argument.empty()) {
2348                         string lsarg(argument);
2349                         if (contains(lsarg, "|")) {
2350                                 new_inset->setContents(token(lsarg, '|', 0));
2351                                 new_inset->setOptions(token(lsarg, '|', 1));
2352                         } else
2353                                 new_inset->setContents(lsarg);
2354                         if (!owner->view()->insertInset(new_inset))
2355                                 delete new_inset;
2356                 } else {
2357                         if (owner->view()->insertInset(new_inset))
2358                                 new_inset->Edit(owner->view(), 0, 0, 0);
2359                         else
2360                                 delete new_inset;
2361                 }
2362         }
2363         break;
2364                     
2365         case LFUN_INSERT_BIBTEX:
2366         {   
2367                 // ale970405+lasgoutt970425
2368                 // The argument can be up to two tokens separated 
2369                 // by a space. The first one is the bibstyle.
2370                 string lsarg(argument);
2371                 string bibstyle = token(lsarg, ' ', 1);
2372                 if (bibstyle.empty())
2373                         bibstyle = "plain";
2374                 InsetBibtex * new_inset 
2375                         = new InsetBibtex(token(lsarg, ' ', 0),
2376                                           bibstyle,
2377                                           owner->buffer());
2378                 
2379                 if (owner->view()->insertInset(new_inset)) {
2380                         if (lsarg.empty())
2381                                 new_inset->Edit(owner->view(), 0, 0, 0);
2382                 } else
2383                         delete new_inset;
2384         }
2385         break;
2386                 
2387         // BibTeX data bases
2388         case LFUN_BIBDB_ADD:
2389         {
2390                 InsetBibtex * inset = 
2391                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2392                 if (inset) {
2393                         inset->addDatabase(argument);
2394                 }
2395         }
2396         break;
2397                     
2398         case LFUN_BIBDB_DEL:
2399         {
2400                 InsetBibtex * inset = 
2401                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2402                 if (inset) {
2403                         inset->delDatabase(argument);
2404                 }
2405         }
2406         break;
2407         
2408         case LFUN_BIBTEX_STYLE:
2409         {
2410                 InsetBibtex * inset = 
2411                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2412                 if (inset) {
2413                         inset->setOptions(argument);
2414                 }
2415         }
2416         break;
2417                 
2418         case LFUN_INDEX_INSERT:
2419         case LFUN_INDEX_INSERT_LAST:
2420         {
2421                 // Can't do that at the beginning of a paragraph.
2422                 if (owner->view()->text->cursor.pos - 1 < 0)
2423                         break;
2424
2425                 InsetIndex * new_inset = new InsetIndex();
2426                 if (!argument.empty()) {
2427                         string lsarg(argument);
2428                         new_inset->setContents(lsarg);
2429                         if (!owner->view()->insertInset(new_inset))
2430                                 delete new_inset;
2431                 } else {
2432                         //reh 98/09/21
2433                         //get the current word for an argument
2434                         LyXParagraph::size_type lastpos = 
2435                                 owner->view()->text->cursor.pos - 1;
2436                         // Get the current word. note that this must be done
2437                         // before inserting the inset, or the inset will
2438                         // break the word
2439                         string curstring(owner->view()
2440                                          ->text->cursor.par->GetWord(lastpos));
2441
2442                         //make the new inset and write the current word into it
2443                         InsetIndex * new_inset = new InsetIndex();
2444
2445                         new_inset->setContents(curstring);
2446
2447                         //don't edit it if the call was to INSERT_LAST
2448                         if(action != LFUN_INDEX_INSERT_LAST) {
2449                                 new_inset->Edit(owner->view(), 0, 0, 0);
2450                         } else {
2451                                 //it looks blank on the screen unless
2452                                 //we do  something.  put it here.
2453
2454                                 // move the cursor to the returned value of lastpos
2455                                 // but only for the auto-insert
2456                                 owner->view()->text->cursor.pos = lastpos;
2457                         }
2458
2459                         //put the new inset into the buffer.
2460                         // there should be some way of knowing the user
2461                         //cancelled & avoiding this, but i don't know how
2462                         if (!owner->view()->insertInset(new_inset))
2463                                 delete new_inset;
2464                 }
2465         }
2466         break;
2467
2468         case LFUN_INDEX_PRINT:
2469         {
2470                 Inset * new_inset = new InsetPrintIndex(owner->buffer());
2471                 if (!owner->view()->insertInset(new_inset, "Standard", true))
2472                         delete new_inset;
2473         }
2474         break;
2475
2476         case LFUN_PARENTINSERT:
2477         {
2478                 lyxerr << "arg " << argument << endl;
2479                 Inset * new_inset = new InsetParent(argument, owner->buffer());
2480                 if (!owner->view()->insertInset(new_inset, "Standard", true))
2481                         delete new_inset;
2482         }
2483         break;
2484
2485         case LFUN_CHILDINSERT:
2486         {
2487                 Inset * new_inset = new InsetInclude(argument,
2488                                                      owner->buffer());
2489                 if (owner->view()->insertInset(new_inset, "Standard", true))
2490                         new_inset->Edit(owner->view(), 0, 0, 0);
2491                 else
2492                         delete new_inset;
2493         }
2494         break;
2495
2496         case LFUN_CHILDOPEN:
2497         {
2498                 string filename =
2499                         MakeAbsPath(argument, 
2500                                     OnlyPath(owner->buffer()->fileName()));
2501                 setMessage(N_("Opening child document ") +
2502                            MakeDisplayPath(filename) + "...");
2503                 owner->view()->savePosition();
2504                 if (bufferlist.exists(filename))
2505                         owner->view()->buffer(bufferlist.getBuffer(filename));
2506                 else
2507                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
2508         }
2509         break;
2510
2511         case LFUN_INSERT_NOTE:
2512                 owner->view()->insertNote();
2513                 break;
2514                 
2515         case LFUN_INSERTFOOTNOTE: 
2516         {
2517                 LyXParagraph::footnote_kind kind;
2518                 if (argument == "footnote")
2519                         { kind = LyXParagraph::FOOTNOTE; }
2520                 else if (argument == "margin")
2521                         { kind = LyXParagraph::MARGIN; }
2522                 else if (argument == "figure")
2523                         { kind = LyXParagraph::FIG; }
2524                 else if (argument == "table")
2525                         { kind = LyXParagraph::TAB; }
2526                 else if (argument == "wide-fig")
2527                         { kind = LyXParagraph::WIDE_FIG; }
2528                 else if (argument == "wide-tab")
2529                         { kind = LyXParagraph::WIDE_TAB; }
2530                 else if (argument == "algorithm")
2531                         { kind = LyXParagraph::ALGORITHM; }
2532                 else {
2533                         setErrorMessage(N_("Unknown kind of footnote"));
2534                         break;
2535                 }
2536                 owner->view()->text->InsertFootnoteEnvironment(kind);
2537                 owner->view()->update(1);
2538                 owner->view()->setState();
2539         }
2540         break;
2541         
2542         case LFUN_BUFFERBULLETSSELECT:
2543                 bulletForm();
2544                 break;
2545                 
2546         case LFUN_TOGGLECURSORFOLLOW:
2547                 cursor_follows_scrollbar = !cursor_follows_scrollbar;
2548                 break;
2549                 
2550         case LFUN_KMAP_OFF:             // keymap off
2551                 owner->getIntl()->KeyMapOn(false);
2552                 break;
2553                 
2554         case LFUN_KMAP_PRIM:    // primary keymap
2555                 owner->getIntl()->KeyMapPrim();
2556                 break;
2557                 
2558         case LFUN_KMAP_SEC:             // secondary keymap
2559                 owner->getIntl()->KeyMapSec();
2560                 break;
2561                 
2562         case LFUN_KMAP_TOGGLE:  // toggle keymap
2563                 owner->getIntl()->ToggleKeyMap();
2564                 break;
2565
2566         case LFUN_SELFINSERT:
2567         {
2568                 for (string::size_type i = 0; i < argument.length(); ++i) {
2569                         owner->view()->text->InsertChar(argument[i]);
2570                         // This needs to be in the loop, or else we
2571                         // won't break lines correctly. (Asger)
2572                         owner->view()->update(1);
2573                 }
2574                 SetUpdateTimer();
2575                 owner->view()->text->sel_cursor = 
2576                         owner->view()->text->cursor;
2577                 moveCursorUpdate(false);
2578         }
2579         break;
2580
2581         case LFUN_SEQUENCE: 
2582         {
2583                 // argument contains ';'-terminated commands
2584                 while (argument.find(';') != string::npos) {
2585                         string first;
2586                         argument = split(argument, first, ';');
2587                         Dispatch(first);
2588                 }
2589         }
2590         break;
2591
2592         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
2593         {
2594                 char datetmp[32];
2595                 int datetmp_len;
2596                 time_t now_time_t;
2597                 struct tm *now_tm;
2598                 static string arg;
2599                 
2600                 now_time_t = time(NULL);
2601                 now_tm = localtime(&now_time_t);
2602                 (void)setlocale(LC_TIME, "");
2603                 if (!argument.empty())
2604                         arg = argument;
2605                 else if (arg.empty())
2606                         arg = lyxrc.date_insert_format;
2607                 datetmp_len = (int) strftime(datetmp, 32, arg.c_str(), now_tm);
2608                 for (int i = 0; i < datetmp_len; i++) {
2609                         owner->view()->text->InsertChar(datetmp[i]);
2610                         owner->view()->update(1);
2611                 }
2612                 SetUpdateTimer();
2613                 owner->view()->text->sel_cursor = owner->view()->text->cursor;
2614                 moveCursorUpdate(false);
2615         }
2616         break;
2617
2618         case LFUN_SAVEPREFERENCES:
2619         {
2620                 Path p(user_lyxdir);
2621                 lyxrc.write("preferences");
2622         }
2623         break;
2624         
2625         case LFUN_UNKNOWN_ACTION:
2626         {
2627                 if(!owner->buffer()) {
2628                         LyXBell();
2629                         setErrorMessage(N_("No document open"));
2630                         break;
2631                 }
2632
2633                 if (owner->buffer()->isReadonly()) {
2634                         LyXBell();
2635                         setErrorMessage(N_("Document is read only"));
2636                         break;
2637                 }
2638                          
2639                 if (!argument.empty()) {
2640                         
2641                         /* Automatically delete the currently selected
2642                          * text and replace it with what is being
2643                          * typed in now. Depends on lyxrc settings
2644                          * "auto_region_delete", which defaults to
2645                          * true (on). */
2646                 
2647                         if ( lyxrc.auto_region_delete ) {
2648                                 if (owner->view()->text->selection){
2649                                         owner->view()->text->CutSelection(false);
2650                                         owner->view()->update(-1);
2651                                 }
2652                         }
2653                         
2654                         owner->view()->beforeChange();
2655                         
2656                         for (string::size_type i = 0;
2657                              i < argument.length(); ++i) {
2658                                 if (greek_kb_flag) {
2659                                         if (!math_insert_greek(argument[i]))
2660                                                 owner->getIntl()->getTrans()->TranslateAndInsert(argument[i], owner->view()->text);
2661                                 } else
2662                                         owner->getIntl()->getTrans()->TranslateAndInsert(argument[i], owner->view()->text);
2663                         }
2664
2665                         owner->view()->update(1);
2666                         SetUpdateTimer();
2667
2668                         owner->view()->text->sel_cursor = 
2669                                 owner->view()->text->cursor;
2670                         moveCursorUpdate(false);
2671                         return string();
2672                 } else {
2673                         // why is an "Unknown action" with empty
2674                         // argument even dispatched in the first
2675                         // place? I`ll probably change that. (Lgb)
2676                         LyXBell();
2677                         setErrorMessage(N_("Unknown action"));
2678                 }
2679                 break;
2680         default:
2681                 lyxerr << "A truly unknown func!" << endl;
2682                 break;
2683         }
2684         } // end of switch
2685   exit_with_message:
2686
2687         string res = getMessage();
2688
2689         if (res.empty()) {
2690                 if (!commandshortcut.empty()) {
2691                         string newbuf = owner->getMiniBuffer()->GetText();
2692                         if (newbuf != commandshortcut) {
2693                                 owner->getMiniBuffer()->Set(newbuf
2694                                                             + " " +
2695                                                             commandshortcut);
2696                         }
2697                 }
2698         } else {
2699                 owner->getMiniBuffer()->Set(string(_(res.c_str()))
2700                                             + " " + commandshortcut);
2701         }
2702
2703         return res;
2704 }
2705
2706
2707 void LyXFunc::setupLocalKeymap()
2708 {
2709         keyseq.stdmap = keyseq.curmap = toplevel_keymap;
2710         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap;
2711 }
2712
2713
2714 void LyXFunc::MenuNew(bool fromTemplate)
2715 {
2716         string fname, initpath = lyxrc.document_path;
2717         LyXFileDlg fileDlg;
2718
2719         if (owner->view()->available()) {
2720                 string trypath = owner->buffer()->filepath;
2721                 // If directory is writeable, use this as default.
2722                 if (IsDirWriteable(trypath) == 1)
2723                         initpath = trypath;
2724         }
2725
2726         ProhibitInput(owner->view());
2727         fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
2728         fileDlg.SetButton(1, _("Templates"), lyxrc.template_path);
2729         fname = fileDlg.Select(_("Enter Filename for new document"), 
2730                                initpath, "*.lyx", _("newfile"));
2731         AllowInput(owner->view());
2732         
2733         if (fname.empty()) {
2734                 owner->getMiniBuffer()->Set(_("Canceled."));
2735                 lyxerr.debug() << "New Document Cancelled." << endl;
2736                 return;
2737         }
2738         
2739         // get absolute path of file and make sure the filename ends
2740         // with .lyx
2741         string s = MakeAbsPath(fname);
2742         if (!IsLyXFilename(s))
2743                 s += ".lyx";
2744
2745         // Check if the document already is open
2746         if (bufferlist.exists(s)){
2747                 switch(AskConfirmation(_("Document is already open:"), 
2748                                        MakeDisplayPath(s, 50),
2749                                        _("Do you want to close that document now?\n"
2750                                          "('No' will just switch to the open version)")))
2751                         {
2752                         case 1: // Yes: close the document
2753                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
2754                                 // If close is canceled, we cancel here too.
2755                                         return;
2756                                 break;
2757                         case 2: // No: switch to the open document
2758                                 owner->view()->buffer(bufferlist.getBuffer(s));
2759                                 return;
2760                         case 3: // Cancel: Do nothing
2761                                 owner->getMiniBuffer()->Set(_("Canceled."));
2762                                 return;
2763                         }
2764         }
2765         
2766         // Check whether the file already exists
2767         if (IsLyXFilename(s)) {
2768                 FileInfo fi(s);
2769                 if (fi.readable() &&
2770                     AskQuestion(_("File already exists:"), 
2771                                 MakeDisplayPath(s, 50),
2772                                 _("Do you want to open the document?"))) {
2773                         // loads document
2774                         owner->getMiniBuffer()->Set(_("Opening document"), 
2775                                                     MakeDisplayPath(s), "...");
2776                         XFlush(fl_display);
2777                         owner->view()->buffer(
2778                                 bufferlist.loadLyXFile(s));
2779                         owner->getMiniBuffer()->Set(_("Document"),
2780                                                     MakeDisplayPath(s),
2781                                                     _("opened."));
2782                         return;
2783                 }
2784         }
2785
2786         // The template stuff
2787         string templname;
2788         if (fromTemplate) {
2789                 ProhibitInput(owner->view());
2790                 fname = fileDlg.Select(_("Choose template"),
2791                                        lyxrc.template_path,
2792                                        "*.lyx");
2793                 templname = fname;
2794                 AllowInput(owner->view());
2795         }
2796   
2797         // find a free buffer
2798         lyxerr.debug() << "Find a free buffer." << endl;
2799         owner->view()->buffer(bufferlist.newFile(s, templname));
2800 }
2801
2802
2803 void LyXFunc::MenuOpen()
2804 {
2805         string initpath = lyxrc.document_path;
2806         LyXFileDlg fileDlg;
2807   
2808         if (owner->view()->available()) {
2809                 string trypath = owner->buffer()->filepath;
2810                 // If directory is writeable, use this as default.
2811                 if (IsDirWriteable(trypath) == 1)
2812                         initpath = trypath;
2813         }
2814
2815         // launches dialog
2816         ProhibitInput(owner->view());
2817         fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
2818         fileDlg.SetButton(1, _("Examples"), 
2819                           AddPath(system_lyxdir, "examples"));
2820         string filename = fileDlg.Select(_("Select Document to Open"),
2821                                          initpath, "*.lyx");
2822         AllowInput(owner->view());
2823  
2824         // check selected filename
2825         if (filename.empty()) {
2826                 owner->getMiniBuffer()->Set(_("Canceled."));
2827                 return;
2828         }
2829
2830         // get absolute path of file and make sure the filename ends
2831         // with .lyx
2832         filename = MakeAbsPath(filename);
2833         if (!IsLyXFilename(filename))
2834                 filename += ".lyx";
2835
2836         // loads document
2837         owner->getMiniBuffer()->Set(_("Opening document"),
2838                                     MakeDisplayPath(filename), "...");
2839         Buffer * openbuf = bufferlist.loadLyXFile(filename);
2840         if (openbuf) {
2841                 owner->view()->buffer(openbuf);
2842                 owner->getMiniBuffer()->Set(_("Document"),
2843                                             MakeDisplayPath(filename),
2844                                             _("opened."));
2845         } else {
2846                 owner->getMiniBuffer()->Set(_("Could not open document"),
2847                                             MakeDisplayPath(filename));
2848         }
2849 }
2850
2851 // returns filename if file must be imported,
2852 // empty string if either file not found or already loaded
2853 // checks for running without gui are missing.
2854
2855 void LyXFunc::doImportHelper(
2856         string const & file,          // filename (possibly empty)
2857         string const & text,          // info when asking for filename
2858         string const & pattern,       // filetype
2859         bool func(BufferView *, string const &)     // the real import function
2860 )
2861 {
2862         string filename = file;
2863
2864         if (filename.empty()) { // need user interaction
2865                 string initpath = lyxrc.document_path;
2866                 LyXFileDlg fileDlg;
2867                 
2868                 if (owner->view()->available()) {
2869                         string trypath = owner->buffer()->filepath;
2870                         // If directory is writeable, use this as default.
2871                         if (IsDirWriteable(trypath) == 1)
2872                                 initpath = trypath;
2873                 }
2874
2875                 // launches dialog
2876                 ProhibitInput(owner->view());
2877                 fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
2878                 fileDlg.SetButton(1, _("Examples"), 
2879                                         AddPath(system_lyxdir, "examples"));
2880                 filename = fileDlg.Select(text, initpath, pattern);
2881                 AllowInput(owner->view());
2882  
2883                 // check selected filename
2884                 if (filename.empty()) 
2885                         owner->getMiniBuffer()->Set(_("Canceled."));
2886         }
2887
2888         // still no filename? abort
2889         if (filename.empty()) 
2890                 return;
2891
2892         // get absolute path of file
2893         filename = MakeAbsPath(filename);
2894
2895         string lyxfile = ChangeExtension(filename, ".lyx");
2896
2897         // Check if the document already is open
2898         if (bufferlist.exists(lyxfile)) {
2899                 switch(AskConfirmation(_("Document is already open:"), 
2900                                        MakeDisplayPath(lyxfile, 50),
2901                                        _("Do you want to close that document now?\n"
2902                                          "('No' will just switch to the open version)")))
2903                         {
2904                         case 1: // Yes: close the document
2905                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
2906                                 // If close is canceled, we cancel here too.
2907                                         return;
2908                                 break;
2909                         case 2: // No: switch to the open document
2910                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
2911                                 return;
2912                         case 3: // Cancel: Do nothing
2913                                 owner->getMiniBuffer()->Set(_("Canceled."));
2914                                 return;
2915                         }
2916         }
2917
2918         // Check if a LyX document by the same root exists in filesystem
2919         FileInfo f(lyxfile, true);
2920         if (f.exist() && !AskQuestion(_("A document by the name"), 
2921                                       MakeDisplayPath(lyxfile),
2922                                       _("already exists. Overwrite?"))) {
2923                 owner->getMiniBuffer()->Set(_("Canceled."));
2924                 return;
2925         }
2926         // filename should be valid now
2927
2928         // notify user of import ahead
2929         string displaypath = MakeDisplayPath(filename);
2930         owner->getMiniBuffer()->Set(_("Importing"), displaypath, "...");
2931
2932         // call real importer
2933         bool result = func(owner->view(), filename);
2934
2935         // we are done
2936         if (result)
2937                 owner->getMiniBuffer()->Set(displaypath, _("imported."));
2938         else
2939                 owner->getMiniBuffer()->Set(displaypath, _(": import failed."));
2940 }
2941
2942 static
2943 bool doImportASCIIasLines(BufferView * view, string const & filename)
2944 {
2945         view->buffer(bufferlist.newFile(filename, string()));
2946         InsertAsciiFile(view, filename, false);
2947         return true;
2948 }
2949
2950 static
2951 bool doImportASCIIasParagraphs(BufferView * view, string const & filename)
2952 {
2953         view->buffer(bufferlist.newFile(filename, string()));
2954         InsertAsciiFile(view, filename, true);
2955         return true;
2956 }
2957
2958 static
2959 bool doImportLaTeX(BufferView * view, string const & filename)
2960 {
2961         ImportLaTeX myImport(filename);
2962         Buffer * openbuf = myImport.run();
2963         if (openbuf) { 
2964                 view->buffer(openbuf);
2965                 return true;
2966         }
2967         else
2968                 return false;
2969 }
2970
2971 static
2972 bool doImportNoweb(BufferView * view, string const & filename)
2973 {
2974         ImportNoweb myImport(filename);
2975         Buffer * openbuf = myImport.run();
2976         if (openbuf) { 
2977                 view->buffer(openbuf);
2978                 return true;
2979         }
2980         else
2981                 return false;
2982 }
2983
2984 static
2985 bool doImportLinuxDoc(BufferView *, string const & filename)
2986 {
2987         // run sgml2lyx
2988         string tmp = lyxrc.linuxdoc_to_lyx_command + filename;
2989         Systemcalls one;
2990         Buffer * buf = 0;
2991
2992         int result = one.startscript(Systemcalls::System, tmp);
2993         if (result == 0) {
2994                 string filename = ChangeExtension(filename, ".lyx");
2995                 // File was generated without problems. Load it.
2996                 buf = bufferlist.loadLyXFile(filename);
2997         }
2998
2999         return result == 0;
3000 }
3001
3002
3003 void LyXFunc::MenuInsertLyXFile(string const & filen)
3004 {
3005         string filename = filen;
3006
3007         if (filename.empty()) {
3008                 // Launch a file browser
3009                 string initpath = lyxrc.document_path;
3010                 LyXFileDlg fileDlg;
3011
3012                 if (owner->view()->available()) {
3013                         string trypath = owner->buffer()->filepath;
3014                         // If directory is writeable, use this as default.
3015                         if (IsDirWriteable(trypath) == 1)
3016                                 initpath = trypath;
3017                 }
3018
3019                 // launches dialog
3020                 ProhibitInput(owner->view());
3021                 fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
3022                 fileDlg.SetButton(1, _("Examples"), 
3023                                   AddPath(system_lyxdir, "examples"));
3024                 filename = fileDlg.Select(_("Select Document to Insert"),
3025                                           initpath, "*.lyx");
3026                 AllowInput(owner->view());
3027
3028                 // check selected filename
3029                 if (filename.empty()) {
3030                         owner->getMiniBuffer()->Set(_("Canceled."));
3031                         return;
3032                 }
3033         } 
3034
3035         // get absolute path of file and make sure the filename ends
3036         // with .lyx
3037         filename = MakeAbsPath(filename);
3038         if (!IsLyXFilename(filename))
3039                 filename += ".lyx";
3040
3041         // Inserts document
3042         owner->getMiniBuffer()->Set(_("Inserting document"),
3043                                     MakeDisplayPath(filename), "...");
3044         bool res = owner->view()->insertLyXFile(filename);
3045         if (res) {
3046                 owner->getMiniBuffer()->Set(_("Document"),
3047                                             MakeDisplayPath(filename),
3048                                             _("inserted."));
3049         } else {
3050                 owner->getMiniBuffer()->Set(_("Could not insert document"),
3051                                             MakeDisplayPath(filename));
3052         }
3053 }
3054
3055 void LyXFunc::doImport(string const & argument)
3056 {
3057         string type;
3058         string filename = split(argument, type, ' ');
3059         lyxerr.debug() << "LyXFunc::doImport: " << type 
3060                        << " file: " << filename << endl;
3061
3062         if (type == "latex") 
3063                 doImportHelper(filename,
3064                                _("Select LaTeX file to import"), "*.tex", 
3065                                doImportLaTeX);
3066         else if (type == "ascii") 
3067                 doImportHelper(filename,
3068                                _("Select ASCII file to import"), "*.txt", 
3069                                doImportASCIIasLines);
3070         else if (type == "asciiparagraph") 
3071                 doImportHelper(filename,
3072                                _("Select ASCII file to import"), "*.txt", 
3073                                doImportASCIIasParagraphs);
3074         else if (type == "noweb") 
3075                 doImportHelper(filename,
3076                                _("Select NoWeb file to import"), "*.nw", 
3077                                doImportNoweb);
3078         else if (type == "linuxdoc") 
3079                 doImportHelper(filename,
3080                                _("Select LinuxDoc file to import"), "*.doc", 
3081                                doImportLinuxDoc);
3082         else 
3083                 setErrorMessage(string(N_("Unknown import type: ")) + type);
3084 }
3085
3086 void LyXFunc::reloadBuffer()
3087 {
3088         string fn = owner->buffer()->fileName();
3089         if (bufferlist.close(owner->buffer()))
3090                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
3091 }
3092
3093
3094 void LyXFunc::CloseBuffer()
3095 {
3096         if (bufferlist.close(owner->buffer()) && !quitting) {
3097                 if (bufferlist.empty()) {
3098                         // need this otherwise SEGV may occur while trying to
3099                         // set variables that don't exist
3100                         // since there's no current buffer
3101                         CloseAllBufferRelatedPopups();
3102                 }
3103                 else {
3104                         owner->view()->buffer(bufferlist.first());
3105                 }
3106         }
3107 }
3108
3109
3110 Inset * LyXFunc::getInsetByCode(Inset::Code code)
3111 {
3112         LyXCursor cursor = owner->view()->text->cursor;
3113         Buffer * buffer = owner->view()->buffer();
3114         for (Buffer::inset_iterator it = Buffer::inset_iterator(cursor.par,
3115                                                                 cursor.pos);
3116              it != buffer->inset_iterator_end(); ++it) {
3117                 if ((*it)->LyxCode() == code)
3118                         return *it;
3119         }
3120         return 0;
3121 }
3122
3123
3124 // Each "owner" should have it's own message method. lyxview and
3125 // the minibuffer would use the minibuffer, but lyxserver would
3126 // send an ERROR signal to its client.  Alejandro 970603
3127 // This func is bit problematic when it comes to NLS, to make the
3128 // lyx servers client be language indepenent we must not translate
3129 // strings sent to this func.
3130 void LyXFunc::setErrorMessage(string const & m) const
3131 {
3132         dispatch_buffer = m;
3133         errorstat = true;
3134 }
3135
3136
3137 void LyXFunc::setMessage(string const & m)
3138 {
3139         dispatch_buffer = m;
3140 }