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