]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
tex2lyx: support for Spreadsheet and chess external templates
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyX.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "SpellChecker.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "WordLangTuple.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/Selection.h"
53
54 #include "insets/InsetCollapsable.h"
55 #include "insets/InsetCommand.h"
56 #include "insets/InsetExternal.h"
57 #include "insets/InsetFloat.h"
58 #include "insets/InsetFloatList.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetGraphicsParams.h"
61 #include "insets/InsetNewline.h"
62 #include "insets/InsetQuotes.h"
63 #include "insets/InsetSpecialChar.h"
64 #include "insets/InsetText.h"
65 #include "insets/InsetWrap.h"
66
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxtime.h"
73 #include "support/os.h"
74
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MathMacroTemplate.h"
77
78 #include <boost/next_prior.hpp>
79
80 #include <clocale>
81 #include <sstream>
82
83 using namespace std;
84 using namespace lyx::support;
85
86 namespace lyx {
87
88 using cap::copySelection;
89 using cap::cutSelection;
90 using cap::pasteFromStack;
91 using cap::pasteClipboardText;
92 using cap::pasteClipboardGraphics;
93 using cap::replaceSelection;
94 using cap::grabAndEraseSelection;
95 using cap::selClearOrDel;
96 using cap::pasteSimpleText;
97
98 // globals...
99 static Font freefont(ignore_font, ignore_language);
100 static bool toggleall = false;
101
102 static void toggleAndShow(Cursor & cur, Text * text,
103         Font const & font, bool toggleall = true)
104 {
105         text->toggleFree(cur, font, toggleall);
106
107         if (font.language() != ignore_language ||
108             font.fontInfo().number() != FONT_IGNORE) {
109                 TextMetrics const & tm = cur.bv().textMetrics(text);
110                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
111                                                        cur.real_current_font))
112                         text->setCursor(cur, cur.pit(), cur.pos(),
113                                         false, !cur.boundary());
114         }
115 }
116
117
118 static void moveCursor(Cursor & cur, bool selecting)
119 {
120         if (selecting || cur.mark())
121                 cur.setSelection();
122 }
123
124
125 static void finishChange(Cursor & cur, bool selecting)
126 {
127         cur.finishUndo();
128         moveCursor(cur, selecting);
129 }
130
131
132 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
133 {
134         cur.recordUndo();
135         docstring sel = cur.selectionAsString(false);
136
137         // It may happen that sel is empty but there is a selection
138         replaceSelection(cur);
139
140         // Is this a valid formula?
141         bool valid = true;
142
143         if (sel.empty()) {
144 #ifdef ENABLE_ASSERTIONS
145                 const int old_pos = cur.pos();
146 #endif
147                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
148 #ifdef ENABLE_ASSERTIONS
149                 LASSERT(old_pos == cur.pos(), /**/);
150 #endif
151                 cur.nextInset()->edit(cur, true);
152                 // don't do that also for LFUN_MATH_MODE
153                 // unless you want end up with always changing
154                 // to mathrm when opening an inlined inset --
155                 // I really hate "LyXfunc overloading"...
156                 if (display)
157                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
158                 // Avoid an unnecessary undo step if cmd.argument
159                 // is empty
160                 if (!cmd.argument().empty())
161                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
162                                                  cmd.argument()));
163         } else {
164                 // create a macro if we see "\\newcommand"
165                 // somewhere, and an ordinary formula
166                 // otherwise
167                 if (sel.find(from_ascii("\\newcommand")) == string::npos
168                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
169                                 && sel.find(from_ascii("\\def")) == string::npos)
170                 {
171                         InsetMathHull * formula = new InsetMathHull(cur.buffer());
172                         string const selstr = to_utf8(sel);
173                         istringstream is(selstr);
174                         Lexer lex;
175                         lex.setStream(is);
176                         if (!formula->readQuiet(lex)) {
177                                 // No valid formula, let's try with delims
178                                 is.str("$" + selstr + "$");
179                                 lex.setStream(is);
180                                 if (!formula->readQuiet(lex)) {
181                                         // Still not valid, leave it as is
182                                         valid = false;
183                                         delete formula;
184                                         cur.insert(sel);
185                                 } else
186                                         cur.insert(formula);
187                         } else
188                                 cur.insert(formula);
189                 } else {
190                         cur.insert(new MathMacroTemplate(cur.buffer(), sel));
191                 }
192         }
193         if (valid)
194                 cur.message(from_utf8(N_("Math editor mode")));
195         else
196                 cur.message(from_utf8(N_("No valid math formula")));
197 }
198
199
200 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
201 {
202         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
203         if (cur.inRegexped()) {
204                 cur.message(_("Already in regular expression mode"));
205                 return;
206         }
207         cur.recordUndo();
208         docstring sel = cur.selectionAsString(false);
209
210         // It may happen that sel is empty but there is a selection
211         replaceSelection(cur);
212
213         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
214         cur.nextInset()->edit(cur, true);
215         cur.niceInsert(sel);
216
217         cur.message(_("Regexp editor mode"));
218 }
219
220
221 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
222 {
223         cur.recordUndo();
224         cap::replaceSelection(cur);
225         cur.insert(new InsetSpecialChar(kind));
226         cur.posForward();
227 }
228
229
230 static bool doInsertInset(Cursor & cur, Text * text,
231         FuncRequest const & cmd, bool edit, bool pastesel)
232 {
233         Buffer & buffer = cur.bv().buffer();
234         BufferParams const & bparams = buffer.params();
235         Inset * inset = createInset(&buffer, cmd);
236         if (!inset)
237                 return false;
238
239         if (InsetCollapsable * ci = inset->asInsetCollapsable())
240                 ci->setButtonLabel();
241
242         cur.recordUndo();
243         if (cmd.action() == LFUN_INDEX_INSERT) {
244                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
245                 text->insertInset(cur, inset);
246                 if (edit)
247                         inset->edit(cur, true);
248                 // Now put this into inset
249                 Font const f(inherit_font, cur.current_font.language());
250                 if (!ds.empty()) {
251                         cur.text()->insertStringAsLines(cur, ds, f);
252                         cur.leaveInset(*inset);
253                 }
254                 return true;
255         }
256
257         bool gotsel = false;
258         if (cur.selection()) {
259                 cutSelection(cur, false, pastesel);
260                 cur.clearSelection();
261                 gotsel = true;
262         }
263         text->insertInset(cur, inset);
264
265         if (edit)
266                 inset->edit(cur, true);
267
268         if (!gotsel || !pastesel)
269                 return true;
270
271         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
272         cur.buffer()->errors("Paste");
273         cur.clearSelection(); // bug 393
274         cur.finishUndo();
275         InsetText * inset_text = inset->asInsetText();
276         if (inset_text) {
277                 inset_text->fixParagraphsFont();
278                 if (!inset_text->allowMultiPar() || cur.lastpit() == 0) {
279                         // reset first par to default
280                         cur.text()->paragraphs().begin()
281                                 ->setPlainOrDefaultLayout(bparams.documentClass());
282                         cur.pos() = 0;
283                         cur.pit() = 0;
284                         // Merge multiple paragraphs -- hack
285                         while (cur.lastpit() > 0)
286                                 mergeParagraph(bparams, cur.text()->paragraphs(), 0);
287                         cur.leaveInset(*inset);
288                 }
289         } else {
290                 cur.leaveInset(*inset);
291                 // reset surrounding par to default
292                 DocumentClass const & dc = bparams.documentClass();
293                 docstring const layoutname = inset->usePlainLayout()
294                         ? dc.plainLayoutName()
295                         : dc.defaultLayoutName();
296                 text->setLayout(cur, layoutname);
297         }
298         return true;
299 }
300
301
302 string const freefont2string()
303 {
304         return freefont.toString(toggleall);
305 }
306
307
308 /// the type of outline operation
309 enum OutlineOp {
310         OutlineUp, // Move this header with text down
311         OutlineDown,   // Move this header with text up
312         OutlineIn, // Make this header deeper
313         OutlineOut // Make this header shallower
314 };
315
316
317 static void outline(OutlineOp mode, Cursor & cur)
318 {
319         Buffer & buf = *cur.buffer();
320         pit_type & pit = cur.pit();
321         ParagraphList & pars = buf.text().paragraphs();
322         ParagraphList::iterator const bgn = pars.begin();
323         // The first paragraph of the area to be copied:
324         ParagraphList::iterator start = boost::next(bgn, pit);
325         // The final paragraph of area to be copied:
326         ParagraphList::iterator finish = start;
327         ParagraphList::iterator const end = pars.end();
328
329         DocumentClass const & tc = buf.params().documentClass();
330
331         int const thistoclevel = start->layout().toclevel;
332         int toclevel;
333
334         // Move out (down) from this section header
335         if (finish != end)
336                 ++finish;
337
338         // Seek the one (on same level) below
339         for (; finish != end; ++finish) {
340                 toclevel = finish->layout().toclevel;
341                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
342                         break;
343         }
344
345         switch (mode) {
346                 case OutlineUp: {
347                         if (start == pars.begin())
348                                 // Nothing to move.
349                                 return;
350                         ParagraphList::iterator dest = start;
351                         // Move out (up) from this header
352                         if (dest == bgn)
353                                 return;
354                         // Search previous same-level header above
355                         do {
356                                 --dest;
357                                 toclevel = dest->layout().toclevel;
358                         } while(dest != bgn
359                                 && (toclevel == Layout::NOT_IN_TOC
360                                     || toclevel > thistoclevel));
361                         // Not found; do nothing
362                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
363                                 return;
364                         pit_type const newpit = distance(bgn, dest);
365                         pit_type const len = distance(start, finish);
366                         pit_type const deletepit = pit + len;
367                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
368                         pars.splice(dest, start, finish);
369                         cur.pit() = newpit;
370                         break;
371                 }
372                 case OutlineDown: {
373                         if (finish == end)
374                                 // Nothing to move.
375                                 return;
376                         // Go one down from *this* header:
377                         ParagraphList::iterator dest = boost::next(finish, 1);
378                         // Go further down to find header to insert in front of:
379                         for (; dest != end; ++dest) {
380                                 toclevel = dest->layout().toclevel;
381                                 if (toclevel != Layout::NOT_IN_TOC
382                                       && toclevel <= thistoclevel)
383                                         break;
384                         }
385                         // One such was found:
386                         pit_type newpit = distance(bgn, dest);
387                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
388                         pit_type const len = distance(start, finish);
389                         pars.splice(dest, start, finish);
390                         cur.pit() = newpit - len;
391                         break;
392                 }
393                 case OutlineIn: {
394                         pit_type const len = distance(start, finish);
395                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
396                         for (; start != finish; ++start) {
397                                 toclevel = start->layout().toclevel;
398                                 if (toclevel == Layout::NOT_IN_TOC)
399                                         continue;
400                                 DocumentClass::const_iterator lit = tc.begin();
401                                 DocumentClass::const_iterator len = tc.end();
402                                 for (; lit != len; ++lit) {
403                                         if (lit->toclevel == toclevel + 1 &&
404                                             start->layout().labeltype == lit->labeltype) {
405                                                 start->setLayout(*lit);
406                                                 break;
407                                         }
408                                 }
409                         }
410                         break;
411                 }
412                 case OutlineOut: {
413                         pit_type const len = distance(start, finish);
414                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
415                         for (; start != finish; ++start) {
416                                 toclevel = start->layout().toclevel;
417                                 if (toclevel == Layout::NOT_IN_TOC)
418                                         continue;
419                                 DocumentClass::const_iterator lit = tc.begin();
420                                 DocumentClass::const_iterator len = tc.end();
421                                 for (; lit != len; ++lit) {
422                                         if (lit->toclevel == toclevel - 1 &&
423                                                 start->layout().labeltype == lit->labeltype) {
424                                                         start->setLayout(*lit);
425                                                         break;
426                                         }
427                                 }
428                         }
429                         break;
430                 }
431         }
432 }
433
434
435 void Text::number(Cursor & cur)
436 {
437         FontInfo font = ignore_font;
438         font.setNumber(FONT_TOGGLE);
439         toggleAndShow(cur, this, Font(font, ignore_language));
440 }
441
442
443 bool Text::isRTL(Paragraph const & par) const
444 {
445         Buffer const & buffer = owner_->buffer();
446         return par.isRTL(buffer.params());
447 }
448
449
450 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
451 {
452         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
453
454         // Dispatch if the cursor is inside the text. It is not the
455         // case for context menus (bug 5797).
456         if (cur.text() != this) {
457                 cur.undispatched();
458                 return;
459         }
460
461         BufferView * bv = &cur.bv();
462         TextMetrics * tm = &bv->textMetrics(this);
463         if (!tm->contains(cur.pit())) {
464                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
465                 tm = &bv->textMetrics(this);
466         }
467
468         // FIXME: We use the update flag to indicates wether a singlePar or a
469         // full screen update is needed. We reset it here but shall we restore it
470         // at the end?
471         cur.noScreenUpdate();
472
473         LASSERT(cur.text() == this, /**/);
474         CursorSlice const oldTopSlice = cur.top();
475         bool const oldBoundary = cur.boundary();
476         bool const oldSelection = cur.selection();
477         // Signals that, even if needsUpdate == false, an update of the
478         // cursor paragraph is required
479         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
480                 LyXAction::SingleParUpdate);
481         // Signals that a full-screen update is required
482         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
483                 LyXAction::NoUpdate) || singleParUpdate);
484         bool const last_misspelled = lyxrc.spellcheck_continuously
485                 && cur.paragraph().isMisspelled(cur.pos(), true);
486         
487         FuncCode const act = cmd.action();
488         switch (act) {
489
490         case LFUN_PARAGRAPH_MOVE_DOWN: {
491                 pit_type const pit = cur.pit();
492                 recUndo(cur, pit, pit + 1);
493                 cur.finishUndo();
494                 pars_.swap(pit, pit + 1);
495                 needsUpdate = true;
496                 cur.forceBufferUpdate();
497                 ++cur.pit();
498                 break;
499         }
500
501         case LFUN_PARAGRAPH_MOVE_UP: {
502                 pit_type const pit = cur.pit();
503                 recUndo(cur, pit - 1, pit);
504                 cur.finishUndo();
505                 pars_.swap(pit, pit - 1);
506                 --cur.pit();
507                 needsUpdate = true;
508                 cur.forceBufferUpdate();
509                 break;
510         }
511
512         case LFUN_APPENDIX: {
513                 Paragraph & par = cur.paragraph();
514                 bool start = !par.params().startOfAppendix();
515
516 // FIXME: The code below only makes sense at top level.
517 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
518                 // ensure that we have only one start_of_appendix in this document
519                 // FIXME: this don't work for multipart document!
520                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
521                         if (pars_[tmp].params().startOfAppendix()) {
522                                 recUndo(cur, tmp);
523                                 pars_[tmp].params().startOfAppendix(false);
524                                 break;
525                         }
526                 }
527
528                 cur.recordUndo();
529                 par.params().startOfAppendix(start);
530
531                 // we can set the refreshing parameters now
532                 cur.forceBufferUpdate();
533                 break;
534         }
535
536         case LFUN_WORD_DELETE_FORWARD:
537                 if (cur.selection())
538                         cutSelection(cur, true, false);
539                 else
540                         deleteWordForward(cur);
541                 finishChange(cur, false);
542                 break;
543
544         case LFUN_WORD_DELETE_BACKWARD:
545                 if (cur.selection())
546                         cutSelection(cur, true, false);
547                 else
548                         deleteWordBackward(cur);
549                 finishChange(cur, false);
550                 break;
551
552         case LFUN_LINE_DELETE:
553                 if (cur.selection())
554                         cutSelection(cur, true, false);
555                 else
556                         tm->deleteLineForward(cur);
557                 finishChange(cur, false);
558                 break;
559
560         case LFUN_BUFFER_BEGIN:
561         case LFUN_BUFFER_BEGIN_SELECT:
562                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
563                 if (cur.depth() == 1)
564                         needsUpdate |= cursorTop(cur);
565                 else
566                         cur.undispatched();
567                 cur.screenUpdateFlags(Update::FitCursor);
568                 break;
569
570         case LFUN_BUFFER_END:
571         case LFUN_BUFFER_END_SELECT:
572                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
573                 if (cur.depth() == 1)
574                         needsUpdate |= cursorBottom(cur);
575                 else
576                         cur.undispatched();
577                 cur.screenUpdateFlags(Update::FitCursor);
578                 break;
579
580         case LFUN_INSET_BEGIN:
581         case LFUN_INSET_BEGIN_SELECT:
582                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
583                 if (cur.depth() == 1 || !cur.top().at_begin())
584                         needsUpdate |= cursorTop(cur);
585                 else
586                         cur.undispatched();
587                 cur.screenUpdateFlags(Update::FitCursor);
588                 break;
589
590         case LFUN_INSET_END:
591         case LFUN_INSET_END_SELECT:
592                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
593                 if (cur.depth() == 1 || !cur.top().at_end())
594                         needsUpdate |= cursorBottom(cur);
595                 else
596                         cur.undispatched();
597                 cur.screenUpdateFlags(Update::FitCursor);
598                 break;
599
600         case LFUN_INSET_SELECT_ALL:
601                 if (cur.depth() == 1 || !cur.selection() || !cur.selBegin().at_begin()
602                           || !cur.selEnd().at_end()) {
603                         needsUpdate |= cur.selHandle(false);
604                         needsUpdate |= cursorTop(cur);
605                         needsUpdate |= cur.selHandle(true);
606                         needsUpdate |= cursorBottom(cur);
607                 } else 
608                         cur.undispatched();
609                 cur.screenUpdateFlags(Update::FitCursor);
610                 break;
611
612         case LFUN_CHAR_FORWARD:
613         case LFUN_CHAR_FORWARD_SELECT:
614                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
615                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
616                 needsUpdate |= cursorForward(cur);
617
618                 if (!needsUpdate && oldTopSlice == cur.top()
619                                 && cur.boundary() == oldBoundary) {
620                         cur.undispatched();
621                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
622                 
623                         // we will probably be moving out the inset, so we should execute
624                         // the depm-mechanism, but only when the cursor has a place to 
625                         // go outside this inset, i.e. in a slice above.
626                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
627                                   && cur.pit() == cur.lastpit()) {
628                                 // The cursor hasn't changed yet. To give the 
629                                 // DEPM the possibility of doing something we must
630                                 // provide it with two different cursors.
631                                 Cursor dummy = cur;
632                                 dummy.pos() = dummy.pit() = 0;
633                                 if (cur.bv().checkDepm(dummy, cur))
634                                         cur.forceBufferUpdate();
635                         }
636                 }
637                 break;
638
639         case LFUN_CHAR_BACKWARD:
640         case LFUN_CHAR_BACKWARD_SELECT:
641                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
642                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
643                 needsUpdate |= cursorBackward(cur);
644
645                 if (!needsUpdate && oldTopSlice == cur.top()
646                         && cur.boundary() == oldBoundary) {
647                         cur.undispatched();
648                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
649
650                         // we will probably be moving out the inset, so we should execute
651                         // the depm-mechanism, but only when the cursor has a place to 
652                         // go outside this inset, i.e. in a slice above.
653                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
654                                 // The cursor hasn't changed yet. To give the 
655                                 // DEPM the possibility of doing something we must
656                                 // provide it with two different cursors.
657                                 Cursor dummy = cur;
658                                 dummy.pos() = cur.lastpos();
659                                 dummy.pit() = cur.lastpit();
660                                 if (cur.bv().checkDepm(dummy, cur))
661                                         cur.forceBufferUpdate();
662                         }
663                 }
664                 break;
665
666         case LFUN_CHAR_LEFT:
667         case LFUN_CHAR_LEFT_SELECT:
668                 if (lyxrc.visual_cursor) {
669                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
670                         needsUpdate |= cursorVisLeft(cur);
671                         if (!needsUpdate && oldTopSlice == cur.top()
672                                         && cur.boundary() == oldBoundary) {
673                                 cur.undispatched();
674                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
675                         }
676                 } else {
677                         if (reverseDirectionNeeded(cur)) {
678                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
679                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
680                         } else {
681                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
682                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
683                         }
684                         dispatch(cur, cmd);
685                         return;
686                 }
687                 break;
688
689         case LFUN_CHAR_RIGHT:
690         case LFUN_CHAR_RIGHT_SELECT:
691                 if (lyxrc.visual_cursor) {
692                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
693                         needsUpdate |= cursorVisRight(cur);
694                         if (!needsUpdate && oldTopSlice == cur.top()
695                                         && cur.boundary() == oldBoundary) {
696                                 cur.undispatched();
697                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
698                         }
699                 } else {
700                         if (reverseDirectionNeeded(cur)) {
701                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
702                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
703                         } else {
704                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
705                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
706                         }
707                         dispatch(cur, cmd);
708                         return;
709                 }
710                 break;
711
712
713         case LFUN_UP_SELECT:
714         case LFUN_DOWN_SELECT:
715         case LFUN_UP:
716         case LFUN_DOWN: {
717                 // stop/start the selection
718                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
719                         cmd.action() == LFUN_UP_SELECT;
720
721                 // move cursor up/down
722                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
723                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
724
725                 if (!atFirstOrLastRow) {
726                         needsUpdate |= cur.selHandle(select);   
727                         cur.selHandle(select);
728                         cur.upDownInText(up, needsUpdate);
729                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
730                 } else {
731                         // if the cursor cannot be moved up or down do not remove
732                         // the selection right now, but wait for the next dispatch.
733                         if (select)
734                                 needsUpdate |= cur.selHandle(select);   
735                         cur.upDownInText(up, needsUpdate);
736                         cur.undispatched();
737                 }
738
739                 break;
740         }
741
742         case LFUN_PARAGRAPH_UP:
743         case LFUN_PARAGRAPH_UP_SELECT:
744                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
745                 needsUpdate |= cursorUpParagraph(cur);
746                 break;
747
748         case LFUN_PARAGRAPH_DOWN:
749         case LFUN_PARAGRAPH_DOWN_SELECT:
750                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
751                 needsUpdate |= cursorDownParagraph(cur);
752                 break;
753
754         case LFUN_LINE_BEGIN:
755         case LFUN_LINE_BEGIN_SELECT:
756                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
757                 needsUpdate |= tm->cursorHome(cur);
758                 break;
759
760         case LFUN_LINE_END:
761         case LFUN_LINE_END_SELECT:
762                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
763                 needsUpdate |= tm->cursorEnd(cur);
764                 break;
765
766         case LFUN_SECTION_SELECT: {
767                 Buffer const & buf = *cur.buffer();
768                 pit_type const pit = cur.pit();
769                 ParagraphList & pars = buf.text().paragraphs();
770                 ParagraphList::iterator bgn = pars.begin();
771                 // The first paragraph of the area to be selected:
772                 ParagraphList::iterator start = boost::next(bgn, pit);
773                 // The final paragraph of area to be selected:
774                 ParagraphList::iterator finish = start;
775                 ParagraphList::iterator end = pars.end();
776
777                 int const thistoclevel = start->layout().toclevel;
778                 if (thistoclevel == Layout::NOT_IN_TOC)
779                         break;
780
781                 cur.pos() = 0;
782                 Cursor const old_cur = cur;
783                 needsUpdate |= cur.selHandle(true);
784
785                 // Move out (down) from this section header
786                 if (finish != end)
787                         ++finish;
788
789                 // Seek the one (on same level) below
790                 for (; finish != end; ++finish, ++cur.pit()) {
791                         int const toclevel = finish->layout().toclevel;
792                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
793                                 break;
794                 }
795                 cur.pos() = cur.lastpos();
796                 
797                 needsUpdate |= cur != old_cur;
798                 break;
799         }
800
801         case LFUN_WORD_RIGHT:
802         case LFUN_WORD_RIGHT_SELECT:
803                 if (lyxrc.visual_cursor) {
804                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
805                         needsUpdate |= cursorVisRightOneWord(cur);
806                         if (!needsUpdate && oldTopSlice == cur.top()
807                                         && cur.boundary() == oldBoundary) {
808                                 cur.undispatched();
809                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
810                         }
811                 } else {
812                         if (reverseDirectionNeeded(cur)) {
813                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
814                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
815                         } else {
816                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
817                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
818                         }
819                         dispatch(cur, cmd);
820                         return;
821                 }
822                 break;
823
824         case LFUN_WORD_FORWARD:
825         case LFUN_WORD_FORWARD_SELECT:
826                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
827                 needsUpdate |= cursorForwardOneWord(cur);
828
829                 if (!needsUpdate && oldTopSlice == cur.top()
830                                 && cur.boundary() == oldBoundary) {
831                         cur.undispatched();
832                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
833                 
834                         // we will probably be moving out the inset, so we should execute
835                         // the depm-mechanism, but only when the cursor has a place to 
836                         // go outside this inset, i.e. in a slice above.
837                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
838                                   && cur.pit() == cur.lastpit()) {
839                                 // The cursor hasn't changed yet. To give the 
840                                 // DEPM the possibility of doing something we must
841                                 // provide it with two different cursors.
842                                 Cursor dummy = cur;
843                                 dummy.pos() = dummy.pit() = 0;
844                                 if (cur.bv().checkDepm(dummy, cur))
845                                         cur.forceBufferUpdate();
846                         }
847                 }
848                 break;
849
850         case LFUN_WORD_LEFT:
851         case LFUN_WORD_LEFT_SELECT:
852                 if (lyxrc.visual_cursor) {
853                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
854                         needsUpdate |= cursorVisLeftOneWord(cur);
855                         if (!needsUpdate && oldTopSlice == cur.top()
856                                         && cur.boundary() == oldBoundary) {
857                                 cur.undispatched();
858                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
859                         }
860                 } else {
861                         if (reverseDirectionNeeded(cur)) {
862                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
863                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
864                         } else {
865                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
866                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
867                         }
868                         dispatch(cur, cmd);
869                         return;
870                 }
871                 break;
872
873         case LFUN_WORD_BACKWARD:
874         case LFUN_WORD_BACKWARD_SELECT:
875                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
876                 needsUpdate |= cursorBackwardOneWord(cur);
877         
878                 if (!needsUpdate && oldTopSlice == cur.top()
879                                 && cur.boundary() == oldBoundary) {
880                         cur.undispatched();
881                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
882                 
883                         // we will probably be moving out the inset, so we should execute
884                         // the depm-mechanism, but only when the cursor has a place to 
885                         // go outside this inset, i.e. in a slice above.
886                         if (cur.depth() > 1 && cur.pos() == 0 
887                                   && cur.pit() == 0) {
888                                 // The cursor hasn't changed yet. To give the 
889                                 // DEPM the possibility of doing something we must
890                                 // provide it with two different cursors.
891                                 Cursor dummy = cur;
892                                 dummy.pos() = cur.lastpos();
893                                 dummy.pit() = cur.lastpit();
894                                 if (cur.bv().checkDepm(dummy, cur))
895                                         cur.forceBufferUpdate();
896                         }
897                 }
898                 break;
899
900         case LFUN_WORD_SELECT: {
901                 selectWord(cur, WHOLE_WORD);
902                 finishChange(cur, true);
903                 break;
904         }
905
906         case LFUN_NEWLINE_INSERT: {
907                 InsetNewlineParams inp;
908                 docstring arg = cmd.argument();
909                 // this avoids a double undo
910                 // FIXME: should not be needed, ideally
911                 if (!cur.selection())
912                         cur.recordUndo();
913                 cap::replaceSelection(cur);
914                 if (arg == "linebreak")
915                         inp.kind = InsetNewlineParams::LINEBREAK;
916                 else
917                         inp.kind = InsetNewlineParams::NEWLINE;
918                 cur.insert(new InsetNewline(inp));
919                 cur.posForward();
920                 moveCursor(cur, false);
921                 break;
922         }
923
924         case LFUN_TAB_INSERT: {
925                 bool const multi_par_selection = cur.selection() &&
926                         cur.selBegin().pit() != cur.selEnd().pit();
927                 if (multi_par_selection) {
928                         // If there is a multi-paragraph selection, a tab is inserted
929                         // at the beginning of each paragraph.
930                         cur.recordUndoSelection();
931                         pit_type const pit_end = cur.selEnd().pit();
932                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
933                                 pars_[pit].insertChar(0, '\t', 
934                                                       bv->buffer().params().trackChanges);
935                                 // Update the selection pos to make sure the selection does not
936                                 // change as the inserted tab will increase the logical pos.
937                                 if (cur.realAnchor().pit() == pit)
938                                         cur.realAnchor().forwardPos();
939                                 if (cur.pit() == pit)
940                                         cur.forwardPos();
941                         }
942                         cur.finishUndo();
943                 } else {
944                         // Maybe we shouldn't allow tabs within a line, because they
945                         // are not (yet) aligned as one might do expect.
946                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
947                         dispatch(cur, cmd);     
948                 }
949                 break;
950         }
951
952         case LFUN_TAB_DELETE: {
953                 bool const tc = bv->buffer().params().trackChanges;
954                 if (cur.selection()) {
955                         // If there is a selection, a tab (if present) is removed from
956                         // the beginning of each paragraph.
957                         cur.recordUndoSelection();
958                         pit_type const pit_end = cur.selEnd().pit();
959                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
960                                 Paragraph & par = paragraphs()[pit];
961                                 if (par.empty())
962                                         continue;
963                                 char_type const c = par.getChar(0);
964                                 if (c == '\t' || c == ' ') {
965                                         // remove either 1 tab or 4 spaces.
966                                         int const n = (c == ' ' ? 4 : 1);
967                                         for (int i = 0; i < n 
968                                                   && !par.empty() && par.getChar(0) == c; ++i) {
969                                                 if (cur.pit() == pit)
970                                                         cur.posBackward();
971                                                 if (cur.realAnchor().pit() == pit 
972                                                           && cur.realAnchor().pos() > 0 )
973                                                         cur.realAnchor().backwardPos();
974                                                 par.eraseChar(0, tc);
975                                         }
976                                 }
977                         }
978                         cur.finishUndo();
979                 } else {
980                         // If there is no selection, try to remove a tab or some spaces 
981                         // before the position of the cursor.
982                         Paragraph & par = paragraphs()[cur.pit()];
983                         pos_type const pos = cur.pos();
984                         
985                         if (pos == 0)
986                                 break;
987                         
988                         char_type const c = par.getChar(pos - 1);
989                         cur.recordUndo();
990                         if (c == '\t') {
991                                 cur.posBackward();
992                                 par.eraseChar(cur.pos(), tc);
993                         } else
994                                 for (int n_spaces = 0; 
995                                      cur.pos() > 0
996                                              && par.getChar(cur.pos() - 1) == ' ' 
997                                              && n_spaces < 4;
998                                      ++n_spaces) {
999                                         cur.posBackward();
1000                                         par.eraseChar(cur.pos(), tc);
1001                                 }
1002                         cur.finishUndo();
1003                 }
1004                 break;
1005         }
1006
1007         case LFUN_CHAR_DELETE_FORWARD:
1008                 if (!cur.selection()) {
1009                         if (cur.pos() == cur.paragraph().size())
1010                                 // Par boundary, force full-screen update
1011                                 singleParUpdate = false;
1012                         needsUpdate |= erase(cur);
1013                         cur.resetAnchor();
1014                         // It is possible to make it a lot faster still
1015                         // just comment out the line below...
1016                 } else {
1017                         cutSelection(cur, true, false);
1018                         singleParUpdate = false;
1019                 }
1020                 moveCursor(cur, false);
1021                 break;
1022
1023         case LFUN_CHAR_DELETE_BACKWARD:
1024                 if (!cur.selection()) {
1025                         if (bv->getIntl().getTransManager().backspace()) {
1026                                 // Par boundary, full-screen update
1027                                 if (cur.pos() == 0)
1028                                         singleParUpdate = false;
1029                                 needsUpdate |= backspace(cur);
1030                                 cur.resetAnchor();
1031                                 // It is possible to make it a lot faster still
1032                                 // just comment out the line below...
1033                         }
1034                 } else {
1035                         cutSelection(cur, true, false);
1036                         singleParUpdate = false;
1037                 }
1038                 break;
1039
1040         case LFUN_BREAK_PARAGRAPH:
1041                 cap::replaceSelection(cur);
1042                 breakParagraph(cur, cmd.argument() == "inverse");
1043                 cur.resetAnchor();
1044                 break;
1045
1046         case LFUN_INSET_INSERT: {
1047                 cur.recordUndo();
1048
1049                 // We have to avoid triggering InstantPreview loading
1050                 // before inserting into the document. See bug #5626.
1051                 bool loaded = bv->buffer().isFullyLoaded();
1052                 bv->buffer().setFullyLoaded(false);
1053                 Inset * inset = createInset(&bv->buffer(), cmd);
1054                 bv->buffer().setFullyLoaded(loaded);
1055
1056                 if (inset) {
1057                         // FIXME (Abdel 01/02/2006):
1058                         // What follows would be a partial fix for bug 2154:
1059                         //   http://www.lyx.org/trac/ticket/2154
1060                         // This automatically put the label inset _after_ a
1061                         // numbered section. It should be possible to extend the mechanism
1062                         // to any kind of LateX environement.
1063                         // The correct way to fix that bug would be at LateX generation.
1064                         // I'll let the code here for reference as it could be used for some
1065                         // other feature like "automatic labelling".
1066                         /*
1067                         Paragraph & par = pars_[cur.pit()];
1068                         if (inset->lyxCode() == LABEL_CODE
1069                                 && par.layout().labeltype == LABEL_COUNTER) {
1070                                 // Go to the end of the paragraph
1071                                 // Warning: Because of Change-Tracking, the last
1072                                 // position is 'size()' and not 'size()-1':
1073                                 cur.pos() = par.size();
1074                                 // Insert a new paragraph
1075                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1076                                 dispatch(cur, fr);
1077                         }
1078                         */
1079                         if (cur.selection())
1080                                 cutSelection(cur, true, false);
1081                         cur.insert(inset);
1082                         if (inset->editable() && inset->asInsetText())
1083                                 inset->edit(cur, true);
1084                         else
1085                                 cur.posForward();
1086
1087                         // trigger InstantPreview now
1088                         if (inset->lyxCode() == EXTERNAL_CODE) {
1089                                 InsetExternal & ins =
1090                                         static_cast<InsetExternal &>(*inset);
1091                                 ins.updatePreview();
1092                         }
1093                 }
1094
1095                 break;
1096         }
1097
1098         case LFUN_INSET_DISSOLVE: {
1099                 if (dissolveInset(cur)) {
1100                         needsUpdate = true;
1101                         cur.forceBufferUpdate();
1102                 }
1103                 break;
1104         }
1105
1106         case LFUN_SET_GRAPHICS_GROUP: {
1107                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1108                 if (!ins)
1109                         break;
1110
1111                 cur.recordUndo();
1112
1113                 string id = to_utf8(cmd.argument());
1114                 string grp = graphics::getGroupParams(bv->buffer(), id);
1115                 InsetGraphicsParams tmp, inspar = ins->getParams();
1116
1117                 if (id.empty())
1118                         inspar.groupId = to_utf8(cmd.argument());
1119                 else {
1120                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1121                         tmp.filename = inspar.filename;
1122                         inspar = tmp;
1123                 }
1124
1125                 ins->setParams(inspar);
1126         }
1127
1128         case LFUN_SPACE_INSERT:
1129                 if (cur.paragraph().layout().free_spacing)
1130                         insertChar(cur, ' ');
1131                 else {
1132                         doInsertInset(cur, this, cmd, false, false);
1133                         cur.posForward();
1134                 }
1135                 moveCursor(cur, false);
1136                 break;
1137
1138         case LFUN_SPECIALCHAR_INSERT: {
1139                 string const name = to_utf8(cmd.argument());
1140                 if (name == "hyphenation")
1141                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1142                 else if (name == "ligature-break")
1143                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1144                 else if (name == "slash")
1145                         specialChar(cur, InsetSpecialChar::SLASH);
1146                 else if (name == "nobreakdash")
1147                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1148                 else if (name == "dots")
1149                         specialChar(cur, InsetSpecialChar::LDOTS);
1150                 else if (name == "end-of-sentence")
1151                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1152                 else if (name == "menu-separator")
1153                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1154                 else if (name.empty())
1155                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1156                 else
1157                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1158                 break;
1159         }
1160
1161         case LFUN_WORD_UPCASE:
1162                 changeCase(cur, text_uppercase);
1163                 break;
1164
1165         case LFUN_WORD_LOWCASE:
1166                 changeCase(cur, text_lowercase);
1167                 break;
1168
1169         case LFUN_WORD_CAPITALIZE:
1170                 changeCase(cur, text_capitalization);
1171                 break;
1172
1173         case LFUN_CHARS_TRANSPOSE:
1174                 charsTranspose(cur);
1175                 break;
1176
1177         case LFUN_PASTE: {
1178                 cur.message(_("Paste"));
1179                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1180                 cap::replaceSelection(cur);
1181
1182                 // without argument?
1183                 string const arg = to_utf8(cmd.argument());
1184                 if (arg.empty()) {
1185                         if (theClipboard().isInternal())
1186                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1187                         else if (theClipboard().hasGraphicsContents() 
1188                                      && !theClipboard().hasTextContents())
1189                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1190                         else
1191                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1192                 } else if (isStrUnsignedInt(arg)) {
1193                         // we have a numerical argument
1194                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1195                                        convert<unsigned int>(arg));
1196                 } else {
1197                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1198                         if (arg == "pdf")
1199                                 type = Clipboard::PdfGraphicsType;
1200                         else if (arg == "png")
1201                                 type = Clipboard::PngGraphicsType;
1202                         else if (arg == "jpeg")
1203                                 type = Clipboard::JpegGraphicsType;
1204                         else if (arg == "linkback")
1205                                 type = Clipboard::LinkBackGraphicsType;
1206                         else if (arg == "emf")
1207                                 type = Clipboard::EmfGraphicsType;
1208                         else if (arg == "wmf")
1209                                 type = Clipboard::WmfGraphicsType;
1210
1211                         else
1212                                 LASSERT(false, /**/);
1213
1214                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1215                 }
1216
1217                 bv->buffer().errors("Paste");
1218                 cur.clearSelection(); // bug 393
1219                 cur.finishUndo();
1220                 break;
1221         }
1222
1223         case LFUN_CUT:
1224                 cutSelection(cur, true, true);
1225                 cur.message(_("Cut"));
1226                 break;
1227
1228         case LFUN_COPY:
1229                 copySelection(cur);
1230                 cur.message(_("Copy"));
1231                 break;
1232
1233         case LFUN_SERVER_GET_XY:
1234                 cur.message(from_utf8(
1235                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1236                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1237                 break;
1238
1239         case LFUN_SERVER_SET_XY: {
1240                 int x = 0;
1241                 int y = 0;
1242                 istringstream is(to_utf8(cmd.argument()));
1243                 is >> x >> y;
1244                 if (!is)
1245                         lyxerr << "SETXY: Could not parse coordinates in '"
1246                                << to_utf8(cmd.argument()) << endl;
1247                 else
1248                         tm->setCursorFromCoordinates(cur, x, y);
1249                 break;
1250         }
1251
1252         case LFUN_SERVER_GET_LAYOUT:
1253                 cur.message(cur.paragraph().layout().name());
1254                 break;
1255
1256         case LFUN_LAYOUT: {
1257                 docstring layout = cmd.argument();
1258                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1259
1260                 Paragraph const & para = cur.paragraph();
1261                 docstring const old_layout = para.layout().name();
1262                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1263
1264                 if (layout.empty())
1265                         layout = tclass.defaultLayoutName();
1266
1267                 if (owner_->forcePlainLayout())
1268                         // in this case only the empty layout is allowed
1269                         layout = tclass.plainLayoutName();
1270                 else if (para.usePlainLayout()) {
1271                         // in this case, default layout maps to empty layout
1272                         if (layout == tclass.defaultLayoutName())
1273                                 layout = tclass.plainLayoutName();
1274                 } else {
1275                         // otherwise, the empty layout maps to the default
1276                         if (layout == tclass.plainLayoutName())
1277                                 layout = tclass.defaultLayoutName();
1278                 }
1279
1280                 bool hasLayout = tclass.hasLayout(layout);
1281
1282                 // If the entry is obsolete, use the new one instead.
1283                 if (hasLayout) {
1284                         docstring const & obs = tclass[layout].obsoleted_by();
1285                         if (!obs.empty())
1286                                 layout = obs;
1287                 }
1288
1289                 if (!hasLayout) {
1290                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1291                                 from_utf8(N_(" not known")));
1292                         break;
1293                 }
1294
1295                 bool change_layout = (old_layout != layout);
1296
1297                 if (!change_layout && cur.selection() &&
1298                         cur.selBegin().pit() != cur.selEnd().pit())
1299                 {
1300                         pit_type spit = cur.selBegin().pit();
1301                         pit_type epit = cur.selEnd().pit() + 1;
1302                         while (spit != epit) {
1303                                 if (pars_[spit].layout().name() != old_layout) {
1304                                         change_layout = true;
1305                                         break;
1306                                 }
1307                                 ++spit;
1308                         }
1309                 }
1310
1311                 if (change_layout)
1312                         setLayout(cur, layout);
1313
1314                 break;
1315         }
1316
1317         case LFUN_CLIPBOARD_PASTE:
1318                 cur.clearSelection();
1319                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1320                                cmd.argument() == "paragraph");
1321                 bv->buffer().errors("Paste");
1322                 break;
1323
1324         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1325                 cur.clearSelection();
1326                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1327                 break;
1328
1329         case LFUN_PRIMARY_SELECTION_PASTE:
1330                 pasteString(cur, theSelection().get(),
1331                             cmd.argument() == "paragraph");
1332                 break;
1333
1334         case LFUN_SELECTION_PASTE:
1335                 // Copy the selection buffer to the clipboard stack,
1336                 // because we want it to appear in the "Edit->Paste
1337                 // recent" menu.
1338                 cap::copySelectionToStack();
1339                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1340                 bv->buffer().errors("Paste");
1341                 break;
1342
1343         case LFUN_UNICODE_INSERT: {
1344                 if (cmd.argument().empty())
1345                         break;
1346                 docstring hexstring = cmd.argument();
1347                 if (isHex(hexstring)) {
1348                         char_type c = hexToInt(hexstring);
1349                         if (c >= 32 && c < 0x10ffff) {
1350                                 lyxerr << "Inserting c: " << c << endl;
1351                                 docstring s = docstring(1, c);
1352                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1353                         }
1354                 }
1355                 break;
1356         }
1357
1358         case LFUN_QUOTE_INSERT: {
1359                 // this avoids a double undo
1360                 // FIXME: should not be needed, ideally
1361                 if (!cur.selection())
1362                         cur.recordUndo();
1363                 cap::replaceSelection(cur);
1364
1365                 Paragraph const & par = cur.paragraph();
1366                 pos_type pos = cur.pos();
1367
1368                 BufferParams const & bufparams = bv->buffer().params();
1369                 bool const hebrew = 
1370                         par.getFontSettings(bufparams, pos).language()->lang() == "hebrew";
1371                 bool const allow_inset_quote = !(par.isPassThru() || hebrew);
1372                 
1373                 if (allow_inset_quote) {
1374                         char_type c = ' ';
1375                         if (pos > 0 && (!cur.prevInset() || !cur.prevInset()->isSpace()))
1376                                 c = par.getChar(pos - 1);
1377                         string const arg = to_utf8(cmd.argument());
1378                         InsetQuotes::QuoteTimes const quote_type = (arg == "single")
1379                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes;
1380                         cur.insert(new InsetQuotes(cur.buffer(), c, quote_type));
1381                         cur.posForward();
1382                 } else {
1383                         // The cursor might have been invalidated by the replaceSelection.
1384                         cur.buffer()->changed(true);
1385                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1386                 }                       
1387                 break;
1388         }
1389
1390         case LFUN_DATE_INSERT: {
1391                 string const format = cmd.argument().empty()
1392                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1393                 string const time = formatted_time(current_time(), format);
1394                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1395                 break;
1396         }
1397
1398         case LFUN_MOUSE_TRIPLE:
1399                 if (cmd.button() == mouse_button::button1) {
1400                         tm->cursorHome(cur);
1401                         cur.resetAnchor();
1402                         tm->cursorEnd(cur);
1403                         cur.setSelection();
1404                         bv->cursor() = cur;
1405                 }
1406                 break;
1407
1408         case LFUN_MOUSE_DOUBLE:
1409                 if (cmd.button() == mouse_button::button1) {
1410                         selectWord(cur, WHOLE_WORD_STRICT);
1411                         bv->cursor() = cur;
1412                 }
1413                 break;
1414
1415         // Single-click on work area
1416         case LFUN_MOUSE_PRESS: {
1417                 // We are not marking a selection with the keyboard in any case.
1418                 Cursor & bvcur = cur.bv().cursor();
1419                 bvcur.setMark(false);
1420                 switch (cmd.button()) {
1421                 case mouse_button::button1:
1422                         // Set the cursor
1423                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1424                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1425                         if (bvcur.wordSelection())
1426                                 selectWord(bvcur, WHOLE_WORD);
1427                         break;
1428
1429                 case mouse_button::button2:
1430                         // Middle mouse pasting.
1431                         bv->mouseSetCursor(cur);
1432                         lyx::dispatch(
1433                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1434                                             "selection-paste ; primary-selection-paste paragraph"));
1435                         cur.noScreenUpdate();
1436                         break;
1437
1438                 case mouse_button::button3: {
1439                         // Don't do anything if we right-click a
1440                         // selection, a context menu will popup.
1441                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1442                             && cur < bvcur.selectionEnd()) {
1443                                 cur.noScreenUpdate();
1444                                 return;
1445                         }
1446                         if (!bv->mouseSetCursor(cur, false))
1447                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1448                         break;
1449                 }
1450
1451                 default:
1452                         break;
1453                 } // switch (cmd.button())
1454                 break;
1455         }
1456         case LFUN_MOUSE_MOTION: {
1457                 // Mouse motion with right or middle mouse do nothing for now.
1458                 if (cmd.button() != mouse_button::button1) {
1459                         cur.noScreenUpdate();
1460                         return;
1461                 }
1462                 // ignore motions deeper nested than the real anchor
1463                 Cursor & bvcur = cur.bv().cursor();
1464                 if (!bvcur.realAnchor().hasPart(cur)) {
1465                         cur.undispatched();
1466                         break;
1467                 }
1468                 CursorSlice old = bvcur.top();
1469
1470                 int const wh = bv->workHeight();
1471                 int const y = max(0, min(wh - 1, cmd.y()));
1472
1473                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1474                 cur.setTargetX(cmd.x());
1475                 if (cmd.y() >= wh)
1476                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1477                 else if (cmd.y() < 0)
1478                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1479                 // This is to allow jumping over large insets
1480                 if (cur.top() == old) {
1481                         if (cmd.y() >= wh)
1482                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1483                         else if (cmd.y() < 0)
1484                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1485                 }
1486                 // We continue with our existing selection or start a new one, so don't
1487                 // reset the anchor.
1488                 bvcur.setCursor(cur);
1489                 bvcur.setSelection(true);
1490                 if (cur.top() == old) {
1491                         // We didn't move one iota, so no need to update the screen.
1492                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1493                         //cur.noScreenUpdate();
1494                         return;
1495                 }
1496                 break;
1497         }
1498
1499         case LFUN_MOUSE_RELEASE:
1500                 switch (cmd.button()) {
1501                 case mouse_button::button1:
1502                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1503                         // If there is a new selection, update persistent selection;
1504                         // otherwise, single click does not clear persistent selection
1505                         // buffer.
1506                         if (cur.selection()) {
1507                                 // Finish selection. If double click,
1508                                 // cur is moved to the end of word by
1509                                 // selectWord but bvcur is current
1510                                 // mouse position.
1511                                 cur.bv().cursor().setSelection();
1512                                 // We might have removed an empty but drawn selection
1513                                 // (probably a margin)
1514                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1515                         } else
1516                                 cur.noScreenUpdate();
1517                         // FIXME: We could try to handle drag and drop of selection here.
1518                         return;
1519
1520                 case mouse_button::button2:
1521                         // Middle mouse pasting is handled at mouse press time,
1522                         // see LFUN_MOUSE_PRESS.
1523                         cur.noScreenUpdate();
1524                         return;
1525
1526                 case mouse_button::button3:
1527                         // Cursor was set at LFUN_MOUSE_PRESS time.
1528                         // FIXME: If there is a selection we could try to handle a special
1529                         // drag & drop context menu.
1530                         cur.noScreenUpdate();
1531                         return;
1532
1533                 case mouse_button::none:
1534                 case mouse_button::button4:
1535                 case mouse_button::button5:
1536                         break;
1537                 } // switch (cmd.button())
1538
1539                 break;
1540
1541         case LFUN_SELF_INSERT: {
1542                 if (cmd.argument().empty())
1543                         break;
1544
1545                 // Automatically delete the currently selected
1546                 // text and replace it with what is being
1547                 // typed in now. Depends on lyxrc settings
1548                 // "auto_region_delete", which defaults to
1549                 // true (on).
1550
1551                 if (lyxrc.auto_region_delete && cur.selection())
1552                         cutSelection(cur, false, false);
1553
1554                 cur.clearSelection();
1555
1556                 docstring::const_iterator cit = cmd.argument().begin();
1557                 docstring::const_iterator const end = cmd.argument().end();
1558                 for (; cit != end; ++cit)
1559                         bv->translateAndInsert(*cit, this, cur);
1560
1561                 cur.resetAnchor();
1562                 moveCursor(cur, false);
1563                 cur.markNewWordPosition();
1564                 bv->bookmarkEditPosition();
1565                 break;
1566         }
1567
1568         case LFUN_HYPERLINK_INSERT: {
1569                 InsetCommandParams p(HYPERLINK_CODE);
1570                 docstring content;
1571                 if (cur.selection()) {
1572                         content = cur.selectionAsString(false);
1573                         cutSelection(cur, true, false);
1574                 }
1575                 p["target"] = (cmd.argument().empty()) ?
1576                         content : cmd.argument();
1577                 string const data = InsetCommand::params2string(p);
1578                 if (p["target"].empty()) {
1579                         bv->showDialog("href", data);
1580                 } else {
1581                         FuncRequest fr(LFUN_INSET_INSERT, data);
1582                         dispatch(cur, fr);
1583                 }
1584                 break;
1585         }
1586
1587         case LFUN_LABEL_INSERT: {
1588                 InsetCommandParams p(LABEL_CODE);
1589                 // Try to generate a valid label
1590                 p["name"] = (cmd.argument().empty()) ?
1591                         cur.getPossibleLabel() :
1592                         cmd.argument();
1593                 string const data = InsetCommand::params2string(p);
1594
1595                 if (cmd.argument().empty()) {
1596                         bv->showDialog("label", data);
1597                 } else {
1598                         FuncRequest fr(LFUN_INSET_INSERT, data);
1599                         dispatch(cur, fr);
1600                 }
1601                 break;
1602         }
1603
1604         case LFUN_INFO_INSERT: {
1605                 Inset * inset;
1606                 if (cmd.argument().empty() && cur.selection()) {
1607                         // if command argument is empty use current selection as parameter.
1608                         docstring ds = cur.selectionAsString(false);
1609                         cutSelection(cur, true, false);
1610                         FuncRequest cmd0(cmd, ds);
1611                         inset = createInset(cur.buffer(), cmd0);
1612                 } else {
1613                         inset = createInset(cur.buffer(), cmd);
1614                 }
1615                 if (!inset)
1616                         break;
1617                 cur.recordUndo();
1618                 insertInset(cur, inset);
1619                 cur.posForward();
1620                 break;
1621         }
1622         case LFUN_CAPTION_INSERT:
1623         case LFUN_FOOTNOTE_INSERT:
1624         case LFUN_NOTE_INSERT:
1625         case LFUN_FLEX_INSERT:
1626         case LFUN_BOX_INSERT:
1627         case LFUN_BRANCH_INSERT:
1628         case LFUN_PHANTOM_INSERT:
1629         case LFUN_ERT_INSERT:
1630         case LFUN_LISTING_INSERT:
1631         case LFUN_MARGINALNOTE_INSERT:
1632         case LFUN_ARGUMENT_INSERT:
1633         case LFUN_INDEX_INSERT:
1634         case LFUN_PREVIEW_INSERT:
1635         case LFUN_SCRIPT_INSERT:
1636                 // Open the inset, and move the current selection
1637                 // inside it.
1638                 doInsertInset(cur, this, cmd, true, true);
1639                 cur.posForward();
1640                 // Some insets are numbered, others are shown in the outline pane so
1641                 // let's update the labels and the toc backend.
1642                 cur.forceBufferUpdate();
1643                 break;
1644
1645         case LFUN_TABULAR_INSERT:
1646                 // if there were no arguments, just open the dialog
1647                 if (doInsertInset(cur, this, cmd, false, true))
1648                         cur.posForward();
1649                 else
1650                         bv->showDialog("tabularcreate");
1651
1652                 break;
1653
1654         case LFUN_FLOAT_INSERT:
1655         case LFUN_FLOAT_WIDE_INSERT:
1656         case LFUN_WRAP_INSERT: {
1657                 // will some text be moved into the inset?
1658                 bool content = cur.selection();
1659
1660                 doInsertInset(cur, this, cmd, true, true);
1661                 cur.posForward();
1662
1663                 // If some text is moved into the inset, doInsertInset 
1664                 // puts the cursor outside the inset. To insert the
1665                 // caption we put it back into the inset.
1666                 if (content)
1667                         cur.backwardPos();
1668
1669                 ParagraphList & pars = cur.text()->paragraphs();
1670
1671                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1672
1673                 // add a separate paragraph for the caption inset
1674                 pars.push_back(Paragraph());
1675                 pars.back().setInsetOwner(&cur.text()->inset());
1676                 pars.back().setPlainOrDefaultLayout(tclass);
1677                 int cap_pit = pars.size() - 1;
1678
1679                 // if an empty inset was created, we create an additional empty
1680                 // paragraph at the bottom so that the user can choose where to put
1681                 // the graphics (or table).
1682                 if (!content) {
1683                         pars.push_back(Paragraph());
1684                         pars.back().setInsetOwner(&cur.text()->inset());
1685                         pars.back().setPlainOrDefaultLayout(tclass);
1686                 }
1687
1688                 // reposition the cursor to the caption
1689                 cur.pit() = cap_pit;
1690                 cur.pos() = 0;
1691                 // FIXME: This Text/Cursor dispatch handling is a mess!
1692                 // We cannot use Cursor::dispatch here it needs access to up to
1693                 // date metrics.
1694                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1695                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1696                 cur.forceBufferUpdate();
1697                 cur.screenUpdateFlags(Update::Force);
1698                 // FIXME: When leaving the Float (or Wrap) inset we should
1699                 // delete any empty paragraph left above or below the
1700                 // caption.
1701                 break;
1702         }
1703
1704         case LFUN_NOMENCL_INSERT: {
1705                 InsetCommandParams p(NOMENCL_CODE);
1706                 if (cmd.argument().empty())
1707                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1708                 else
1709                         p["symbol"] = cmd.argument();
1710                 string const data = InsetCommand::params2string(p);
1711                 bv->showDialog("nomenclature", data);
1712                 break;
1713         }
1714
1715         case LFUN_INDEX_PRINT: {
1716                 InsetCommandParams p(INDEX_PRINT_CODE);
1717                 if (cmd.argument().empty())
1718                         p["type"] = from_ascii("idx");
1719                 else
1720                         p["type"] = cmd.argument();
1721                 string const data = InsetCommand::params2string(p);
1722                 FuncRequest fr(LFUN_INSET_INSERT, data);
1723                 dispatch(cur, fr);
1724                 break;
1725         }
1726         
1727         case LFUN_NOMENCL_PRINT:
1728         case LFUN_NEWPAGE_INSERT:
1729                 // do nothing fancy
1730                 doInsertInset(cur, this, cmd, false, false);
1731                 cur.posForward();
1732                 break;
1733
1734         case LFUN_DEPTH_DECREMENT:
1735                 changeDepth(cur, DEC_DEPTH);
1736                 break;
1737
1738         case LFUN_DEPTH_INCREMENT:
1739                 changeDepth(cur, INC_DEPTH);
1740                 break;
1741
1742         case LFUN_MATH_DISPLAY:
1743                 mathDispatch(cur, cmd, true);
1744                 break;
1745
1746         case LFUN_REGEXP_MODE:
1747                 regexpDispatch(cur, cmd);
1748                 break;
1749
1750         case LFUN_MATH_MODE:
1751                 if (cmd.argument() == "on")
1752                         // don't pass "on" as argument
1753                         // (it would appear literally in the first cell)
1754                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1755                 else
1756                         mathDispatch(cur, cmd, false);
1757                 break;
1758
1759         case LFUN_MATH_MACRO:
1760                 if (cmd.argument().empty())
1761                         cur.errorMessage(from_utf8(N_("Missing argument")));
1762                 else {
1763                         cur.recordUndo();
1764                         string s = to_utf8(cmd.argument());
1765                         string const s1 = token(s, ' ', 1);
1766                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1767                         string const s2 = token(s, ' ', 2);
1768                         MacroType type = MacroTypeNewcommand;
1769                         if (s2 == "def")
1770                                 type = MacroTypeDef;
1771                         MathMacroTemplate * inset = new MathMacroTemplate(cur.buffer(),
1772                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
1773                         inset->setBuffer(bv->buffer());
1774                         insertInset(cur, inset);
1775
1776                         // enter macro inset and select the name
1777                         cur.push(*inset);
1778                         cur.top().pos() = cur.top().lastpos();
1779                         cur.resetAnchor();
1780                         cur.setSelection(true);
1781                         cur.top().pos() = 0;
1782                 }
1783                 break;
1784
1785         // passthrough hat and underscore outside mathed:
1786         case LFUN_MATH_SUBSCRIPT:
1787                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1788                 break;
1789         case LFUN_MATH_SUPERSCRIPT:
1790                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1791                 break;
1792
1793         case LFUN_MATH_INSERT:
1794         case LFUN_MATH_AMS_MATRIX:
1795         case LFUN_MATH_MATRIX:
1796         case LFUN_MATH_DELIM:
1797         case LFUN_MATH_BIGDELIM: {
1798                 cur.recordUndo();
1799                 cap::replaceSelection(cur);
1800                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
1801                 checkAndActivateInset(cur, true);
1802                 LASSERT(cur.inMathed(), /**/);
1803                 cur.dispatch(cmd);
1804                 break;
1805         }
1806
1807         case LFUN_FONT_EMPH: {
1808                 Font font(ignore_font, ignore_language);
1809                 font.fontInfo().setEmph(FONT_TOGGLE);
1810                 toggleAndShow(cur, this, font);
1811                 break;
1812         }
1813
1814         case LFUN_FONT_ITAL: {
1815                 Font font(ignore_font, ignore_language);
1816                 font.fontInfo().setShape(ITALIC_SHAPE);
1817                 toggleAndShow(cur, this, font);
1818                 break;
1819         }
1820
1821         case LFUN_FONT_BOLD:
1822         case LFUN_FONT_BOLDSYMBOL: {
1823                 Font font(ignore_font, ignore_language);
1824                 font.fontInfo().setSeries(BOLD_SERIES);
1825                 toggleAndShow(cur, this, font);
1826                 break;
1827         }
1828
1829         case LFUN_FONT_NOUN: {
1830                 Font font(ignore_font, ignore_language);
1831                 font.fontInfo().setNoun(FONT_TOGGLE);
1832                 toggleAndShow(cur, this, font);
1833                 break;
1834         }
1835
1836         case LFUN_FONT_TYPEWRITER: {
1837                 Font font(ignore_font, ignore_language);
1838                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1839                 toggleAndShow(cur, this, font);
1840                 break;
1841         }
1842
1843         case LFUN_FONT_SANS: {
1844                 Font font(ignore_font, ignore_language);
1845                 font.fontInfo().setFamily(SANS_FAMILY);
1846                 toggleAndShow(cur, this, font);
1847                 break;
1848         }
1849
1850         case LFUN_FONT_ROMAN: {
1851                 Font font(ignore_font, ignore_language);
1852                 font.fontInfo().setFamily(ROMAN_FAMILY);
1853                 toggleAndShow(cur, this, font);
1854                 break;
1855         }
1856
1857         case LFUN_FONT_DEFAULT: {
1858                 Font font(inherit_font, ignore_language);
1859                 toggleAndShow(cur, this, font);
1860                 break;
1861         }
1862
1863         case LFUN_FONT_STRIKEOUT: {
1864                 Font font(ignore_font, ignore_language);
1865                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1866                 toggleAndShow(cur, this, font);
1867                 break;
1868         }
1869
1870         case LFUN_FONT_UULINE: {
1871                 Font font(ignore_font, ignore_language);
1872                 font.fontInfo().setUuline(FONT_TOGGLE);
1873                 toggleAndShow(cur, this, font);
1874                 break;
1875         }
1876
1877         case LFUN_FONT_UWAVE: {
1878                 Font font(ignore_font, ignore_language);
1879                 font.fontInfo().setUwave(FONT_TOGGLE);
1880                 toggleAndShow(cur, this, font);
1881                 break;
1882         }
1883
1884         case LFUN_FONT_UNDERLINE: {
1885                 Font font(ignore_font, ignore_language);
1886                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1887                 toggleAndShow(cur, this, font);
1888                 break;
1889         }
1890
1891         case LFUN_FONT_SIZE: {
1892                 Font font(ignore_font, ignore_language);
1893                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1894                 toggleAndShow(cur, this, font);
1895                 break;
1896         }
1897
1898         case LFUN_LANGUAGE: {
1899                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1900                 if (!lang)
1901                         break;
1902                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
1903                 Font font(ignore_font, lang);
1904                 toggleAndShow(cur, this, font, false);
1905                 break;
1906         }
1907
1908         case LFUN_TEXTSTYLE_APPLY:
1909                 toggleAndShow(cur, this, freefont, toggleall);
1910                 cur.message(_("Character set"));
1911                 break;
1912
1913         // Set the freefont using the contents of \param data dispatched from
1914         // the frontends and apply it at the current cursor location.
1915         case LFUN_TEXTSTYLE_UPDATE: {
1916                 Font font;
1917                 bool toggle;
1918                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1919                         freefont = font;
1920                         toggleall = toggle;
1921                         toggleAndShow(cur, this, freefont, toggleall);
1922                         cur.message(_("Character set"));
1923                 } else {
1924                         lyxerr << "Argument not ok";
1925                 }
1926                 break;
1927         }
1928
1929         case LFUN_FINISHED_LEFT:
1930                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1931                 // We're leaving an inset, going left. If the inset is LTR, we're
1932                 // leaving from the front, so we should not move (remain at --- but
1933                 // not in --- the inset). If the inset is RTL, move left, without
1934                 // entering the inset itself; i.e., move to after the inset.
1935                 if (cur.paragraph().getFontSettings(
1936                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1937                         cursorVisLeft(cur, true);
1938                 break;
1939
1940         case LFUN_FINISHED_RIGHT:
1941                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1942                 // We're leaving an inset, going right. If the inset is RTL, we're
1943                 // leaving from the front, so we should not move (remain at --- but
1944                 // not in --- the inset). If the inset is LTR, move right, without
1945                 // entering the inset itself; i.e., move to after the inset.
1946                 if (!cur.paragraph().getFontSettings(
1947                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1948                         cursorVisRight(cur, true);
1949                 break;
1950
1951         case LFUN_FINISHED_BACKWARD:
1952                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1953                 break;
1954
1955         case LFUN_FINISHED_FORWARD:
1956                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1957                 ++cur.pos();
1958                 cur.setCurrentFont();
1959                 break;
1960
1961         case LFUN_LAYOUT_PARAGRAPH: {
1962                 string data;
1963                 params2string(cur.paragraph(), data);
1964                 data = "show\n" + data;
1965                 bv->showDialog("paragraph", data);
1966                 break;
1967         }
1968
1969         case LFUN_PARAGRAPH_UPDATE: {
1970                 string data;
1971                 params2string(cur.paragraph(), data);
1972
1973                 // Will the paragraph accept changes from the dialog?
1974                 bool const accept =
1975                         cur.inset().allowParagraphCustomization(cur.idx());
1976
1977                 data = "update " + convert<string>(accept) + '\n' + data;
1978                 bv->updateDialog("paragraph", data);
1979                 break;
1980         }
1981
1982         case LFUN_ACCENT_UMLAUT:
1983         case LFUN_ACCENT_CIRCUMFLEX:
1984         case LFUN_ACCENT_GRAVE:
1985         case LFUN_ACCENT_ACUTE:
1986         case LFUN_ACCENT_TILDE:
1987         case LFUN_ACCENT_CEDILLA:
1988         case LFUN_ACCENT_MACRON:
1989         case LFUN_ACCENT_DOT:
1990         case LFUN_ACCENT_UNDERDOT:
1991         case LFUN_ACCENT_UNDERBAR:
1992         case LFUN_ACCENT_CARON:
1993         case LFUN_ACCENT_BREVE:
1994         case LFUN_ACCENT_TIE:
1995         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1996         case LFUN_ACCENT_CIRCLE:
1997         case LFUN_ACCENT_OGONEK:
1998                 theApp()->handleKeyFunc(cmd.action());
1999                 if (!cmd.argument().empty())
2000                         // FIXME: Are all these characters encoded in one byte in utf8?
2001                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2002                 cur.screenUpdateFlags(Update::FitCursor);
2003                 break;
2004
2005         case LFUN_FLOAT_LIST_INSERT: {
2006                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2007                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2008                         cur.recordUndo();
2009                         if (cur.selection())
2010                                 cutSelection(cur, true, false);
2011                         breakParagraph(cur);
2012
2013                         if (cur.lastpos() != 0) {
2014                                 cursorBackward(cur);
2015                                 breakParagraph(cur);
2016                         }
2017
2018                         docstring const laystr = cur.inset().usePlainLayout() ?
2019                                 tclass.plainLayoutName() :
2020                                 tclass.defaultLayoutName();
2021                         setLayout(cur, laystr);
2022                         ParagraphParameters p;
2023                         // FIXME If this call were replaced with one to clearParagraphParams(),
2024                         // then we could get rid of this method altogether.
2025                         setParagraphs(cur, p);
2026                         // FIXME This should be simplified when InsetFloatList takes a
2027                         // Buffer in its constructor.
2028                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2029                         ifl->setBuffer(bv->buffer());
2030                         insertInset(cur, ifl);
2031                         cur.posForward();
2032                 } else {
2033                         lyxerr << "Non-existent float type: "
2034                                << to_utf8(cmd.argument()) << endl;
2035                 }
2036                 break;
2037         }
2038
2039         case LFUN_CHANGE_ACCEPT: {
2040                 acceptOrRejectChanges(cur, ACCEPT);
2041                 break;
2042         }
2043
2044         case LFUN_CHANGE_REJECT: {
2045                 acceptOrRejectChanges(cur, REJECT);
2046                 break;
2047         }
2048
2049         case LFUN_THESAURUS_ENTRY: {
2050                 docstring arg = cmd.argument();
2051                 if (arg.empty()) {
2052                         arg = cur.selectionAsString(false);
2053                         // FIXME
2054                         if (arg.size() > 100 || arg.empty()) {
2055                                 // Get word or selection
2056                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2057                                 arg = cur.selectionAsString(false);
2058                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2059                         }
2060                 }
2061                 bv->showDialog("thesaurus", to_utf8(arg));
2062                 break;
2063         }
2064
2065         case LFUN_SPELLING_ADD: {
2066                 docstring word = from_utf8(cmd.getArg(0));
2067                 Language * lang;
2068                 if (word.empty()) {
2069                         word = cur.selectionAsString(false);
2070                         // FIXME
2071                         if (word.size() > 100 || word.empty()) {
2072                                 // Get word or selection
2073                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2074                                 word = cur.selectionAsString(false);
2075                         }
2076                         lang = const_cast<Language *>(cur.getFont().language());
2077                 } else
2078                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2079                 WordLangTuple wl(word, lang);
2080                 theSpellChecker()->insert(wl);
2081                 break;
2082         }
2083
2084         case LFUN_SPELLING_IGNORE: {
2085                 docstring word = from_utf8(cmd.getArg(0));
2086                 Language * lang;
2087                 if (word.empty()) {
2088                         word = cur.selectionAsString(false);
2089                         // FIXME
2090                         if (word.size() > 100 || word.empty()) {
2091                                 // Get word or selection
2092                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2093                                 word = cur.selectionAsString(false);
2094                         }
2095                         lang = const_cast<Language *>(cur.getFont().language());
2096                 } else
2097                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2098                 WordLangTuple wl(word, lang);
2099                 theSpellChecker()->accept(wl);
2100                 break;
2101         }
2102
2103         case LFUN_SPELLING_REMOVE: {
2104                 docstring word = from_utf8(cmd.getArg(0));
2105                 Language * lang;
2106                 if (word.empty()) {
2107                         word = cur.selectionAsString(false);
2108                         // FIXME
2109                         if (word.size() > 100 || word.empty()) {
2110                                 // Get word or selection
2111                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2112                                 word = cur.selectionAsString(false);
2113                         }
2114                         lang = const_cast<Language *>(cur.getFont().language());
2115                 } else
2116                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2117                 WordLangTuple wl(word, lang);
2118                 theSpellChecker()->remove(wl);
2119                 break;
2120         }
2121
2122         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2123                 // Given data, an encoding of the ParagraphParameters
2124                 // generated in the Paragraph dialog, this function sets
2125                 // the current paragraph, or currently selected paragraphs,
2126                 // appropriately.
2127                 // NOTE: This function overrides all existing settings.
2128                 setParagraphs(cur, cmd.argument());
2129                 cur.message(_("Paragraph layout set"));
2130                 break;
2131         }
2132
2133         case LFUN_PARAGRAPH_PARAMS: {
2134                 // Given data, an encoding of the ParagraphParameters as we'd
2135                 // find them in a LyX file, this function modifies the current paragraph,
2136                 // or currently selected paragraphs.
2137                 // NOTE: This function only modifies, and does not override, existing
2138                 // settings.
2139                 setParagraphs(cur, cmd.argument(), true);
2140                 cur.message(_("Paragraph layout set"));
2141                 break;
2142         }
2143
2144         case LFUN_ESCAPE:
2145                 if (cur.selection()) {
2146                         cur.setSelection(false);
2147                 } else {
2148                         cur.undispatched();
2149                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2150                         // correct, but I'm not 100% sure -- dov, 071019
2151                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2152                 }
2153                 break;
2154
2155         case LFUN_OUTLINE_UP:
2156                 outline(OutlineUp, cur);
2157                 setCursor(cur, cur.pit(), 0);
2158                 cur.forceBufferUpdate();
2159                 needsUpdate = true;
2160                 break;
2161
2162         case LFUN_OUTLINE_DOWN:
2163                 outline(OutlineDown, cur);
2164                 setCursor(cur, cur.pit(), 0);
2165                 cur.forceBufferUpdate();
2166                 needsUpdate = true;
2167                 break;
2168
2169         case LFUN_OUTLINE_IN:
2170                 outline(OutlineIn, cur);
2171                 cur.forceBufferUpdate();
2172                 needsUpdate = true;
2173                 break;
2174
2175         case LFUN_OUTLINE_OUT:
2176                 outline(OutlineOut, cur);
2177                 cur.forceBufferUpdate();
2178                 needsUpdate = true;
2179                 break;
2180
2181         default:
2182                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2183                 cur.undispatched();
2184                 break;
2185         }
2186
2187         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2188
2189         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2190                 // Check for misspelled text
2191                 // The redraw is useful because of the painting of
2192                 // misspelled markers depends on the cursor position.
2193                 // Trigger a redraw for cursor moves inside misspelled text.
2194                 if (!cur.inTexted()) {
2195                         // move from regular text to math
2196                         needsUpdate = last_misspelled;
2197                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2198                         // move inside regular text
2199                         needsUpdate = last_misspelled
2200                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2201                 }
2202         }
2203
2204         // FIXME: The cursor flag is reset two lines below
2205         // so we need to check here if some of the LFUN did touch that.
2206         // for now only Text::erase() and Text::backspace() do that.
2207         // The plan is to verify all the LFUNs and then to remove this
2208         // singleParUpdate boolean altogether.
2209         if (cur.result().screenUpdate() & Update::Force) {
2210                 singleParUpdate = false;
2211                 needsUpdate = true;
2212         }
2213
2214         // FIXME: the following code should go in favor of fine grained
2215         // update flag treatment.
2216         if (singleParUpdate) {
2217                 // Inserting characters does not change par height in general. So, try
2218                 // to update _only_ this paragraph. BufferView will detect if a full
2219                 // metrics update is needed anyway.
2220                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2221                 return;
2222         }
2223         if (!needsUpdate
2224             && &oldTopSlice.inset() == &cur.inset()
2225             && oldTopSlice.idx() == cur.idx()
2226             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2227             && !cur.selection())
2228                 // FIXME: it would be better if we could just do this
2229                 //
2230                 //if (cur.result().update() != Update::FitCursor)
2231                 //      cur.noScreenUpdate();
2232                 //
2233                 // But some LFUNs do not set Update::FitCursor when needed, so we
2234                 // do it for all. This is not very harmfull as FitCursor will provoke
2235                 // a full redraw only if needed but still, a proper review of all LFUN
2236                 // should be done and this needsUpdate boolean can then be removed.
2237                 cur.screenUpdateFlags(Update::FitCursor);
2238         else
2239                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2240 }
2241
2242
2243 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2244                         FuncStatus & flag) const
2245 {
2246         LASSERT(cur.text() == this, /**/);
2247
2248         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2249         bool enable = true;
2250         InsetCode code = NO_CODE;
2251
2252         switch (cmd.action()) {
2253
2254         case LFUN_DEPTH_DECREMENT:
2255                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2256                 break;
2257
2258         case LFUN_DEPTH_INCREMENT:
2259                 enable = changeDepthAllowed(cur, INC_DEPTH);
2260                 break;
2261
2262         case LFUN_APPENDIX:
2263                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2264                 break;
2265
2266         case LFUN_DIALOG_SHOW_NEW_INSET:
2267                 if (cmd.argument() == "bibitem")
2268                         code = BIBITEM_CODE;
2269                 else if (cmd.argument() == "bibtex") {
2270                         code = BIBTEX_CODE;
2271                         // not allowed in description items
2272                         enable = !inDescriptionItem(cur);
2273                 }
2274                 else if (cmd.argument() == "box")
2275                         code = BOX_CODE;
2276                 else if (cmd.argument() == "branch")
2277                         code = BRANCH_CODE;
2278                 else if (cmd.argument() == "citation")
2279                         code = CITE_CODE;
2280                 else if (cmd.argument() == "ert")
2281                         code = ERT_CODE;
2282                 else if (cmd.argument() == "external")
2283                         code = EXTERNAL_CODE;
2284                 else if (cmd.argument() == "float")
2285                         code = FLOAT_CODE;
2286                 else if (cmd.argument() == "graphics")
2287                         code = GRAPHICS_CODE;
2288                 else if (cmd.argument() == "href")
2289                         code = HYPERLINK_CODE;
2290                 else if (cmd.argument() == "include")
2291                         code = INCLUDE_CODE;
2292                 else if (cmd.argument() == "index")
2293                         code = INDEX_CODE;
2294                 else if (cmd.argument() == "index_print")
2295                         code = INDEX_PRINT_CODE;
2296                 else if (cmd.argument() == "nomenclature")
2297                         code = NOMENCL_CODE;
2298                 else if (cmd.argument() == "nomencl_print")
2299                         code = NOMENCL_PRINT_CODE;
2300                 else if (cmd.argument() == "label")
2301                         code = LABEL_CODE;
2302                 else if (cmd.argument() == "line")
2303                         code = LINE_CODE;
2304                 else if (cmd.argument() == "note")
2305                         code = NOTE_CODE;
2306                 else if (cmd.argument() == "phantom")
2307                         code = PHANTOM_CODE;
2308                 else if (cmd.argument() == "ref")
2309                         code = REF_CODE;
2310                 else if (cmd.argument() == "space")
2311                         code = SPACE_CODE;
2312                 else if (cmd.argument() == "toc")
2313                         code = TOC_CODE;
2314                 else if (cmd.argument() == "vspace")
2315                         code = VSPACE_CODE;
2316                 else if (cmd.argument() == "wrap")
2317                         code = WRAP_CODE;
2318                 else if (cmd.argument() == "listings")
2319                         code = LISTINGS_CODE;
2320                 break;
2321
2322         case LFUN_ERT_INSERT:
2323                 code = ERT_CODE;
2324                 break;
2325         case LFUN_LISTING_INSERT:
2326                 code = LISTINGS_CODE;
2327                 // not allowed in description items
2328                 enable = !inDescriptionItem(cur);
2329                 break;
2330         case LFUN_FOOTNOTE_INSERT:
2331                 code = FOOT_CODE;
2332                 break;
2333         case LFUN_TABULAR_INSERT:
2334                 code = TABULAR_CODE;
2335                 break;
2336         case LFUN_MARGINALNOTE_INSERT:
2337                 code = MARGIN_CODE;
2338                 break;
2339         case LFUN_FLOAT_INSERT:
2340         case LFUN_FLOAT_WIDE_INSERT:
2341                 // FIXME: If there is a selection, we should check whether there
2342                 // are floats in the selection, but this has performance issues, see
2343                 // LFUN_CHANGE_ACCEPT/REJECT.
2344                 code = FLOAT_CODE;
2345                 if (inDescriptionItem(cur))
2346                         // not allowed in description items
2347                         enable = false;
2348                 else {
2349                         InsetCode const inset_code = cur.inset().lyxCode();
2350
2351                         // algorithm floats cannot be put in another float
2352                         if (to_utf8(cmd.argument()) == "algorithm") {
2353                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2354                                 break;
2355                         }
2356
2357                         // for figures and tables: only allow in another
2358                         // float or wrap if it is of the same type and
2359                         // not a subfloat already
2360                         if(cur.inset().lyxCode() == code) {
2361                                 InsetFloat const & ins =
2362                                         static_cast<InsetFloat const &>(cur.inset());
2363                                 enable = ins.params().type == to_utf8(cmd.argument())
2364                                         && !ins.params().subfloat;
2365                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2366                                 InsetWrap const & ins =
2367                                         static_cast<InsetWrap const &>(cur.inset());
2368                                 enable = ins.params().type == to_utf8(cmd.argument());
2369                         }
2370                 }
2371                 break;
2372         case LFUN_WRAP_INSERT:
2373                 code = WRAP_CODE;
2374                 // not allowed in description items
2375                 enable = !inDescriptionItem(cur);
2376                 break;
2377         case LFUN_FLOAT_LIST_INSERT: {
2378                 code = FLOAT_LIST_CODE;
2379                 // not allowed in description items
2380                 enable = !inDescriptionItem(cur);
2381                 if (enable) {
2382                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2383                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2384                         // make sure we know about such floats
2385                         if (cit == floats.end() ||
2386                                         // and that we know how to generate a list of them
2387                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2388                                 flag.setUnknown(true);
2389                                 // probably not necessary, but...
2390                                 enable = false;
2391                         }
2392                 }
2393                 break;
2394         }
2395         case LFUN_CAPTION_INSERT:
2396                 code = CAPTION_CODE;
2397                 // not allowed in description items
2398                 enable = !inDescriptionItem(cur);
2399                 break;
2400         case LFUN_NOTE_INSERT:
2401                 code = NOTE_CODE;
2402                 // in commands (sections etc.) and description items,
2403                 // only Notes are allowed
2404                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2405                           (!cur.paragraph().layout().isCommand()
2406                            && !inDescriptionItem(cur)));
2407                 break;
2408         case LFUN_FLEX_INSERT: {
2409                 code = FLEX_CODE;
2410                 string s = cmd.getArg(0);
2411                 InsetLayout il =
2412                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2413                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2414                     il.lyxtype() != InsetLayout::CUSTOM &&
2415                     il.lyxtype() != InsetLayout::ELEMENT &&
2416                     il.lyxtype ()!= InsetLayout::STANDARD)
2417                         enable = false;
2418                 break;
2419                 }
2420         case LFUN_BOX_INSERT:
2421                 code = BOX_CODE;
2422                 break;
2423         case LFUN_BRANCH_INSERT:
2424                 code = BRANCH_CODE;
2425                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2426                     && cur.buffer()->params().branchlist().empty())
2427                         enable = false;
2428                 break;
2429         case LFUN_PHANTOM_INSERT:
2430                 code = PHANTOM_CODE;
2431                 break;
2432         case LFUN_LABEL_INSERT:
2433                 code = LABEL_CODE;
2434                 break;
2435         case LFUN_INFO_INSERT:
2436                 code = INFO_CODE;
2437                 break;
2438         case LFUN_ARGUMENT_INSERT: {
2439                 code = ARG_CODE;
2440                 Layout const & lay = cur.paragraph().layout();
2441                 int const numargs = lay.reqargs + lay.optargs;
2442                 enable = cur.paragraph().insetList().count(ARG_CODE) < numargs;
2443                 break;
2444         }
2445         case LFUN_INDEX_INSERT:
2446                 code = INDEX_CODE;
2447                 break;
2448         case LFUN_INDEX_PRINT:
2449                 code = INDEX_PRINT_CODE;
2450                 // not allowed in description items
2451                 enable = !inDescriptionItem(cur);
2452                 break;
2453         case LFUN_NOMENCL_INSERT:
2454                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2455                         enable = false;
2456                         break;
2457                 }
2458                 code = NOMENCL_CODE;
2459                 break;
2460         case LFUN_NOMENCL_PRINT:
2461                 code = NOMENCL_PRINT_CODE;
2462                 // not allowed in description items
2463                 enable = !inDescriptionItem(cur);
2464                 break;
2465         case LFUN_HYPERLINK_INSERT:
2466                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2467                         enable = false;
2468                         break;
2469                 }
2470                 code = HYPERLINK_CODE;
2471                 break;
2472         case LFUN_QUOTE_INSERT:
2473                 // always allow this, since we will inset a raw quote
2474                 // if an inset is not allowed.
2475                 break;
2476         case LFUN_SPECIALCHAR_INSERT:
2477                 code = SPECIALCHAR_CODE;
2478                 break;
2479         case LFUN_SPACE_INSERT:
2480                 // slight hack: we know this is allowed in math mode
2481                 if (cur.inTexted())
2482                         code = SPACE_CODE;
2483                 break;
2484         case LFUN_PREVIEW_INSERT:
2485                 code = PREVIEW_CODE;
2486                 break;
2487         case LFUN_SCRIPT_INSERT:
2488                 code = SCRIPT_CODE;
2489                 break;
2490
2491         case LFUN_MATH_INSERT:
2492         case LFUN_MATH_AMS_MATRIX:
2493         case LFUN_MATH_MATRIX:
2494         case LFUN_MATH_DELIM:
2495         case LFUN_MATH_BIGDELIM:
2496         case LFUN_MATH_DISPLAY:
2497         case LFUN_MATH_MODE:
2498         case LFUN_MATH_MACRO:
2499         case LFUN_MATH_SUBSCRIPT:
2500         case LFUN_MATH_SUPERSCRIPT:
2501                 code = MATH_HULL_CODE;
2502                 break;
2503
2504         case LFUN_REGEXP_MODE:
2505                 code = MATH_HULL_CODE;
2506                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
2507                 break;
2508
2509         case LFUN_INSET_MODIFY:
2510                 // We need to disable this, because we may get called for a
2511                 // tabular cell via
2512                 // InsetTabular::getStatus() -> InsetText::getStatus()
2513                 // and we don't handle LFUN_INSET_MODIFY.
2514                 enable = false;
2515                 break;
2516
2517         case LFUN_FONT_EMPH:
2518                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2519                 enable = !cur.paragraph().isPassThru();
2520                 break;
2521
2522         case LFUN_FONT_ITAL:
2523                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2524                 enable = !cur.paragraph().isPassThru();
2525                 break;
2526
2527         case LFUN_FONT_NOUN:
2528                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2529                 enable = !cur.paragraph().isPassThru();
2530                 break;
2531
2532         case LFUN_FONT_BOLD:
2533         case LFUN_FONT_BOLDSYMBOL:
2534                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2535                 enable = !cur.paragraph().isPassThru();
2536                 break;
2537
2538         case LFUN_FONT_SANS:
2539                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2540                 enable = !cur.paragraph().isPassThru();
2541                 break;
2542
2543         case LFUN_FONT_ROMAN:
2544                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2545                 enable = !cur.paragraph().isPassThru();
2546                 break;
2547
2548         case LFUN_FONT_TYPEWRITER:
2549                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2550                 enable = !cur.paragraph().isPassThru();
2551                 break;
2552
2553         case LFUN_CUT:
2554         case LFUN_COPY:
2555                 enable = cur.selection();
2556                 break;
2557
2558         case LFUN_PASTE: {
2559                 if (cmd.argument().empty()) {
2560                         if (theClipboard().isInternal())
2561                                 enable = cap::numberOfSelections() > 0;
2562                         else
2563                                 enable = !theClipboard().empty();
2564                         break;
2565                 }
2566
2567                 // we have an argument
2568                 string const arg = to_utf8(cmd.argument());
2569                 if (isStrUnsignedInt(arg)) {
2570                         // it's a number and therefore means the internal stack
2571                         unsigned int n = convert<unsigned int>(arg);
2572                         enable = cap::numberOfSelections() > n;
2573                         break;
2574                 }
2575
2576                 // explicit graphics type?
2577                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2578                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2579                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2580                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2581                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2582                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2583                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2584                         enable = theClipboard().hasGraphicsContents(type);
2585                         break;
2586                 }
2587
2588                 // unknown argument
2589                 enable = false;
2590                 break;
2591          }
2592
2593         case LFUN_CLIPBOARD_PASTE:
2594         case LFUN_CLIPBOARD_PASTE_SIMPLE:
2595                 enable = !theClipboard().empty();
2596                 break;
2597
2598         case LFUN_PRIMARY_SELECTION_PASTE:
2599                 enable = cur.selection() || !theSelection().empty();
2600                 break;
2601
2602         case LFUN_SELECTION_PASTE:
2603                 enable = cap::selection();
2604                 break;
2605
2606         case LFUN_PARAGRAPH_MOVE_UP:
2607                 enable = cur.pit() > 0 && !cur.selection();
2608                 break;
2609
2610         case LFUN_PARAGRAPH_MOVE_DOWN:
2611                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2612                 break;
2613
2614         case LFUN_CHANGE_ACCEPT:
2615         case LFUN_CHANGE_REJECT:
2616                 // In principle, these LFUNs should only be enabled if there
2617                 // is a change at the current position/in the current selection.
2618                 // However, without proper optimizations, this will inevitably
2619                 // result in unacceptable performance - just imagine a user who
2620                 // wants to select the complete content of a long document.
2621                 if (!cur.selection())
2622                         enable = cur.paragraph().isChanged(cur.pos());
2623                 else
2624                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2625                         // for selections.
2626                         enable = true;
2627                 break;
2628
2629         case LFUN_OUTLINE_UP:
2630         case LFUN_OUTLINE_DOWN:
2631         case LFUN_OUTLINE_IN:
2632         case LFUN_OUTLINE_OUT:
2633                 // FIXME: LyX is not ready for outlining within inset.
2634                 enable = isMainText()
2635                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2636                 break;
2637
2638         case LFUN_NEWLINE_INSERT:
2639                 // LaTeX restrictions (labels or empty par)
2640                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2641                 break;
2642
2643         case LFUN_TAB_INSERT:
2644         case LFUN_TAB_DELETE:
2645                 enable = cur.paragraph().isPassThru();
2646                 break;
2647
2648         case LFUN_SET_GRAPHICS_GROUP: {
2649                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2650                 if (!ins)
2651                         enable = false;
2652                 else
2653                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2654                 break;
2655         }
2656
2657         case LFUN_NEWPAGE_INSERT:
2658                 // not allowed in description items
2659                 code = NEWPAGE_CODE;
2660                 enable = !inDescriptionItem(cur);
2661                 break;
2662
2663         case LFUN_DATE_INSERT: {
2664                 string const format = cmd.argument().empty()
2665                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2666                 enable = support::os::is_valid_strftime(format);
2667                 break;
2668         }
2669
2670         case LFUN_LANGUAGE:
2671                 enable = !cur.paragraph().isPassThru();
2672                 flag.setOnOff(to_utf8(cmd.argument()) == cur.real_current_font.language()->lang());
2673                 break;
2674
2675         case LFUN_BREAK_PARAGRAPH:
2676                 enable = cur.inset().getLayout().isMultiPar();
2677                 break;
2678         
2679         case LFUN_SPELLING_ADD:
2680         case LFUN_SPELLING_IGNORE:
2681         case LFUN_SPELLING_REMOVE:
2682                 enable = theSpellChecker();
2683                 break;
2684
2685         case LFUN_LAYOUT:
2686                 enable = !cur.inset().forcePlainLayout();
2687                 break;
2688                 
2689         case LFUN_LAYOUT_PARAGRAPH:
2690         case LFUN_PARAGRAPH_PARAMS:
2691         case LFUN_PARAGRAPH_PARAMS_APPLY:
2692         case LFUN_PARAGRAPH_UPDATE:
2693                 enable = cur.inset().allowParagraphCustomization();
2694                 break;
2695
2696         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
2697         case LFUN_ACCENT_ACUTE:
2698         case LFUN_ACCENT_BREVE:
2699         case LFUN_ACCENT_CARON:
2700         case LFUN_ACCENT_CEDILLA:
2701         case LFUN_ACCENT_CIRCLE:
2702         case LFUN_ACCENT_CIRCUMFLEX:
2703         case LFUN_ACCENT_DOT:
2704         case LFUN_ACCENT_GRAVE:
2705         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2706         case LFUN_ACCENT_MACRON:
2707         case LFUN_ACCENT_OGONEK:
2708         case LFUN_ACCENT_TIE:
2709         case LFUN_ACCENT_TILDE:
2710         case LFUN_ACCENT_UMLAUT:
2711         case LFUN_ACCENT_UNDERBAR:
2712         case LFUN_ACCENT_UNDERDOT:
2713         case LFUN_FONT_DEFAULT:
2714         case LFUN_FONT_FRAK:
2715         case LFUN_FONT_SIZE:
2716         case LFUN_FONT_STATE:
2717         case LFUN_FONT_UNDERLINE:
2718         case LFUN_FONT_STRIKEOUT:
2719         case LFUN_FONT_UULINE:
2720         case LFUN_FONT_UWAVE:
2721         case LFUN_TEXTSTYLE_APPLY:
2722         case LFUN_TEXTSTYLE_UPDATE:
2723                 enable = !cur.paragraph().isPassThru();
2724                 break;
2725
2726         case LFUN_WORD_DELETE_FORWARD:
2727         case LFUN_WORD_DELETE_BACKWARD:
2728         case LFUN_LINE_DELETE:
2729         case LFUN_WORD_FORWARD:
2730         case LFUN_WORD_BACKWARD:
2731         case LFUN_WORD_RIGHT:
2732         case LFUN_WORD_LEFT:
2733         case LFUN_CHAR_FORWARD:
2734         case LFUN_CHAR_FORWARD_SELECT:
2735         case LFUN_CHAR_BACKWARD:
2736         case LFUN_CHAR_BACKWARD_SELECT:
2737         case LFUN_CHAR_LEFT:
2738         case LFUN_CHAR_LEFT_SELECT:
2739         case LFUN_CHAR_RIGHT:
2740         case LFUN_CHAR_RIGHT_SELECT:
2741         case LFUN_UP:
2742         case LFUN_UP_SELECT:
2743         case LFUN_DOWN:
2744         case LFUN_DOWN_SELECT:
2745         case LFUN_PARAGRAPH_UP_SELECT:
2746         case LFUN_PARAGRAPH_DOWN_SELECT:
2747         case LFUN_LINE_BEGIN_SELECT:
2748         case LFUN_LINE_END_SELECT:
2749         case LFUN_WORD_FORWARD_SELECT:
2750         case LFUN_WORD_BACKWARD_SELECT:
2751         case LFUN_WORD_RIGHT_SELECT:
2752         case LFUN_WORD_LEFT_SELECT:
2753         case LFUN_WORD_SELECT:
2754         case LFUN_SECTION_SELECT:
2755         case LFUN_BUFFER_BEGIN:
2756         case LFUN_BUFFER_END:
2757         case LFUN_BUFFER_BEGIN_SELECT:
2758         case LFUN_BUFFER_END_SELECT:
2759         case LFUN_INSET_BEGIN:
2760         case LFUN_INSET_END:
2761         case LFUN_INSET_BEGIN_SELECT:
2762         case LFUN_INSET_END_SELECT:
2763         case LFUN_INSET_SELECT_ALL:
2764         case LFUN_PARAGRAPH_UP:
2765         case LFUN_PARAGRAPH_DOWN:
2766         case LFUN_LINE_BEGIN:
2767         case LFUN_LINE_END:
2768         case LFUN_CHAR_DELETE_FORWARD:
2769         case LFUN_CHAR_DELETE_BACKWARD:
2770         case LFUN_WORD_UPCASE:
2771         case LFUN_WORD_LOWCASE:
2772         case LFUN_WORD_CAPITALIZE:
2773         case LFUN_CHARS_TRANSPOSE:
2774         case LFUN_SERVER_GET_XY:
2775         case LFUN_SERVER_SET_XY:
2776         case LFUN_SERVER_GET_LAYOUT:
2777         case LFUN_SELF_INSERT:
2778         case LFUN_UNICODE_INSERT:
2779         case LFUN_THESAURUS_ENTRY:
2780         case LFUN_ESCAPE:
2781                 // these are handled in our dispatch()
2782                 enable = true;
2783                 break;
2784
2785         case LFUN_INSET_INSERT: {
2786                 string const type = cmd.getArg(0);
2787                 if (type == "toc") {
2788                         code = TOC_CODE;
2789                         // not allowed in description items
2790                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
2791                         enable = !inDescriptionItem(cur);
2792                 } else {
2793                         enable = true;
2794                 }
2795                 break;
2796         }
2797
2798         default:
2799                 return false;
2800         }
2801
2802         if (code != NO_CODE
2803             && (cur.empty() 
2804                 || !cur.inset().insetAllowed(code)
2805                 || cur.paragraph().layout().pass_thru))
2806                 enable = false;
2807
2808         flag.setEnabled(enable);
2809         return true;
2810 }
2811
2812
2813 void Text::pasteString(Cursor & cur, docstring const & clip,
2814                 bool asParagraphs)
2815 {
2816         cur.clearSelection();
2817         if (!clip.empty()) {
2818                 cur.recordUndo();
2819                 if (asParagraphs)
2820                         insertStringAsParagraphs(cur, clip, cur.current_font);
2821                 else
2822                         insertStringAsLines(cur, clip, cur.current_font);
2823         }
2824 }
2825
2826
2827 // FIXME: an item inset would make things much easier.
2828 bool Text::inDescriptionItem(Cursor & cur) const
2829 {
2830         Paragraph & par = cur.paragraph();
2831         pos_type const pos = cur.pos();
2832         pos_type const body_pos = par.beginOfBody();
2833
2834         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2835             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2836                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2837                 return false;
2838
2839         return (pos < body_pos
2840                 || (pos == body_pos
2841                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2842 }
2843
2844 } // namespace lyx