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