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