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