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