]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Fix InsetQuotes creation. Not very clean but it does the job. Andre, I think we shoul...
[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 "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyXFunc.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include "insets/InsetCollapsable.h"
53 #include "insets/InsetCommand.h"
54 #include "insets/InsetFloatList.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetQuotes.h"
57 #include "insets/InsetSpecialChar.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetInfo.h"
60
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/lstrings.h"
65 #include "support/lyxtime.h"
66
67 #include "mathed/InsetMathHull.h"
68 #include "mathed/MathMacroTemplate.h"
69
70 #include <boost/next_prior.hpp>
71
72 #include <clocale>
73 #include <sstream>
74
75 using namespace std;
76 using namespace lyx::support;
77
78 namespace lyx {
79
80 using cap::copySelection;
81 using cap::cutSelection;
82 using cap::pasteFromStack;
83 using cap::pasteClipboardText;
84 using cap::pasteClipboardGraphics;
85 using cap::replaceSelection;
86
87 // globals...
88 static Font freefont(ignore_font, ignore_language);
89 static bool toggleall = false;
90
91 static void toggleAndShow(Cursor & cur, Text * text,
92         Font const & font, bool toggleall = true)
93 {
94         text->toggleFree(cur, font, toggleall);
95
96         if (font.language() != ignore_language ||
97             font.fontInfo().number() != FONT_IGNORE) {
98                 TextMetrics const & tm = cur.bv().textMetrics(text);
99                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
100                                                        cur.real_current_font))
101                         text->setCursor(cur, cur.pit(), cur.pos(),
102                                         false, !cur.boundary());
103         }
104 }
105
106
107 static void moveCursor(Cursor & cur, bool selecting)
108 {
109         if (selecting || cur.mark())
110                 cur.setSelection();
111 }
112
113
114 static void finishChange(Cursor & cur, bool selecting)
115 {
116         cur.finishUndo();
117         moveCursor(cur, selecting);
118 }
119
120
121 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
122 {
123         cur.recordUndo();
124         docstring sel = cur.selectionAsString(false);
125
126         // It may happen that sel is empty but there is a selection
127         replaceSelection(cur);
128
129         if (sel.empty()) {
130 #ifdef ENABLE_ASSERTIONS
131                 const int old_pos = cur.pos();
132 #endif
133                 cur.insert(new InsetMathHull(hullSimple));
134                 BOOST_ASSERT(old_pos == cur.pos());
135                 cur.nextInset()->edit(cur, true);
136                 // don't do that also for LFUN_MATH_MODE
137                 // unless you want end up with always changing
138                 // to mathrm when opening an inlined inset --
139                 // I really hate "LyXfunc overloading"...
140                 if (display)
141                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
142                 // Avoid an unnecessary undo step if cmd.argument
143                 // is empty
144                 if (!cmd.argument().empty())
145                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
146                                                  cmd.argument()));
147         } else {
148                 // create a macro if we see "\\newcommand"
149                 // somewhere, and an ordinary formula
150                 // otherwise
151                 if (sel.find(from_ascii("\\newcommand")) == string::npos
152                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
153                                 && sel.find(from_ascii("\\def")) == string::npos)
154                 {
155                         InsetMathHull * formula = new InsetMathHull;
156                         istringstream is(to_utf8(sel));
157                         Lexer lex(0, 0);
158                         lex.setStream(is);
159                         formula->read(lex);
160                         if (formula->getType() == hullNone)
161                                 // Don't create pseudo formulas if
162                                 // delimiters are left out
163                                 formula->mutate(hullSimple);
164                         cur.insert(formula);
165                 } else {
166                         cur.insert(new MathMacroTemplate(sel));
167                 }
168         }
169         cur.message(from_utf8(N_("Math editor mode")));
170 }
171
172
173 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
174 {
175         cur.recordUndo();
176         cap::replaceSelection(cur);
177         cur.insert(new InsetSpecialChar(kind));
178         cur.posForward();
179 }
180
181
182 static bool doInsertInset(Cursor & cur, Text * text,
183         FuncRequest const & cmd, bool edit, bool pastesel)
184 {
185         Buffer & buffer = cur.bv().buffer();
186         BufferParams const & bparams = buffer.params();
187         Inset * inset = createInset(buffer, cmd);
188         if (!inset)
189                 return false;
190
191         if (InsetCollapsable * ci = inset->asInsetCollapsable())
192                 ci->setLayout(bparams);
193
194         cur.recordUndo();
195         if (cmd.action == LFUN_INDEX_INSERT) {
196                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
197                 text->insertInset(cur, inset);
198                 if (edit)
199                         inset->edit(cur, true);
200                 // Now put this into inset
201                 static_cast<InsetCollapsable *>(inset)->text_.insertStringAsParagraphs(cur, ds);
202                 return true;
203         }
204
205         bool gotsel = false;
206         if (cur.selection()) {
207                 lyx::dispatch(FuncRequest(LFUN_CUT));
208                 gotsel = true;
209         }
210         text->insertInset(cur, inset);
211
212         if (edit)
213                 inset->edit(cur, true);
214
215         if (!gotsel || !pastesel)
216                 return true;
217
218         lyx::dispatch(FuncRequest(LFUN_PASTE, "0"));
219         InsetText * insetText = dynamic_cast<InsetText *>(inset);
220         if (insetText && !insetText->allowMultiPar() || cur.lastpit() == 0) {
221                 // reset first par to default
222                 cur.text()->paragraphs().begin()
223                         ->setEmptyOrDefaultLayout(bparams.documentClass());
224                 cur.pos() = 0;
225                 cur.pit() = 0;
226                 // Merge multiple paragraphs -- hack
227                 while (cur.lastpit() > 0)
228                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
229         } else {
230                 // reset surrounding par to default
231                 docstring const layoutname = insetText->useEmptyLayout()
232                         ? bparams.documentClass().emptyLayoutName()
233                         : bparams.documentClass().defaultLayoutName();
234                 cur.leaveInset(*inset);
235                 text->setLayout(cur, layoutname);
236         }
237
238         return true;
239 }
240
241
242 string const freefont2string()
243 {
244         return freefont.toString(toggleall);
245 }
246
247
248 /// the type of outline operation
249 enum OutlineOp {
250         OutlineUp, // Move this header with text down
251         OutlineDown,   // Move this header with text up
252         OutlineIn, // Make this header deeper
253         OutlineOut // Make this header shallower
254 };
255
256
257 static void outline(OutlineOp mode, Cursor & cur)
258 {
259         Buffer & buf = cur.buffer();
260         pit_type & pit = cur.pit();
261         ParagraphList & pars = buf.text().paragraphs();
262         ParagraphList::iterator bgn = pars.begin();
263         // The first paragraph of the area to be copied:
264         ParagraphList::iterator start = boost::next(bgn, pit);
265         // The final paragraph of area to be copied:
266         ParagraphList::iterator finish = start;
267         ParagraphList::iterator end = pars.end();
268
269         DocumentClass const & tc = buf.params().documentClass();
270
271         int const thistoclevel = start->layout()->toclevel;
272         int toclevel;
273         switch (mode) {
274                 case OutlineUp: {
275                         // Move out (down) from this section header
276                         if (finish != end)
277                                 ++finish;
278                         // Seek the one (on same level) below
279                         for (; finish != end; ++finish) {
280                                 toclevel = finish->layout()->toclevel;
281                                 if (toclevel != Layout::NOT_IN_TOC
282                                     && toclevel <= thistoclevel) {
283                                         break;
284                                 }
285                         }
286                         ParagraphList::iterator dest = start;
287                         // Move out (up) from this header
288                         if (dest == bgn)
289                                 break;
290                         // Search previous same-level header above
291                         do {
292                                 --dest;
293                                 toclevel = dest->layout()->toclevel;
294                         } while(dest != bgn
295                                 && (toclevel == Layout::NOT_IN_TOC
296                                     || toclevel > thistoclevel));
297                         // Not found; do nothing
298                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
299                                 break;
300                         pit_type const newpit = distance(bgn, dest);
301                         pit_type const len = distance(start, finish);
302                         pit_type const deletepit = pit + len;
303                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
304                         pars.insert(dest, start, finish);
305                         start = boost::next(pars.begin(), deletepit);
306                         pit = newpit;
307                         pars.erase(start, finish);
308                         break;
309                 }
310                 case OutlineDown: {
311                         // Go down out of current header:
312                         if (finish != end)
313                                 ++finish;
314                         // Find next same-level header:
315                         for (; finish != end; ++finish) {
316                                 toclevel = finish->layout()->toclevel;
317                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
318                                         break;
319                         }
320                         ParagraphList::iterator dest = finish;
321                         // Go one down from *this* header:
322                         if (dest != end)
323                                 ++dest;
324                         else
325                                 break;
326                         // Go further down to find header to insert in front of:
327                         for (; dest != end; ++dest) {
328                                 toclevel = dest->layout()->toclevel;
329                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
330                                         break;
331                         }
332                         // One such was found:
333                         pit_type newpit = distance(bgn, dest);
334                         pit_type const len = distance(start, finish);
335                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
336                         pars.insert(dest, start, finish);
337                         start = boost::next(bgn, pit);
338                         pit = newpit - len;
339                         pars.erase(start, finish);
340                         break;
341                 }
342                 case OutlineIn:
343                         buf.undo().recordUndo(cur);
344                         for (size_t i = 0; i != tc.layoutCount(); ++i) {
345                                 LayoutPtr const & lt = tc.layout(i);
346                                 if (lt->toclevel == thistoclevel + 1 &&
347                                     start->layout()->labeltype == lt->labeltype) {
348                                         start->setLayout(lt);
349                                         break;
350                                 }
351                         }
352                         break;
353                 case OutlineOut:
354                         buf.undo().recordUndo(cur);
355                         for (size_t i = 0; i != tc.layoutCount(); ++i) {
356                                 LayoutPtr const & lt = tc.layout(i);
357                                 if (lt->toclevel == thistoclevel - 1 &&
358                                     start->layout()->labeltype == lt->labeltype) {
359                                         start->setLayout(lt);
360                                         break;
361                                 }
362                         }
363                         break;
364                 default:
365                         break;
366         }
367 }
368
369
370 void Text::number(Cursor & cur)
371 {
372         FontInfo font = ignore_font;
373         font.setNumber(FONT_TOGGLE);
374         toggleAndShow(cur, this, Font(font, ignore_language));
375 }
376
377
378 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
379 {
380         return par.isRTL(buffer.params());
381 }
382
383
384 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
385 {
386         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
387
388         BufferView * bv = &cur.bv();
389         TextMetrics & tm = bv->textMetrics(this);
390         if (!tm.contains(cur.pit()))
391                 lyx::dispatch(FuncRequest(LFUN_SCREEN_RECENTER));
392
393         // FIXME: We use the update flag to indicates wether a singlePar or a
394         // full screen update is needed. We reset it here but shall we restore it
395         // at the end?
396         cur.noUpdate();
397
398         BOOST_ASSERT(cur.text() == this);
399         CursorSlice oldTopSlice = cur.top();
400         bool oldBoundary = cur.boundary();
401         bool sel = cur.selection();
402         // Signals that, even if needsUpdate == false, an update of the
403         // cursor paragraph is required
404         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
405                 LyXAction::SingleParUpdate);
406         // Signals that a full-screen update is required
407         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
408                 LyXAction::NoUpdate) || singleParUpdate);
409
410         switch (cmd.action) {
411
412         case LFUN_PARAGRAPH_MOVE_DOWN: {
413                 pit_type const pit = cur.pit();
414                 recUndo(cur, pit, pit + 1);
415                 cur.finishUndo();
416                 swap(pars_[pit], pars_[pit + 1]);
417                 updateLabels(cur.buffer());
418                 needsUpdate = true;
419                 ++cur.pit();
420                 break;
421         }
422
423         case LFUN_PARAGRAPH_MOVE_UP: {
424                 pit_type const pit = cur.pit();
425                 recUndo(cur, pit - 1, pit);
426                 cur.finishUndo();
427                 swap(pars_[pit], pars_[pit - 1]);
428                 updateLabels(cur.buffer());
429                 --cur.pit();
430                 needsUpdate = true;
431                 break;
432         }
433
434         case LFUN_APPENDIX: {
435                 Paragraph & par = cur.paragraph();
436                 bool start = !par.params().startOfAppendix();
437
438 // FIXME: The code below only makes sense at top level.
439 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
440                 // ensure that we have only one start_of_appendix in this document
441                 // FIXME: this don't work for multipart document!
442                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
443                         if (pars_[tmp].params().startOfAppendix()) {
444                                 recUndo(cur, tmp);
445                                 pars_[tmp].params().startOfAppendix(false);
446                                 break;
447                         }
448                 }
449
450                 cur.recordUndo();
451                 par.params().startOfAppendix(start);
452
453                 // we can set the refreshing parameters now
454                 updateLabels(cur.buffer());
455                 break;
456         }
457
458         case LFUN_WORD_DELETE_FORWARD:
459                 if (cur.selection()) {
460                         cutSelection(cur, true, false);
461                 } else
462                         deleteWordForward(cur);
463                 finishChange(cur, false);
464                 break;
465
466         case LFUN_WORD_DELETE_BACKWARD:
467                 if (cur.selection()) {
468                         cutSelection(cur, true, false);
469                 } else
470                         deleteWordBackward(cur);
471                 finishChange(cur, false);
472                 break;
473
474         case LFUN_LINE_DELETE:
475                 if (cur.selection()) {
476                         cutSelection(cur, true, false);
477                 } else
478                         tm.deleteLineForward(cur);
479                 finishChange(cur, false);
480                 break;
481
482         case LFUN_BUFFER_BEGIN:
483         case LFUN_BUFFER_BEGIN_SELECT:
484                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
485                 if (cur.depth() == 1) {
486                         needsUpdate |= cursorTop(cur);
487                 } else {
488                         cur.undispatched();
489                 }
490                 cur.updateFlags(Update::FitCursor);
491                 break;
492
493         case LFUN_BUFFER_END:
494         case LFUN_BUFFER_END_SELECT:
495                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
496                 if (cur.depth() == 1) {
497                         needsUpdate |= cursorBottom(cur);
498                 } else {
499                         cur.undispatched();
500                 }
501                 cur.updateFlags(Update::FitCursor);
502                 break;
503
504         case LFUN_CHAR_FORWARD:
505         case LFUN_CHAR_FORWARD_SELECT:
506                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
507                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
508                 needsUpdate |= cursorForward(cur);
509
510                 if (!needsUpdate && oldTopSlice == cur.top()
511                                 && cur.boundary() == oldBoundary) {
512                         cur.undispatched();
513                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
514                 }
515                 break;
516
517         case LFUN_CHAR_BACKWARD:
518         case LFUN_CHAR_BACKWARD_SELECT:
519                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
520                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
521                 needsUpdate |= cursorBackward(cur);
522
523                 if (!needsUpdate && oldTopSlice == cur.top()
524                         && cur.boundary() == oldBoundary) {
525                         cur.undispatched();
526                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
527                 }
528                 break;
529
530         case LFUN_CHAR_LEFT:
531         case LFUN_CHAR_LEFT_SELECT:
532                 if (lyxrc.visual_cursor) {
533                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
534                         needsUpdate |= cursorVisLeft(cur);
535                         if (!needsUpdate && oldTopSlice == cur.top()
536                                         && cur.boundary() == oldBoundary) {
537                                 cur.undispatched();
538                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
539                         }
540                 } else {
541                         if (reverseDirectionNeeded(cur)) {
542                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
543                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
544                         } else {
545                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
546                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
547                         }
548                         dispatch(cur, cmd);
549                         return;
550                 }
551                 break;
552
553         case LFUN_CHAR_RIGHT:
554         case LFUN_CHAR_RIGHT_SELECT:
555                 if (lyxrc.visual_cursor) {
556                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
557                         needsUpdate |= cursorVisRight(cur);
558                         if (!needsUpdate && oldTopSlice == cur.top()
559                                         && cur.boundary() == oldBoundary) {
560                                 cur.undispatched();
561                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
562                         }
563                 } else {
564                         if (reverseDirectionNeeded(cur)) {
565                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
566                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
567                         } else {
568                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
569                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
570                         }
571                         dispatch(cur, cmd);
572                         return;
573                 }
574                 break;
575                 
576
577         case LFUN_UP_SELECT:
578         case LFUN_DOWN_SELECT:
579         case LFUN_UP:
580         case LFUN_DOWN: {
581                 // stop/start the selection
582                 bool select = cmd.action == LFUN_DOWN_SELECT ||
583                         cmd.action == LFUN_UP_SELECT;
584                 cur.selHandle(select);
585                 
586                 // move cursor up/down
587                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
588                 bool const successful = cur.upDownInText(up, needsUpdate);
589                 if (successful) {
590                         // redraw if you leave mathed (for the decorations)
591                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
592                 } else
593                         cur.undispatched();
594                 
595                 break;
596         }
597
598         case LFUN_PARAGRAPH_UP:
599         case LFUN_PARAGRAPH_UP_SELECT:
600                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
601                 needsUpdate |= cursorUpParagraph(cur);
602                 break;
603
604         case LFUN_PARAGRAPH_DOWN:
605         case LFUN_PARAGRAPH_DOWN_SELECT:
606                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
607                 needsUpdate |= cursorDownParagraph(cur);
608                 break;
609
610         case LFUN_SCREEN_UP_SELECT:
611                 needsUpdate |= cur.selHandle(true);
612                 if (cur.pit() == 0 && cur.textRow().pos() == 0)
613                         cur.undispatched();
614                 else {
615                         tm.cursorPrevious(cur);
616                 }
617                 break;
618
619         case LFUN_SCREEN_DOWN_SELECT:
620                 needsUpdate |= cur.selHandle(true);
621                 if (cur.pit() == cur.lastpit()
622                           && cur.textRow().endpos() == cur.lastpos())
623                         cur.undispatched();
624                 else {
625                         tm.cursorNext(cur);
626                 }
627                 break;
628
629         case LFUN_LINE_BEGIN:
630         case LFUN_LINE_BEGIN_SELECT:
631                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
632                 needsUpdate |= tm.cursorHome(cur);
633                 break;
634
635         case LFUN_LINE_END:
636         case LFUN_LINE_END_SELECT:
637                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
638                 needsUpdate |= tm.cursorEnd(cur);
639                 break;
640
641         case LFUN_WORD_RIGHT:
642         case LFUN_WORD_RIGHT_SELECT:
643                 //FIXME: for visual cursor mode, really move right
644                 if (reverseDirectionNeeded(cur)) {
645                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
646                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
647                 } else {
648                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
649                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
650                 }
651                 dispatch(cur, cmd);
652                 return;
653
654         case LFUN_WORD_FORWARD:
655         case LFUN_WORD_FORWARD_SELECT:
656                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
657                 needsUpdate |= cursorForwardOneWord(cur);
658                 break;
659
660         case LFUN_WORD_LEFT:
661         case LFUN_WORD_LEFT_SELECT:
662                 //FIXME: for visual cursor mode, really move left
663                 if (reverseDirectionNeeded(cur)) {
664                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
665                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
666                 } else {
667                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
668                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
669                 }
670                 dispatch(cur, cmd);
671                 return;
672
673         case LFUN_WORD_BACKWARD:
674         case LFUN_WORD_BACKWARD_SELECT:
675                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
676                 needsUpdate |= cursorBackwardOneWord(cur);
677                 break;
678
679         case LFUN_WORD_SELECT: {
680                 selectWord(cur, WHOLE_WORD);
681                 finishChange(cur, true);
682                 break;
683         }
684
685         case LFUN_NEW_LINE: {
686                 // Not allowed by LaTeX (labels or empty par)
687                 if (cur.pos() > cur.paragraph().beginOfBody()) {
688                         // this avoids a double undo
689                         // FIXME: should not be needed, ideally
690                         if (!cur.selection())
691                                 cur.recordUndo();
692                         cap::replaceSelection(cur);
693                         cur.insert(new InsetNewline);
694                         cur.posForward();
695                         moveCursor(cur, false);
696                 }
697                 break;
698         }
699         
700         case LFUN_LINE_BREAK: {
701                 // Not allowed by LaTeX (labels or empty par)
702                 if (cur.pos() > cur.paragraph().beginOfBody()) {
703                         // this avoids a double undo
704                         // FIXME: should not be needed, ideally
705                         if (!cur.selection())
706                                 cur.recordUndo();
707                         cap::replaceSelection(cur);
708                         cur.insert(new InsetLinebreak);
709                         cur.posForward();
710                         moveCursor(cur, false);
711                 }
712                 break;
713         }
714
715         case LFUN_CHAR_DELETE_FORWARD:
716                 if (!cur.selection()) {
717                         if (cur.pos() == cur.paragraph().size())
718                                 // Par boundary, force full-screen update
719                                 singleParUpdate = false;
720                         needsUpdate |= erase(cur);
721                         cur.resetAnchor();
722                         // It is possible to make it a lot faster still
723                         // just comment out the line below...
724                 } else {
725                         cutSelection(cur, true, false);
726                         singleParUpdate = false;
727                 }
728                 moveCursor(cur, false);
729                 break;
730
731         case LFUN_DELETE_FORWARD_SKIP:
732                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
733                 if (!cur.selection()) {
734                         if (cur.pos() == cur.lastpos()) {
735                                 cursorForward(cur);
736                                 cursorBackward(cur);
737                         }
738                         erase(cur);
739                         cur.resetAnchor();
740                 } else {
741                         cutSelection(cur, true, false);
742                 }
743                 break;
744
745
746         case LFUN_CHAR_DELETE_BACKWARD:
747                 if (!cur.selection()) {
748                         if (bv->getIntl().getTransManager().backspace()) {
749                                 // Par boundary, full-screen update
750                                 if (cur.pos() == 0)
751                                         singleParUpdate = false;
752                                 needsUpdate |= backspace(cur);
753                                 cur.resetAnchor();
754                                 // It is possible to make it a lot faster still
755                                 // just comment out the line below...
756                         }
757                 } else {
758                         cutSelection(cur, true, false);
759                         singleParUpdate = false;
760                 }
761                 break;
762
763         case LFUN_DELETE_BACKWARD_SKIP:
764                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
765                 if (!cur.selection()) {
766                         // FIXME: look here
767                         //CursorSlice cur = cursor();
768                         backspace(cur);
769                         //anchor() = cur;
770                 } else {
771                         cutSelection(cur, true, false);
772                 }
773                 break;
774
775         case LFUN_BREAK_PARAGRAPH:
776                 cap::replaceSelection(cur);
777                 breakParagraph(cur, cmd.argument() == "inverse");
778                 cur.resetAnchor();
779                 break;
780
781         case LFUN_BREAK_PARAGRAPH_SKIP: {
782                 // When at the beginning of a paragraph, remove
783                 // indentation.  Otherwise, do the same as LFUN_BREAK_PARAGRAPH.
784                 cap::replaceSelection(cur);
785                 if (cur.pos() == 0)
786                         cur.paragraph().params().labelWidthString(docstring());
787                 else
788                         breakParagraph(cur, false);
789                 cur.resetAnchor();
790                 break;
791         }
792
793         // TODO
794         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
795         // as its duties can be performed there. Should it be removed??
796         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
797         case LFUN_PARAGRAPH_SPACING: {
798                 Paragraph & par = cur.paragraph();
799                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
800                 string cur_value = "1.0";
801                 if (cur_spacing == Spacing::Other)
802                         cur_value = par.params().spacing().getValueAsString();
803
804                 istringstream is(to_utf8(cmd.argument()));
805                 string tmp;
806                 is >> tmp;
807                 Spacing::Space new_spacing = cur_spacing;
808                 string new_value = cur_value;
809                 if (tmp.empty()) {
810                         lyxerr << "Missing argument to `paragraph-spacing'"
811                                << endl;
812                 } else if (tmp == "single") {
813                         new_spacing = Spacing::Single;
814                 } else if (tmp == "onehalf") {
815                         new_spacing = Spacing::Onehalf;
816                 } else if (tmp == "double") {
817                         new_spacing = Spacing::Double;
818                 } else if (tmp == "other") {
819                         new_spacing = Spacing::Other;
820                         string tmpval = "0.0";
821                         is >> tmpval;
822                         lyxerr << "new_value = " << tmpval << endl;
823                         if (tmpval != "0.0")
824                                 new_value = tmpval;
825                 } else if (tmp == "default") {
826                         new_spacing = Spacing::Default;
827                 } else {
828                         lyxerr << to_utf8(_("Unknown spacing argument: "))
829                                << to_utf8(cmd.argument()) << endl;
830                 }
831                 if (cur_spacing != new_spacing || cur_value != new_value)
832                         par.params().spacing(Spacing(new_spacing, new_value));
833                 break;
834         }
835
836         case LFUN_INSET_INSERT: {
837                 cur.recordUndo();
838                 Inset * inset = createInset(bv->buffer(), cmd);
839                 if (inset) {
840                         // FIXME (Abdel 01/02/2006):
841                         // What follows would be a partial fix for bug 2154:
842                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
843                         // This automatically put the label inset _after_ a
844                         // numbered section. It should be possible to extend the mechanism
845                         // to any kind of LateX environement.
846                         // The correct way to fix that bug would be at LateX generation.
847                         // I'll let the code here for reference as it could be used for some
848                         // other feature like "automatic labelling".
849                         /*
850                         Paragraph & par = pars_[cur.pit()];
851                         if (inset->lyxCode() == LABEL_CODE
852                                 && par.layout()->labeltype == LABEL_COUNTER) {
853                                 // Go to the end of the paragraph
854                                 // Warning: Because of Change-Tracking, the last
855                                 // position is 'size()' and not 'size()-1':
856                                 cur.pos() = par.size();
857                                 // Insert a new paragraph
858                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
859                                 dispatch(cur, fr);
860                         }
861                         */
862                         if (cur.selection())
863                                 cutSelection(cur, true, false);
864                         insertInset(cur, inset);
865                         cur.posForward();
866                 }
867                 break;
868         }
869
870         case LFUN_INSET_DISSOLVE:
871                 needsUpdate |= dissolveInset(cur);
872                 break;
873
874         case LFUN_INSET_SETTINGS:
875                 cur.inset().showInsetDialog(bv);
876                 break;
877
878         case LFUN_SPACE_INSERT:
879                 if (cur.paragraph().layout()->free_spacing)
880                         insertChar(cur, ' ');
881                 else {
882                         doInsertInset(cur, this, cmd, false, false);
883                         cur.posForward();
884                 }
885                 moveCursor(cur, false);
886                 break;
887
888         case LFUN_SPECIALCHAR_INSERT: {
889                 string const name = to_utf8(cmd.argument());
890                 if (name == "hyphenation")
891                         specialChar(cur, InsetSpecialChar::HYPHENATION);
892                 else if (name == "ligature-break")
893                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
894                 else if (name == "slash")
895                         specialChar(cur, InsetSpecialChar::SLASH);
896                 else if (name == "nobreakdash")
897                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
898                 else if (name == "dots")
899                         specialChar(cur, InsetSpecialChar::LDOTS);
900                 else if (name == "end-of-sentence")
901                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
902                 else if (name == "menu-separator")
903                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
904                 else if (name.empty())
905                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
906                 else
907                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
908                 break;
909         }
910
911         case LFUN_WORD_UPCASE:
912                 changeCase(cur, text_uppercase);
913                 break;
914
915         case LFUN_WORD_LOWCASE:
916                 changeCase(cur, text_lowercase);
917                 break;
918
919         case LFUN_WORD_CAPITALIZE:
920                 changeCase(cur, text_capitalization);
921                 break;
922
923         case LFUN_CHARS_TRANSPOSE:
924                 charsTranspose(cur);
925                 break;
926
927         case LFUN_PASTE: {
928                 cur.message(_("Paste"));
929                 cap::replaceSelection(cur);
930
931                 // without argument?
932                 string const arg = to_utf8(cmd.argument());
933                 if (arg.empty()) {
934                         if (theClipboard().isInternal())
935                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
936                         else if (theClipboard().hasGraphicsContents())
937                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
938                         else
939                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
940                 } else if (isStrUnsignedInt(arg)) {
941                         // we have a numerical argument
942                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
943                                        convert<unsigned int>(arg));
944                 } else {
945                         Clipboard::GraphicsType type;
946                         if (arg == "pdf")
947                                 type = Clipboard::PdfGraphicsType;
948                         else if (arg == "png")
949                                 type = Clipboard::PngGraphicsType;
950                         else if (arg == "jpeg")
951                                 type = Clipboard::JpegGraphicsType;
952                         else if (arg == "linkback")
953                                 type = Clipboard::LinkBackGraphicsType;
954                         else
955                                 BOOST_ASSERT(false);
956
957                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
958                 }
959
960                 bv->buffer().errors("Paste");
961                 cur.clearSelection(); // bug 393
962                 cur.finishUndo();
963                 break;
964         }
965
966         case LFUN_CUT:
967                 cutSelection(cur, true, true);
968                 cur.message(_("Cut"));
969                 break;
970
971         case LFUN_COPY:
972                 copySelection(cur);
973                 cur.message(_("Copy"));
974                 break;
975
976         case LFUN_SERVER_GET_XY:
977                 cur.message(from_utf8(
978                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
979                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
980                 break;
981
982         case LFUN_SERVER_SET_XY: {
983                 int x = 0;
984                 int y = 0;
985                 istringstream is(to_utf8(cmd.argument()));
986                 is >> x >> y;
987                 if (!is)
988                         lyxerr << "SETXY: Could not parse coordinates in '"
989                                << to_utf8(cmd.argument()) << endl;
990                 else
991                         tm.setCursorFromCoordinates(cur, x, y);
992                 break;
993         }
994
995         case LFUN_SERVER_GET_FONT:
996                 if (cur.current_font.fontInfo().shape() == ITALIC_SHAPE)
997                         cur.message(from_ascii("E"));
998                 else if (cur.current_font.fontInfo().shape() == SMALLCAPS_SHAPE)
999                         cur.message(from_ascii("N"));
1000                 else
1001                         cur.message(from_ascii("0"));
1002                 break;
1003
1004         case LFUN_SERVER_GET_LAYOUT:
1005                 cur.message(cur.paragraph().layout()->name());
1006                 break;
1007
1008         case LFUN_LAYOUT: {
1009                 docstring layout = cmd.argument();
1010                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1011
1012                 Paragraph const & para = cur.paragraph();
1013                 docstring const old_layout = para.layout()->name();
1014                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1015
1016                 if (layout.empty())
1017                         layout = tclass.defaultLayoutName();
1018
1019                 if (para.forceEmptyLayout()) 
1020                         // in this case only the empty layout is allowed
1021                         layout = tclass.emptyLayoutName();
1022                 else if (para.useEmptyLayout()) {
1023                         // in this case, default layout maps to empty layout 
1024                         if (layout == tclass.defaultLayoutName())
1025                                 layout = tclass.emptyLayoutName();
1026                 } else { 
1027                         // otherwise, the empty layout maps to the default
1028                         if (layout == tclass.emptyLayoutName())
1029                                 layout = tclass.defaultLayoutName();
1030                 }
1031
1032                 bool hasLayout = tclass.hasLayout(layout);
1033
1034                 // If the entry is obsolete, use the new one instead.
1035                 if (hasLayout) {
1036                         docstring const & obs = tclass[layout]->obsoleted_by();
1037                         if (!obs.empty())
1038                                 layout = obs;
1039                 }
1040
1041                 if (!hasLayout) {
1042                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1043                                 from_utf8(N_(" not known")));
1044                         break;
1045                 }
1046
1047                 bool change_layout = (old_layout != layout);
1048
1049                 if (!change_layout && cur.selection() &&
1050                         cur.selBegin().pit() != cur.selEnd().pit())
1051                 {
1052                         pit_type spit = cur.selBegin().pit();
1053                         pit_type epit = cur.selEnd().pit() + 1;
1054                         while (spit != epit) {
1055                                 if (pars_[spit].layout()->name() != old_layout) {
1056                                         change_layout = true;
1057                                         break;
1058                                 }
1059                                 ++spit;
1060                         }
1061                 }
1062
1063                 if (change_layout)
1064                         setLayout(cur, layout);
1065
1066                 break;
1067         }
1068
1069         case LFUN_CLIPBOARD_PASTE:
1070                 cur.clearSelection();
1071                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1072                                cmd.argument() == "paragraph");
1073                 bv->buffer().errors("Paste");
1074                 break;
1075
1076         case LFUN_PRIMARY_SELECTION_PASTE:
1077                 pasteString(cur, theSelection().get(),
1078                             cmd.argument() == "paragraph");
1079                 break;
1080
1081         case LFUN_UNICODE_INSERT: {
1082                 if (cmd.argument().empty())
1083                         break;
1084                 docstring hexstring = cmd.argument();
1085                 if (isHex(hexstring)) {
1086                         char_type c = hexToInt(hexstring);
1087                         if (c >= 32 && c < 0x10ffff) {
1088                                 lyxerr << "Inserting c: " << c << endl;
1089                                 docstring s = docstring(1, c);
1090                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1091                         }
1092                 }
1093                 break;
1094         }
1095
1096         case LFUN_QUOTE_INSERT: {
1097                 Paragraph & par = cur.paragraph();
1098                 pos_type pos = cur.pos();
1099                 BufferParams const & bufparams = bv->buffer().params();
1100                 LayoutPtr const & style = par.layout();
1101                 if (!style->pass_thru
1102                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1103                         // this avoids a double undo
1104                         // FIXME: should not be needed, ideally
1105                         if (!cur.selection())
1106                                 cur.recordUndo();
1107                         cap::replaceSelection(cur);
1108                         pos = cur.pos();
1109                         char_type c;
1110                         if (pos == 0)
1111                                 c = ' ';
1112                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1113                                 c = ' ';
1114                         else
1115                                 c = par.getChar(pos - 1);
1116                         string arg = to_utf8(cmd.argument());
1117                         InsetQuotes * iq;
1118                         if (arg == "single")
1119                                 iq = new InsetQuotes(c, bufparams.quotes_language,
1120                                         InsetQuotes::SingleQ);
1121                         else
1122                                 iq = new InsetQuotes(c, bufparams.quotes_language,
1123                                         InsetQuotes::DoubleQ);
1124                         iq->setBuffer(bv->buffer());
1125                         cur.insert(iq);
1126                         cur.posForward();
1127                 }
1128                 else
1129                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1130                 break;
1131         }
1132
1133         case LFUN_DATE_INSERT: {
1134                 string const format = cmd.argument().empty()
1135                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1136                 string const time = formatted_time(current_time(), format);
1137                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1138                 break;
1139         }
1140
1141         case LFUN_MOUSE_TRIPLE:
1142                 if (cmd.button() == mouse_button::button1) {
1143                         tm.cursorHome(cur);
1144                         cur.resetAnchor();
1145                         tm.cursorEnd(cur);
1146                         cur.setSelection();
1147                         bv->cursor() = cur;
1148                 }
1149                 break;
1150
1151         case LFUN_MOUSE_DOUBLE:
1152                 if (cmd.button() == mouse_button::button1) {
1153                         selectWord(cur, WHOLE_WORD_STRICT);
1154                         bv->cursor() = cur;
1155                 }
1156                 break;
1157
1158         // Single-click on work area
1159         case LFUN_MOUSE_PRESS: {
1160                 // Right click on a footnote flag opens float menu
1161                 // FIXME: Why should we clear the selection in this case?
1162                 if (cmd.button() == mouse_button::button3)
1163                         cur.clearSelection();
1164
1165                 bool do_selection = cmd.button() == mouse_button::button1
1166                         && cmd.argument() == "region-select";
1167                 // Set the cursor
1168                 bool update = bv->mouseSetCursor(cur, do_selection);
1169
1170                 // Insert primary selection with middle mouse
1171                 // if there is a local selection in the current buffer,
1172                 // insert this
1173                 if (cmd.button() == mouse_button::button2) {
1174                         if (cap::selection()) {
1175                                 // Copy the selection buffer to the clipboard
1176                                 // stack, because we want it to appear in the
1177                                 // "Edit->Paste recent" menu.
1178                                 cap::copySelectionToStack();
1179
1180                                 cap::pasteSelection(bv->cursor(), 
1181                                                     bv->buffer().errorList("Paste"));
1182                                 bv->buffer().errors("Paste");
1183                                 bv->buffer().markDirty();
1184                                 bv->cursor().finishUndo();
1185                         } else {
1186                                 lyx::dispatch(FuncRequest(LFUN_PRIMARY_SELECTION_PASTE, "paragraph"));
1187                         }
1188                 }
1189
1190                 // we have to update after dEPM triggered
1191                 if (!update && cmd.button() == mouse_button::button1) {
1192                         needsUpdate = false;
1193                         cur.noUpdate();
1194                 }
1195
1196                 break;
1197         }
1198
1199         case LFUN_MOUSE_MOTION: {
1200                 // Only use motion with button 1
1201                 //if (cmd.button() != mouse_button::button1)
1202                 //      return false;
1203
1204                 // ignore motions deeper nested than the real anchor
1205                 Cursor & bvcur = cur.bv().cursor();
1206                 if (!bvcur.anchor_.hasPart(cur)) {
1207                         cur.undispatched();
1208                         break;
1209                 }
1210                 CursorSlice old = bvcur.top();
1211
1212                 int const wh = bv->workHeight();
1213                 int const y = max(0, min(wh - 1, cmd.y));
1214
1215                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1216                 cur.setTargetX(cmd.x);
1217                 if (cmd.y >= wh)
1218                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1219                 else if (cmd.y < 0)
1220                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1221                 // This is to allow jumping over large insets
1222                 if (cur.top() == old) {
1223                         if (cmd.y >= wh)
1224                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1225                         else if (cmd.y < 0)
1226                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1227                 }
1228
1229                 if (cur.top() == old)
1230                         cur.noUpdate();
1231                 else {
1232                         // FIXME: This is brute force! But without it the selected
1233                         // area is not corrected updated while moving the mouse.
1234                         cur.updateFlags(Update::Force | Update::FitCursor);
1235                         // don't set anchor_
1236                         bvcur.setCursor(cur);
1237                         bvcur.selection() = true;
1238                         //lyxerr << "MOTION: " << bv->cursor() << endl;
1239                 }
1240                 break;
1241         }
1242
1243         case LFUN_MOUSE_RELEASE: {
1244                 if (cmd.button() == mouse_button::button2)
1245                         break;
1246
1247                 if (cmd.button() == mouse_button::button1) {
1248                         // if there is new selection, update persistent
1249                         // selection, otherwise, single click does not
1250                         // clear persistent selection buffer
1251                         if (cur.selection()) {
1252                                 // finish selection
1253                                 // if double click, cur is moved to the end of word by selectWord
1254                                 // but bvcur is current mouse position
1255                                 Cursor & bvcur = cur.bv().cursor();
1256                                 bvcur.selection() = true;
1257                         }
1258                         needsUpdate = false;
1259                         cur.noUpdate();
1260                 }
1261
1262                 break;
1263         }
1264
1265         case LFUN_SELF_INSERT: {
1266                 if (cmd.argument().empty())
1267                         break;
1268
1269                 // Automatically delete the currently selected
1270                 // text and replace it with what is being
1271                 // typed in now. Depends on lyxrc settings
1272                 // "auto_region_delete", which defaults to
1273                 // true (on).
1274
1275                 if (lyxrc.auto_region_delete && cur.selection())
1276                         cutSelection(cur, false, false);
1277
1278                 cur.clearSelection();
1279                 Font const old_font = cur.real_current_font;
1280
1281                 docstring::const_iterator cit = cmd.argument().begin();
1282                 docstring::const_iterator end = cmd.argument().end();
1283                 for (; cit != end; ++cit)
1284                         bv->translateAndInsert(*cit, this, cur);
1285
1286                 cur.resetAnchor();
1287                 moveCursor(cur, false);
1288                 break;
1289         }
1290
1291         case LFUN_HYPERLINK_INSERT: {
1292                 InsetCommandParams p(HYPERLINK_CODE);
1293                 docstring content;
1294                 if (cur.selection()) {
1295                         content = cur.selectionAsString(false);
1296                         cutSelection(cur, true, false);
1297                 }
1298                 p["target"] = (cmd.argument().empty()) ?
1299                         content : cmd.argument();
1300                 string const data = InsetCommandMailer::params2string("href", p);
1301                 if (p["target"].empty()) {
1302                         bv->showDialog("href", data);
1303                 } else {
1304                         FuncRequest fr(LFUN_INSET_INSERT, data);
1305                         dispatch(cur, fr);
1306                 }
1307                 break;
1308         }
1309
1310         case LFUN_LABEL_INSERT: {
1311                 InsetCommandParams p(LABEL_CODE);
1312                 // Try to generate a valid label
1313                 p["name"] = (cmd.argument().empty()) ?
1314                         cur.getPossibleLabel() :
1315                         cmd.argument();
1316                 string const data = InsetCommandMailer::params2string("label", p);
1317
1318                 if (cmd.argument().empty()) {
1319                         bv->showDialog("label", data);
1320                 } else {
1321                         FuncRequest fr(LFUN_INSET_INSERT, data);
1322                         dispatch(cur, fr);
1323                 }
1324                 break;
1325         }
1326
1327         case LFUN_INFO_INSERT: {
1328                 Inset * inset = createInset(cur.bv().buffer(), cmd);
1329                 if (!inset)
1330                         break;
1331                 // if an empty inset is created (cmd.argument() is empty)
1332                 // use current selection as parameter.
1333                 if (cmd.argument().empty() && cur.selection()) {
1334                         // use selected text as info to avoid a separate UI
1335                         docstring ds = cur.selectionAsString(false);
1336                         cutSelection(cur, true, false);
1337                         static_cast<InsetInfo *>(inset)->setInfo(to_utf8(ds));
1338                         static_cast<InsetInfo *>(inset)->updateInfo();
1339                 }
1340                 insertInset(cur, inset);
1341                 cur.posForward();
1342                 break;
1343         }
1344 #if 0
1345         case LFUN_LIST_INSERT:
1346         case LFUN_THEOREM_INSERT:
1347 #endif
1348         case LFUN_CAPTION_INSERT:
1349         case LFUN_FOOTNOTE_INSERT:
1350         case LFUN_NOTE_INSERT:
1351         case LFUN_FLEX_INSERT:
1352         case LFUN_BOX_INSERT:
1353         case LFUN_BRANCH_INSERT:
1354         case LFUN_BIBITEM_INSERT:
1355         case LFUN_ERT_INSERT:
1356         case LFUN_LISTING_INSERT:
1357         case LFUN_MARGINALNOTE_INSERT:
1358         case LFUN_OPTIONAL_INSERT:
1359         case LFUN_ENVIRONMENT_INSERT:
1360         case LFUN_INDEX_INSERT:
1361                 // Open the inset, and move the current selection
1362                 // inside it.
1363                 doInsertInset(cur, this, cmd, true, true);
1364                 cur.posForward();
1365                 // Some insets are numbered, others are shown in the outline pane so
1366                 // let's update the labels and the toc backend.
1367                 updateLabels(bv->buffer());
1368                 break;
1369
1370         case LFUN_TABULAR_INSERT:
1371                 // if there were no arguments, just open the dialog
1372                 if (doInsertInset(cur, this, cmd, false, true))
1373                         cur.posForward();
1374                 else
1375                         bv->showDialog("tabularcreate");
1376
1377                 break;
1378
1379         case LFUN_FLOAT_INSERT:
1380         case LFUN_FLOAT_WIDE_INSERT:
1381         case LFUN_WRAP_INSERT: {
1382                 bool content = cur.selection();  // will some text be moved into the inset?
1383
1384                 doInsertInset(cur, this, cmd, true, true);
1385                 cur.posForward();
1386                 ParagraphList & pars = cur.text()->paragraphs();
1387
1388                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1389
1390                 // add a separate paragraph for the caption inset
1391                 pars.push_back(Paragraph());
1392                 pars.back().setInsetOwner(pars[0].inInset());
1393                 pars.back().setEmptyOrDefaultLayout(tclass);
1394                 int cap_pit = pars.size() - 1;
1395
1396                 // if an empty inset was created, we create an additional empty
1397                 // paragraph at the bottom so that the user can choose where to put
1398                 // the graphics (or table).
1399                 if (!content) {
1400                         pars.push_back(Paragraph());
1401                         pars.back().setInsetOwner(pars[0].inInset());
1402                         pars.back().setEmptyOrDefaultLayout(tclass);
1403                 }
1404
1405                 // reposition the cursor to the caption
1406                 cur.pit() = cap_pit;
1407                 cur.pos() = 0;
1408                 // FIXME: This Text/Cursor dispatch handling is a mess!
1409                 // We cannot use Cursor::dispatch here it needs access to up to
1410                 // date metrics.
1411                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1412                 cur.text()->dispatch(cur, cmd_caption);
1413                 cur.updateFlags(Update::Force);
1414                 // FIXME: When leaving the Float (or Wrap) inset we should
1415                 // delete any empty paragraph left above or below the
1416                 // caption.
1417                 break;
1418         }
1419
1420         case LFUN_NOMENCL_INSERT: {
1421                 FuncRequest cmd1 = cmd;
1422                 if (cmd.argument().empty())
1423                         cmd1 = FuncRequest(cmd,
1424                                 bv->cursor().innerText()->getStringToIndex(bv->cursor()));
1425                 Inset * inset = createInset(cur.bv().buffer(), cmd1);
1426                 if (!inset)
1427                         break;
1428                 cur.recordUndo();
1429                 cur.clearSelection();
1430                 insertInset(cur, inset);
1431                 // Show the dialog for the nomenclature entry, since the
1432                 // description entry still needs to be filled in.
1433                 if (cmd.action == LFUN_NOMENCL_INSERT)
1434                         inset->edit(cur, true);
1435                 cur.posForward();
1436                 break;
1437         }
1438
1439         case LFUN_INDEX_PRINT:
1440         case LFUN_NOMENCL_PRINT:
1441         case LFUN_TOC_INSERT:
1442         case LFUN_HFILL_INSERT:
1443         case LFUN_LINE_INSERT:
1444         case LFUN_NEWPAGE_INSERT:
1445         case LFUN_PAGEBREAK_INSERT:
1446         case LFUN_CLEARPAGE_INSERT:
1447         case LFUN_CLEARDOUBLEPAGE_INSERT:
1448                 // do nothing fancy
1449                 doInsertInset(cur, this, cmd, false, false);
1450                 cur.posForward();
1451                 break;
1452
1453         case LFUN_DEPTH_DECREMENT:
1454                 changeDepth(cur, DEC_DEPTH);
1455                 break;
1456
1457         case LFUN_DEPTH_INCREMENT:
1458                 changeDepth(cur, INC_DEPTH);
1459                 break;
1460
1461         case LFUN_MATH_DISPLAY:
1462                 mathDispatch(cur, cmd, true);
1463                 break;
1464
1465         case LFUN_MATH_IMPORT_SELECTION:
1466         case LFUN_MATH_MODE:
1467                 if (cmd.argument() == "on")
1468                         // don't pass "on" as argument
1469                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1470                 else
1471                         mathDispatch(cur, cmd, false);
1472                 break;
1473
1474         case LFUN_MATH_MACRO:
1475                 if (cmd.argument().empty())
1476                         cur.errorMessage(from_utf8(N_("Missing argument")));
1477                 else {
1478                         string s = to_utf8(cmd.argument());
1479                         string const s1 = token(s, ' ', 1);
1480                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1481                         string const s2 = token(s, ' ', 2);
1482                         MacroType type = MacroTypeNewcommand;
1483                         if (s2 == "def")
1484                                 type = MacroTypeDef;
1485                         cur.insert(new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type));
1486                         //cur.nextInset()->edit(cur, true);
1487                 }
1488                 break;
1489
1490         // passthrough hat and underscore outside mathed:
1491         case LFUN_MATH_SUBSCRIPT:
1492                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1493                 break;
1494         case LFUN_MATH_SUPERSCRIPT:
1495                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1496                 break;
1497
1498         case LFUN_MATH_INSERT:
1499         case LFUN_MATH_MATRIX:
1500         case LFUN_MATH_DELIM:
1501         case LFUN_MATH_BIGDELIM: {
1502                 cap::replaceSelection(cur);
1503                 cur.insert(new InsetMathHull(hullSimple));
1504                 checkAndActivateInset(cur, true);
1505                 BOOST_ASSERT(cur.inMathed());
1506                 cur.dispatch(cmd);
1507                 break;
1508         }
1509
1510         case LFUN_FONT_EMPH: {
1511                 Font font(ignore_font, ignore_language);
1512                 font.fontInfo().setEmph(FONT_TOGGLE);
1513                 toggleAndShow(cur, this, font);
1514                 break;
1515         }
1516
1517         case LFUN_FONT_BOLD: {
1518                 Font font(ignore_font, ignore_language);
1519                 font.fontInfo().setSeries(BOLD_SERIES);
1520                 toggleAndShow(cur, this, font);
1521                 break;
1522         }
1523
1524         case LFUN_FONT_NOUN: {
1525                 Font font(ignore_font, ignore_language);
1526                 font.fontInfo().setNoun(FONT_TOGGLE);
1527                 toggleAndShow(cur, this, font);
1528                 break;
1529         }
1530
1531         case LFUN_FONT_TYPEWRITER: {
1532                 Font font(ignore_font, ignore_language);
1533                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1534                 toggleAndShow(cur, this, font);
1535                 break;
1536         }
1537
1538         case LFUN_FONT_SANS: {
1539                 Font font(ignore_font, ignore_language);
1540                 font.fontInfo().setFamily(SANS_FAMILY);
1541                 toggleAndShow(cur, this, font);
1542                 break;
1543         }
1544
1545         case LFUN_FONT_ROMAN: {
1546                 Font font(ignore_font, ignore_language);
1547                 font.fontInfo().setFamily(ROMAN_FAMILY);
1548                 toggleAndShow(cur, this, font);
1549                 break;
1550         }
1551
1552         case LFUN_FONT_DEFAULT: {
1553                 Font font(inherit_font, ignore_language);
1554                 toggleAndShow(cur, this, font);
1555                 break;
1556         }
1557
1558         case LFUN_FONT_UNDERLINE: {
1559                 Font font(ignore_font, ignore_language);
1560                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1561                 toggleAndShow(cur, this, font);
1562                 break;
1563         }
1564
1565         case LFUN_FONT_SIZE: {
1566                 Font font(ignore_font, ignore_language);
1567                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1568                 toggleAndShow(cur, this, font);
1569                 break;
1570         }
1571
1572         case LFUN_LANGUAGE: {
1573                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1574                 if (!lang)
1575                         break;
1576                 Font font(ignore_font, lang);
1577                 toggleAndShow(cur, this, font);
1578                 break;
1579         }
1580
1581         case LFUN_FONT_FREE_APPLY:
1582                 toggleAndShow(cur, this, freefont, toggleall);
1583                 cur.message(_("Character set"));
1584                 break;
1585
1586         // Set the freefont using the contents of \param data dispatched from
1587         // the frontends and apply it at the current cursor location.
1588         case LFUN_FONT_FREE_UPDATE: {
1589                 Font font;
1590                 bool toggle;
1591                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1592                         freefont = font;
1593                         toggleall = toggle;
1594                         toggleAndShow(cur, this, freefont, toggleall);
1595                         cur.message(_("Character set"));
1596                 } else {
1597                         lyxerr << "Argument not ok";
1598                 }
1599                 break;
1600         }
1601
1602         case LFUN_FINISHED_LEFT:
1603                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1604                 // We're leaving an inset, going left. If the inset is LTR, we're 
1605                 // leaving from the front, so we should not move (remain at --- but
1606                 // not in --- the inset). If the inset is RTL, move left, without 
1607                 // entering the inset itself; i.e., move to after the inset.
1608                 if (cur.paragraph().getFontSettings(
1609                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1610                         cursorVisLeft(cur, true);
1611                 break;
1612
1613         case LFUN_FINISHED_RIGHT:
1614                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1615                 // We're leaving an inset, going right. If the inset is RTL, we're 
1616                 // leaving from the front, so we should not move (remain at --- but
1617                 // not in --- the inset). If the inset is LTR, move right, without 
1618                 // entering the inset itself; i.e., move to after the inset.
1619                 if (!cur.paragraph().getFontSettings(
1620                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1621                         cursorVisRight(cur, true);
1622                 break;
1623
1624         case LFUN_FINISHED_BACKWARD:
1625                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1626                 break;
1627
1628         case LFUN_FINISHED_FORWARD:
1629                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1630                 ++cur.pos();
1631                 cur.setCurrentFont();
1632                 break;
1633
1634         case LFUN_LAYOUT_PARAGRAPH: {
1635                 string data;
1636                 params2string(cur.paragraph(), data);
1637                 data = "show\n" + data;
1638                 bv->showDialog("paragraph", data);
1639                 break;
1640         }
1641
1642         case LFUN_PARAGRAPH_UPDATE: {
1643                 string data;
1644                 params2string(cur.paragraph(), data);
1645
1646                 // Will the paragraph accept changes from the dialog?
1647                 bool const accept = 
1648                         cur.inset().allowParagraphCustomization(cur.idx());
1649
1650                 data = "update " + convert<string>(accept) + '\n' + data;
1651                 bv->updateDialog("paragraph", data);
1652                 break;
1653         }
1654
1655         case LFUN_ACCENT_UMLAUT:
1656         case LFUN_ACCENT_CIRCUMFLEX:
1657         case LFUN_ACCENT_GRAVE:
1658         case LFUN_ACCENT_ACUTE:
1659         case LFUN_ACCENT_TILDE:
1660         case LFUN_ACCENT_CEDILLA:
1661         case LFUN_ACCENT_MACRON:
1662         case LFUN_ACCENT_DOT:
1663         case LFUN_ACCENT_UNDERDOT:
1664         case LFUN_ACCENT_UNDERBAR:
1665         case LFUN_ACCENT_CARON:
1666         case LFUN_ACCENT_SPECIAL_CARON:
1667         case LFUN_ACCENT_BREVE:
1668         case LFUN_ACCENT_TIE:
1669         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1670         case LFUN_ACCENT_CIRCLE:
1671         case LFUN_ACCENT_OGONEK:
1672                 theLyXFunc().handleKeyFunc(cmd.action);
1673                 if (!cmd.argument().empty())
1674                         // FIXME: Are all these characters encoded in one byte in utf8?
1675                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1676                 break;
1677
1678         case LFUN_FLOAT_LIST: {
1679                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1680                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1681                         cur.recordUndo();
1682                         if (cur.selection())
1683                                 cutSelection(cur, true, false);
1684                         breakParagraph(cur);
1685
1686                         if (cur.lastpos() != 0) {
1687                                 cursorBackward(cur);
1688                                 breakParagraph(cur);
1689                         }
1690
1691                         //FIXME Check if this should be emptyLayout()
1692                         setLayout(cur, tclass.defaultLayoutName());
1693                         ParagraphParameters p;
1694                         setParagraphs(cur, p);
1695                         insertInset(cur, new InsetFloatList(to_utf8(cmd.argument())));
1696                         cur.posForward();
1697                 } else {
1698                         lyxerr << "Non-existent float type: "
1699                                << to_utf8(cmd.argument()) << endl;
1700                 }
1701                 break;
1702         }
1703
1704         case LFUN_CHANGE_ACCEPT: {
1705                 acceptOrRejectChanges(cur, ACCEPT);
1706                 break;
1707         }
1708
1709         case LFUN_CHANGE_REJECT: {
1710                 acceptOrRejectChanges(cur, REJECT);
1711                 break;
1712         }
1713
1714         case LFUN_THESAURUS_ENTRY: {
1715                 docstring arg = cmd.argument();
1716                 if (arg.empty()) {
1717                         arg = cur.selectionAsString(false);
1718                         // FIXME
1719                         if (arg.size() > 100 || arg.empty()) {
1720                                 // Get word or selection
1721                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1722                                 arg = cur.selectionAsString(false);
1723                         }
1724                 }
1725                 bv->showDialog("thesaurus", to_utf8(arg));
1726                 break;
1727         }
1728
1729         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1730                 // Given data, an encoding of the ParagraphParameters
1731                 // generated in the Paragraph dialog, this function sets
1732                 // the current paragraph, or currently selected paragraphs,
1733                 // appropriately. 
1734                 // NOTE: This function overrides all existing settings.
1735                 setParagraphs(cur, cmd.argument());
1736                 cur.message(_("Paragraph layout set"));
1737                 break;
1738         }
1739         
1740         case LFUN_PARAGRAPH_PARAMS: {
1741                 // Given data, an encoding of the ParagraphParameters as we'd
1742                 // find them in a LyX file, this function modifies the current paragraph, 
1743                 // or currently selected paragraphs. 
1744                 // NOTE: This function only modifies, and does not override, existing
1745                 // settings.
1746                 setParagraphs(cur, cmd.argument(), true);
1747                 cur.message(_("Paragraph layout set"));
1748                 break;
1749         }
1750
1751         case LFUN_ESCAPE:
1752                 if (cur.selection()) {
1753                         cur.selection() = false;
1754                 } else {
1755                         cur.undispatched();
1756                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1757                         // correct, but I'm not 100% sure -- dov, 071019
1758                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1759                 }
1760                 break;
1761
1762         case LFUN_OUTLINE_UP:
1763                 outline(OutlineUp, cur);
1764                 setCursor(cur, cur.pit(), 0);
1765                 updateLabels(cur.buffer());
1766                 needsUpdate = true;
1767                 break;
1768
1769         case LFUN_OUTLINE_DOWN:
1770                 outline(OutlineDown, cur);
1771                 setCursor(cur, cur.pit(), 0);
1772                 updateLabels(cur.buffer());
1773                 needsUpdate = true;
1774                 break;
1775
1776         case LFUN_OUTLINE_IN:
1777                 outline(OutlineIn, cur);
1778                 updateLabels(cur.buffer());
1779                 needsUpdate = true;
1780                 break;
1781
1782         case LFUN_OUTLINE_OUT:
1783                 outline(OutlineOut, cur);
1784                 updateLabels(cur.buffer());
1785                 needsUpdate = true;
1786                 break;
1787
1788         default:
1789                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1790                 cur.undispatched();
1791                 break;
1792         }
1793
1794         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1795
1796         // FIXME: The cursor flag is reset two lines below
1797         // so we need to check here if some of the LFUN did touch that.
1798         // for now only Text::erase() and Text::backspace() do that.
1799         // The plan is to verify all the LFUNs and then to remove this
1800         // singleParUpdate boolean altogether.
1801         if (cur.result().update() & Update::Force) {
1802                 singleParUpdate = false;
1803                 needsUpdate = true;
1804         }
1805
1806         // FIXME: the following code should go in favor of fine grained
1807         // update flag treatment.
1808         if (singleParUpdate) {
1809                 // Inserting characters does not change par height in general. So, try
1810                 // to update _only_ this paragraph. BufferView will detect if a full
1811                 // metrics update is needed anyway.
1812                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1813                 return;
1814         }
1815
1816         if (!needsUpdate
1817             && &oldTopSlice.inset() == &cur.inset()
1818             && oldTopSlice.idx() == cur.idx()
1819             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1820             && !cur.selection())
1821                 // FIXME: it would be better if we could just do this
1822                 //
1823                 //if (cur.result().update() != Update::FitCursor)
1824                 //      cur.noUpdate();
1825                 //
1826                 // But some LFUNs do not set Update::FitCursor when needed, so we
1827                 // do it for all. This is not very harmfull as FitCursor will provoke
1828                 // a full redraw only if needed but still, a proper review of all LFUN
1829                 // should be done and this needsUpdate boolean can then be removed.
1830                 cur.updateFlags(Update::FitCursor);
1831         else
1832                 cur.updateFlags(Update::Force | Update::FitCursor);
1833 }
1834
1835
1836 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1837                         FuncStatus & flag) const
1838 {
1839         BOOST_ASSERT(cur.text() == this);
1840
1841         Font const & font = cur.real_current_font;
1842         FontInfo const & fontinfo = font.fontInfo();
1843         bool enable = true;
1844         InsetCode code = NO_CODE;
1845
1846         switch (cmd.action) {
1847
1848         case LFUN_DEPTH_DECREMENT:
1849                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1850                 break;
1851
1852         case LFUN_DEPTH_INCREMENT:
1853                 enable = changeDepthAllowed(cur, INC_DEPTH);
1854                 break;
1855
1856         case LFUN_APPENDIX:
1857                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1858                 return true;
1859
1860         case LFUN_BIBITEM_INSERT:
1861                 enable = (cur.paragraph().layout()->labeltype == LABEL_BIBLIO
1862                           && cur.pos() == 0);
1863                 break;
1864
1865         case LFUN_DIALOG_SHOW_NEW_INSET:
1866                 if (cmd.argument() == "bibitem")
1867                         code = BIBITEM_CODE;
1868                 else if (cmd.argument() == "bibtex")
1869                         code = BIBTEX_CODE;
1870                 else if (cmd.argument() == "box")
1871                         code = BOX_CODE;
1872                 else if (cmd.argument() == "branch")
1873                         code = BRANCH_CODE;
1874                 else if (cmd.argument() == "citation")
1875                         code = CITE_CODE;
1876                 else if (cmd.argument() == "ert")
1877                         code = ERT_CODE;
1878                 else if (cmd.argument() == "external")
1879                         code = EXTERNAL_CODE;
1880                 else if (cmd.argument() == "float")
1881                         code = FLOAT_CODE;
1882                 else if (cmd.argument() == "graphics")
1883                         code = GRAPHICS_CODE;
1884                 else if (cmd.argument() == "href")
1885                         code = HYPERLINK_CODE;
1886                 else if (cmd.argument() == "include")
1887                         code = INCLUDE_CODE;
1888                 else if (cmd.argument() == "index")
1889                         code = INDEX_CODE;
1890                 else if (cmd.argument() == "nomenclature")
1891                         code = NOMENCL_CODE;
1892                 else if (cmd.argument() == "label")
1893                         code = LABEL_CODE;
1894                 else if (cmd.argument() == "note")
1895                         code = NOTE_CODE;
1896                 else if (cmd.argument() == "ref")
1897                         code = REF_CODE;
1898                 else if (cmd.argument() == "toc")
1899                         code = TOC_CODE;
1900                 else if (cmd.argument() == "vspace")
1901                         code = VSPACE_CODE;
1902                 else if (cmd.argument() == "wrap")
1903                         code = WRAP_CODE;
1904                 else if (cmd.argument() == "listings")
1905                         code = LISTINGS_CODE;
1906                 break;
1907
1908         case LFUN_ERT_INSERT:
1909                 code = ERT_CODE;
1910                 break;
1911         case LFUN_LISTING_INSERT:
1912             code = LISTINGS_CODE;
1913                 break;
1914         case LFUN_FOOTNOTE_INSERT:
1915                 code = FOOT_CODE;
1916                 break;
1917         case LFUN_TABULAR_INSERT:
1918                 code = TABULAR_CODE;
1919                 break;
1920         case LFUN_MARGINALNOTE_INSERT:
1921                 code = MARGIN_CODE;
1922                 break;
1923         case LFUN_FLOAT_INSERT:
1924         case LFUN_FLOAT_WIDE_INSERT:
1925                 code = FLOAT_CODE;
1926                 break;
1927         case LFUN_WRAP_INSERT:
1928                 code = WRAP_CODE;
1929                 break;
1930         case LFUN_FLOAT_LIST:
1931                 code = FLOAT_LIST_CODE;
1932                 break;
1933 #if 0
1934         case LFUN_LIST_INSERT:
1935                 code = LIST_CODE;
1936                 break;
1937         case LFUN_THEOREM_INSERT:
1938                 code = THEOREM_CODE;
1939                 break;
1940 #endif
1941         case LFUN_CAPTION_INSERT:
1942                 code = CAPTION_CODE;
1943                 break;
1944         case LFUN_NOTE_INSERT:
1945                 code = NOTE_CODE;
1946                 break;
1947         case LFUN_FLEX_INSERT: {
1948                 code = FLEX_CODE;
1949                 string s = cmd.getArg(0);
1950                 InsetLayout il = 
1951                         cur.buffer().params().documentClass().insetLayout(from_utf8(s));
1952                 if (il.lyxtype() != "charstyle" &&
1953                     il.lyxtype() != "custom" &&
1954                     il.lyxtype() != "element" &&
1955                     il.lyxtype ()!= "standard")
1956                         enable = false;
1957                 break;
1958                 }
1959         case LFUN_BOX_INSERT:
1960                 code = BOX_CODE;
1961                 break;
1962         case LFUN_BRANCH_INSERT:
1963                 code = BRANCH_CODE;
1964                 if (cur.buffer().masterBuffer()->params().branchlist().empty())
1965                         enable = false;
1966                 break;
1967         case LFUN_LABEL_INSERT:
1968                 code = LABEL_CODE;
1969                 break;
1970         case LFUN_INFO_INSERT:
1971                 code = INFO_CODE;
1972                 break;
1973         case LFUN_OPTIONAL_INSERT:
1974                 code = OPTARG_CODE;
1975                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
1976                         < cur.paragraph().layout()->optionalargs;
1977                 break;
1978         case LFUN_ENVIRONMENT_INSERT:
1979                 code = BOX_CODE;
1980                 break;
1981         case LFUN_INDEX_INSERT:
1982                 code = INDEX_CODE;
1983                 break;
1984         case LFUN_INDEX_PRINT:
1985                 code = INDEX_PRINT_CODE;
1986                 break;
1987         case LFUN_NOMENCL_INSERT:
1988                 code = NOMENCL_CODE;
1989                 break;
1990         case LFUN_NOMENCL_PRINT:
1991                 code = NOMENCL_PRINT_CODE;
1992                 break;
1993         case LFUN_TOC_INSERT:
1994                 code = TOC_CODE;
1995                 break;
1996         case LFUN_HYPERLINK_INSERT:
1997                 code = HYPERLINK_CODE;
1998                 break;
1999         case LFUN_QUOTE_INSERT:
2000                 // always allow this, since we will inset a raw quote
2001                 // if an inset is not allowed.
2002                 break;
2003         case LFUN_HFILL_INSERT:
2004         case LFUN_SPECIALCHAR_INSERT:
2005                 code = SPECIALCHAR_CODE;
2006                 break;
2007         case LFUN_SPACE_INSERT:
2008                 // slight hack: we know this is allowed in math mode
2009                 if (cur.inTexted())
2010                         code = SPACE_CODE;
2011                 break;
2012
2013         case LFUN_INSET_MODIFY:
2014                 // We need to disable this, because we may get called for a
2015                 // tabular cell via
2016                 // InsetTabular::getStatus() -> InsetText::getStatus()
2017                 // and we don't handle LFUN_INSET_MODIFY.
2018                 enable = false;
2019                 break;
2020
2021         case LFUN_FONT_EMPH:
2022                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2023                 return true;
2024
2025         case LFUN_FONT_NOUN:
2026                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2027                 return true;
2028
2029         case LFUN_FONT_BOLD:
2030                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2031                 return true;
2032
2033         case LFUN_FONT_SANS:
2034                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2035                 return true;
2036
2037         case LFUN_FONT_ROMAN:
2038                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2039                 return true;
2040
2041         case LFUN_FONT_TYPEWRITER:
2042                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2043                 return true;
2044
2045         case LFUN_CUT:
2046         case LFUN_COPY:
2047                 enable = cur.selection();
2048                 break;
2049
2050         case LFUN_PASTE: {
2051                 if (cmd.argument().empty()) {
2052                         if (theClipboard().isInternal())
2053                                 enable = cap::numberOfSelections() > 0;
2054                         else
2055                                 enable = !theClipboard().empty();
2056                         break;
2057                 }
2058                 
2059                 // we have an argument
2060                 string const arg = to_utf8(cmd.argument());
2061                 if (isStrUnsignedInt(arg)) {
2062                         // it's a number and therefore means the internal stack
2063                         unsigned int n = convert<unsigned int>(arg);
2064                         enable = cap::numberOfSelections() > n;
2065                         break;
2066                 }
2067                 
2068                 // explicit graphics type?
2069                 if ((arg == "pdf" && theClipboard().hasGraphicsContents(Clipboard::PdfGraphicsType))
2070                     || (arg == "png" && theClipboard().hasGraphicsContents(Clipboard::PngGraphicsType))
2071                     || (arg == "jpeg" && theClipboard().hasGraphicsContents(Clipboard::JpegGraphicsType))
2072                     || (arg == "linkback" && theClipboard().hasGraphicsContents(Clipboard::LinkBackGraphicsType))) {
2073                         enable = true;
2074                         break;
2075                 }
2076                 
2077                 // unknown argument
2078                 enable = false;
2079                 break;
2080          }
2081
2082         case LFUN_CLIPBOARD_PASTE:
2083                 enable = !theClipboard().empty();
2084                 break;
2085
2086         case LFUN_PRIMARY_SELECTION_PASTE:
2087                 enable = cur.selection() || !theSelection().empty();
2088                 break;
2089
2090         case LFUN_PARAGRAPH_MOVE_UP:
2091                 enable = cur.pit() > 0 && !cur.selection();
2092                 break;
2093
2094         case LFUN_PARAGRAPH_MOVE_DOWN:
2095                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2096                 break;
2097
2098         case LFUN_INSET_DISSOLVE:
2099                 if (!cmd.argument().empty()) {
2100                         InsetLayout il = cur.inset().getLayout(cur.buffer().params());
2101                         enable = cur.inset().lyxCode() == FLEX_CODE
2102                                  && il.lyxtype() == to_utf8(cmd.argument());
2103                 } else {
2104                         enable = !isMainText(cur.bv().buffer()) 
2105                                  && cur.inset().nargs() == 1;
2106                 }
2107                 break;
2108
2109         case LFUN_CHANGE_ACCEPT:
2110         case LFUN_CHANGE_REJECT:
2111                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2112                 // In principle, these LFUNs should only be enabled if there
2113                 // is a change at the current position/in the current selection.
2114                 // However, without proper optimizations, this will inevitably
2115                 // result in unacceptable performance - just imagine a user who
2116                 // wants to select the complete content of a long document.
2117                 enable = true;
2118                 break;
2119
2120         case LFUN_OUTLINE_UP:
2121         case LFUN_OUTLINE_DOWN:
2122         case LFUN_OUTLINE_IN:
2123         case LFUN_OUTLINE_OUT:
2124                 enable = (cur.paragraph().layout()->toclevel != Layout::NOT_IN_TOC);
2125                 break;
2126
2127         case LFUN_WORD_DELETE_FORWARD:
2128         case LFUN_WORD_DELETE_BACKWARD:
2129         case LFUN_LINE_DELETE:
2130         case LFUN_WORD_FORWARD:
2131         case LFUN_WORD_BACKWARD:
2132         case LFUN_WORD_RIGHT:
2133         case LFUN_WORD_LEFT:
2134         case LFUN_CHAR_FORWARD:
2135         case LFUN_CHAR_FORWARD_SELECT:
2136         case LFUN_CHAR_BACKWARD:
2137         case LFUN_CHAR_BACKWARD_SELECT:
2138         case LFUN_CHAR_LEFT:
2139         case LFUN_CHAR_LEFT_SELECT:
2140         case LFUN_CHAR_RIGHT:
2141         case LFUN_CHAR_RIGHT_SELECT:
2142         case LFUN_UP:
2143         case LFUN_UP_SELECT:
2144         case LFUN_DOWN:
2145         case LFUN_DOWN_SELECT:
2146         case LFUN_PARAGRAPH_UP_SELECT:
2147         case LFUN_PARAGRAPH_DOWN_SELECT:
2148         case LFUN_SCREEN_UP_SELECT:
2149         case LFUN_SCREEN_DOWN_SELECT:
2150         case LFUN_LINE_BEGIN_SELECT:
2151         case LFUN_LINE_END_SELECT:
2152         case LFUN_WORD_FORWARD_SELECT:
2153         case LFUN_WORD_BACKWARD_SELECT:
2154         case LFUN_WORD_RIGHT_SELECT:
2155         case LFUN_WORD_LEFT_SELECT:
2156         case LFUN_WORD_SELECT:
2157         case LFUN_PARAGRAPH_UP:
2158         case LFUN_PARAGRAPH_DOWN:
2159         case LFUN_LINE_BEGIN:
2160         case LFUN_LINE_BREAK:
2161         case LFUN_LINE_END:
2162         case LFUN_NEW_LINE:
2163         case LFUN_CHAR_DELETE_FORWARD:
2164         case LFUN_DELETE_FORWARD_SKIP:
2165         case LFUN_CHAR_DELETE_BACKWARD:
2166         case LFUN_DELETE_BACKWARD_SKIP:
2167         case LFUN_BREAK_PARAGRAPH:
2168         case LFUN_BREAK_PARAGRAPH_SKIP:
2169         case LFUN_PARAGRAPH_SPACING:
2170         case LFUN_INSET_INSERT:
2171         case LFUN_WORD_UPCASE:
2172         case LFUN_WORD_LOWCASE:
2173         case LFUN_WORD_CAPITALIZE:
2174         case LFUN_CHARS_TRANSPOSE:
2175         case LFUN_SERVER_GET_XY:
2176         case LFUN_SERVER_SET_XY:
2177         case LFUN_SERVER_GET_FONT:
2178         case LFUN_SERVER_GET_LAYOUT:
2179         case LFUN_LAYOUT:
2180         case LFUN_DATE_INSERT:
2181         case LFUN_SELF_INSERT:
2182         case LFUN_LINE_INSERT:
2183         case LFUN_NEWPAGE_INSERT:
2184         case LFUN_PAGEBREAK_INSERT:
2185         case LFUN_CLEARPAGE_INSERT:
2186         case LFUN_CLEARDOUBLEPAGE_INSERT:
2187         case LFUN_MATH_DISPLAY:
2188         case LFUN_MATH_IMPORT_SELECTION:
2189         case LFUN_MATH_MODE:
2190         case LFUN_MATH_MACRO:
2191         case LFUN_MATH_MATRIX:
2192         case LFUN_MATH_DELIM:
2193         case LFUN_MATH_BIGDELIM:
2194         case LFUN_MATH_INSERT:
2195         case LFUN_MATH_SUBSCRIPT:
2196         case LFUN_MATH_SUPERSCRIPT:
2197         case LFUN_FONT_DEFAULT:
2198         case LFUN_FONT_UNDERLINE:
2199         case LFUN_FONT_SIZE:
2200         case LFUN_LANGUAGE:
2201         case LFUN_FONT_FREE_APPLY:
2202         case LFUN_FONT_FREE_UPDATE:
2203         case LFUN_LAYOUT_PARAGRAPH:
2204         case LFUN_PARAGRAPH_UPDATE:
2205         case LFUN_ACCENT_UMLAUT:
2206         case LFUN_ACCENT_CIRCUMFLEX:
2207         case LFUN_ACCENT_GRAVE:
2208         case LFUN_ACCENT_ACUTE:
2209         case LFUN_ACCENT_TILDE:
2210         case LFUN_ACCENT_CEDILLA:
2211         case LFUN_ACCENT_MACRON:
2212         case LFUN_ACCENT_DOT:
2213         case LFUN_ACCENT_UNDERDOT:
2214         case LFUN_ACCENT_UNDERBAR:
2215         case LFUN_ACCENT_CARON:
2216         case LFUN_ACCENT_SPECIAL_CARON:
2217         case LFUN_ACCENT_BREVE:
2218         case LFUN_ACCENT_TIE:
2219         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2220         case LFUN_ACCENT_CIRCLE:
2221         case LFUN_ACCENT_OGONEK:
2222         case LFUN_THESAURUS_ENTRY:
2223         case LFUN_PARAGRAPH_PARAMS_APPLY:
2224         case LFUN_PARAGRAPH_PARAMS:
2225         case LFUN_ESCAPE:
2226         case LFUN_BUFFER_END:
2227         case LFUN_BUFFER_BEGIN:
2228         case LFUN_BUFFER_BEGIN_SELECT:
2229         case LFUN_BUFFER_END_SELECT:
2230         case LFUN_UNICODE_INSERT:
2231                 // these are handled in our dispatch()
2232                 enable = true;
2233                 break;
2234
2235         default:
2236                 return false;
2237         }
2238
2239         if (code != NO_CODE
2240             && (cur.empty() || !cur.inset().insetAllowed(code)))
2241                 enable = false;
2242
2243         flag.enabled(enable);
2244         return true;
2245 }
2246
2247
2248 void Text::pasteString(Cursor & cur, docstring const & clip,
2249                 bool asParagraphs)
2250 {
2251         cur.clearSelection();
2252         if (!clip.empty()) {
2253                 cur.recordUndo();
2254                 if (asParagraphs)
2255                         insertStringAsParagraphs(cur, clip);
2256                 else
2257                         insertStringAsLines(cur, clip);
2258         }
2259 }
2260
2261 } // namespace lyx