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