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