]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
Martin/Angus srcdoc patch, a fix for scrollbar and font size change, fix warning...
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author various
7  */
8
9 #include <config.h>
10
11 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "BufferView_pimpl.h"
16 #include "frontends/WorkArea.h"
17 #include "frontends/screen.h"
18 #include "frontends/LyXScreenFactory.h"
19 #include "frontends/WorkAreaFactory.h"
20 #include "frontends/Dialogs.h"
21 #include "frontends/Alert.h"
22 #include "frontends/FileDialog.h"
23 #include "lyxtext.h"
24 #include "lyxrow.h"
25 #include "paragraph.h"
26 #include "frontends/LyXView.h"
27 #include "commandtags.h"
28 #include "lyxfunc.h"
29 #include "debug.h"
30 #include "bufferview_funcs.h"
31 #include "TextCache.h"
32 #include "bufferlist.h"
33 #include "lyxrc.h"
34 #include "intl.h"
35 // added for Dispatch functions
36 #include "lyx_cb.h"
37 #include "lyx_main.h"
38 #include "FloatList.h"
39 #include "gettext.h"
40 #include "ParagraphParameters.h"
41 #include "undo_funcs.h"
42 #include "funcrequest.h"
43
44 #include "insets/insetbib.h"
45 #include "insets/insettext.h"
46 #include "insets/inseturl.h"
47 #include "insets/insetlatexaccent.h"
48 #include "insets/insettoc.h"
49 #include "insets/insetref.h"
50 #include "insets/insetparent.h"
51 #include "insets/insetindex.h"
52 #include "insets/insetnote.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insetcite.h"
55 #include "insets/insetert.h"
56 #include "insets/insetexternal.h"
57 #include "insets/insetgraphics.h"
58 #include "insets/insetfoot.h"
59 #include "insets/insetmarginal.h"
60 #include "insets/insetminipage.h"
61 #include "insets/insetfloat.h"
62 #include "insets/insettabular.h"
63 #if 0
64 #include "insets/insettheorem.h"
65 #include "insets/insetlist.h"
66 #endif
67 #include "insets/insetcaption.h"
68 #include "insets/insetfloatlist.h"
69 #include "insets/insetspecialchar.h"
70
71 #include "mathed/formulabase.h"
72
73 #include "graphics/Previews.h"
74
75 #include "support/LAssert.h"
76 #include "support/lstrings.h"
77 #include "support/filetools.h"
78 #include "support/lyxfunctional.h"
79
80 #include <boost/bind.hpp>
81 #include <boost/signals/connection.hpp>
82
83 #include <cstdio>
84 #include <ctime>
85 #include <unistd.h>
86 #include <sys/wait.h>
87 #include <clocale>
88
89
90 extern string current_layout;
91
92 #ifndef CXX_GLOBAL_CSTD
93 using std::tm;
94 using std::localtime;
95 using std::time;
96 using std::setlocale;
97 using std::strftime;
98 #endif
99
100 using std::vector;
101 using std::find_if;
102 using std::find;
103 using std::pair;
104 using std::endl;
105 using std::make_pair;
106 using std::min;
107
108 using lyx::pos_type;
109 using lyx::textclass_type;
110
111 /* the selection possible is needed, that only motion events are
112  * used, where the bottom press event was on the drawing area too */
113 bool selection_possible = false;
114
115 extern BufferList bufferlist;
116 extern char ascii_type;
117
118 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
119
120
121 namespace {
122
123 unsigned int const saved_positions_num = 20;
124
125 // All the below connection objects are needed because of a bug in some
126 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
127 // to these connections we avoid a segfault upon startup, and also at exit.
128 // (Lgb)
129
130 boost::signals::connection timecon;
131 boost::signals::connection doccon;
132 boost::signals::connection resizecon;
133 boost::signals::connection bpresscon;
134 boost::signals::connection breleasecon;
135 boost::signals::connection motioncon;
136 boost::signals::connection doublecon;
137 boost::signals::connection triplecon;
138 boost::signals::connection kpresscon;
139 boost::signals::connection selectioncon;
140 boost::signals::connection lostcon;
141
142 } // anon namespace
143
144
145 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
146              int xpos, int ypos, int width, int height)
147         : bv_(b), owner_(o), buffer_(0), cursor_timeout(400),
148           using_xterm_cursor(false)
149 {
150         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
151         screen_.reset(LyXScreenFactory::create(workarea()));
152
153         // Setup the signals
154         doccon = workarea().scrollDocView.connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
155         resizecon = workarea().workAreaResize
156                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
157         bpresscon = workarea().workAreaButtonPress
158                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonPress, this, _1, _2, _3));
159         breleasecon = workarea().workAreaButtonRelease
160                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonRelease, this, _1, _2, _3));
161         motioncon = workarea().workAreaMotionNotify
162                 .connect(boost::bind(&BufferView::Pimpl::workAreaMotionNotify, this, _1, _2, _3));
163         doublecon = workarea().workAreaDoubleClick
164                 .connect(boost::bind(&BufferView::Pimpl::doubleClick, this, _1, _2, _3));
165         triplecon = workarea().workAreaTripleClick
166                 .connect(boost::bind(&BufferView::Pimpl::tripleClick, this, _1, _2, _3));
167         kpresscon = workarea().workAreaKeyPress
168                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
169         selectioncon = workarea().selectionRequested
170                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
171         lostcon = workarea().selectionLost
172                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
173
174         timecon = cursor_timeout.timeout.connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
175         cursor_timeout.start();
176         saved_positions.resize(saved_positions_num);
177 }
178
179
180 WorkArea & BufferView::Pimpl::workarea() const
181 {
182         return *workarea_.get();
183 }
184
185
186 LyXScreen & BufferView::Pimpl::screen() const
187 {
188         return *screen_.get();
189 }
190
191
192 Painter & BufferView::Pimpl::painter() const
193 {
194         return workarea().getPainter();
195 }
196
197
198 void BufferView::Pimpl::buffer(Buffer * b)
199 {
200         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
201                             << b << ")" << endl;
202         if (buffer_) {
203                 buffer_->delUser(bv_);
204
205                 // Put the old text into the TextCache, but
206                 // only if the buffer is still loaded.
207                 // Also set the owner of the test to 0
208                 //              bv_->text->owner(0);
209                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
210                 if (lyxerr.debugging())
211                         textcache.show(lyxerr, "BufferView::buffer");
212
213                 bv_->text = 0;
214         }
215
216         // Set current buffer
217         buffer_ = b;
218
219         if (bufferlist.getState() == BufferList::CLOSING) return;
220
221         // If we are closing the buffer, use the first buffer as current
222         if (!buffer_) {
223                 buffer_ = bufferlist.first();
224         }
225
226         if (buffer_) {
227                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
228                 buffer_->addUser(bv_);
229
230                 // If we don't have a text object for this, we make one
231                 if (bv_->text == 0) {
232                         resizeCurrentBuffer();
233                 }
234
235                 // FIXME: needed when ?
236                 bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
237
238                 // Similarly, buffer-dependent dialogs should be updated or
239                 // hidden. This should go here because some dialogs (eg ToC)
240                 // require bv_->text.
241                 owner_->getDialogs()->updateBufferDependent(true);
242         } else {
243                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
244                 owner_->getDialogs()->hideBufferDependent();
245
246                 // Also remove all remaining text's from the testcache.
247                 // (there should not be any!) (if there is any it is a
248                 // bug!)
249                 if (lyxerr.debugging())
250                         textcache.show(lyxerr, "buffer delete all");
251                 textcache.clear();
252         }
253
254         repaint();
255         updateScrollbar();
256         owner_->updateMenubar();
257         owner_->updateToolbar();
258         owner_->updateLayoutChoice();
259         owner_->updateWindowTitle();
260
261         if (grfx::Previews::activated() && buffer_)
262                 grfx::Previews::get().generateBufferPreviews(*buffer_);
263 }
264
265
266 bool BufferView::Pimpl::fitCursor()
267 {
268         bool ret;
269
270         if (bv_->theLockingInset()) {
271                 bv_->theLockingInset()->fitInsetCursor(bv_);
272                 ret = true;
273         } else {
274                 ret = screen().fitCursor(bv_->text, bv_);
275         }
276
277         bv_->owner()->getDialogs()->updateParagraph();
278         if (ret)
279                 updateScrollbar();
280         return ret;
281 }
282
283
284 void BufferView::Pimpl::redoCurrentBuffer()
285 {
286         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
287         if (buffer_ && bv_->text) {
288                 resizeCurrentBuffer();
289                 updateScrollbar();
290                 owner_->updateLayoutChoice();
291                 repaint();
292         }
293 }
294
295
296 int BufferView::Pimpl::resizeCurrentBuffer()
297 {
298         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
299
300         Paragraph * par = 0;
301         Paragraph * selstartpar = 0;
302         Paragraph * selendpar = 0;
303         UpdatableInset * the_locking_inset = 0;
304
305         pos_type pos = 0;
306         pos_type selstartpos = 0;
307         pos_type selendpos = 0;
308         bool selection = false;
309         bool mark_set  = false;
310
311         owner_->prohibitInput();
312
313         owner_->message(_("Formatting document..."));
314
315         if (bv_->text) {
316                 par = bv_->text->cursor.par();
317                 pos = bv_->text->cursor.pos();
318                 selstartpar = bv_->text->selection.start.par();
319                 selstartpos = bv_->text->selection.start.pos();
320                 selendpar = bv_->text->selection.end.par();
321                 selendpos = bv_->text->selection.end.pos();
322                 selection = bv_->text->selection.set();
323                 mark_set = bv_->text->selection.mark();
324                 the_locking_inset = bv_->theLockingInset();
325                 buffer_->resizeInsets(bv_);
326                 // I don't think the delete and new are necessary here we just could
327                 // call only init! (Jug 20020419)
328                 delete bv_->text;
329                 bv_->text = new LyXText(bv_);
330                 bv_->text->init(bv_);
331         } else {
332                 // See if we have a text in TextCache that fits
333                 // the new buffer_ with the correct width.
334                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
335                 if (bv_->text) {
336                         if (lyxerr.debugging()) {
337                                 lyxerr << "Found a LyXText that fits:\n";
338                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
339                         }
340                         // Set the owner of the newly found text
341                         //      bv_->text->owner(bv_);
342                         if (lyxerr.debugging())
343                                 textcache.show(lyxerr, "resizeCurrentBuffer");
344                 } else {
345                         bv_->text = new LyXText(bv_);
346                         bv_->text->init(bv_);
347                         //buffer_->resizeInsets(bv_);
348                 }
349         }
350
351         if (par) {
352                 bv_->text->selection.set(true);
353                 // At this point just to avoid the Delete-Empty-Paragraph-
354                 // Mechanism when setting the cursor.
355                 bv_->text->selection.mark(mark_set);
356                 if (selection) {
357                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
358                         bv_->text->selection.cursor = bv_->text->cursor;
359                         bv_->text->setCursor(bv_, selendpar, selendpos);
360                         bv_->text->setSelection(bv_);
361                         bv_->text->setCursor(bv_, par, pos);
362                 } else {
363                         bv_->text->setCursor(bv_, par, pos);
364                         bv_->text->selection.cursor = bv_->text->cursor;
365                         bv_->text->selection.set(false);
366                 }
367                 // remake the inset locking
368                 bv_->theLockingInset(the_locking_inset);
369         }
370
371         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
372
373         switchKeyMap();
374         owner_->allowInput();
375
376         updateScrollbar();
377  
378         return 0;
379 }
380
381
382 void BufferView::Pimpl::repaint()
383 {
384         // Regenerate the screen.
385         screen().redraw(bv_->text, bv_);
386 }
387
388
389 void BufferView::Pimpl::updateScrollbar()
390 {
391         if (!bv_->text) {
392                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
393                 workarea().setScrollbarParams(0, 0, 0);
394                 return;
395         }
396
397         LyXText const & t = *bv_->text;
398
399         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
400                 << t.first_y << ", default height " << t.defaultHeight() << endl;
401
402         workarea().setScrollbarParams(t.height, t.first_y, t.defaultHeight());
403 }
404
405
406 void BufferView::Pimpl::scrollDocView(int value)
407 {
408         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
409
410         if (!buffer_) return;
411
412         screen().draw(bv_->text, bv_, value);
413
414         if (!lyxrc.cursor_follows_scrollbar) {
415                 return;
416         }
417
418         LyXText * vbt = bv_->text;
419
420         int const height = vbt->defaultHeight();
421         int const first = static_cast<int>((bv_->text->first_y + height));
422         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
423
424         if (vbt->cursor.y() < first)
425                 vbt->setCursorFromCoordinates(bv_, 0, first);
426         else if (vbt->cursor.y() > last)
427                 vbt->setCursorFromCoordinates(bv_, 0, last);
428 }
429
430
431 int BufferView::Pimpl::scroll(long time)
432 {
433         if (!buffer_)
434                 return 0;
435
436         LyXText const * t = bv_->text;
437
438         double const diff = t->defaultHeight()
439                 + double(time) * double(time) * 0.125;
440
441         scrollDocView(int(diff));
442         workarea().setScrollbarParams(t->height, t->first_y, t->defaultHeight());
443         return 0;
444 }
445
446
447 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
448                                          key_modifier::state state)
449 {
450         bv_->owner()->getLyXFunc()->processKeySym(key, state);
451 }
452
453
454 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, mouse_button::state state)
455 {
456         // Only use motion with button 1
457         if (!(state & mouse_button::button1))
458                 return;
459
460         if (!buffer_)
461                 return;
462
463         // Check for inset locking
464         if (bv_->theLockingInset()) {
465                 LyXCursor cursor = bv_->text->cursor;
466                 LyXFont font = bv_->text->getFont(buffer_,
467                                                   cursor.par(), cursor.pos());
468                 int width = bv_->theLockingInset()->width(bv_, font);
469                 int inset_x = font.isVisibleRightToLeft()
470                         ? cursor.ix() - width : cursor.ix();
471                 int start_x = inset_x + bv_->theLockingInset()->scroll();
472
473                 bv_->theLockingInset()->
474                         insetMotionNotify(bv_,
475                                           x - start_x,
476                                           y - cursor.iy() + bv_->text->first_y,
477                                           state);
478                 return;
479         }
480
481         /* The test for not selection possible is needed, that only motion
482            events are used, where the bottom press event was on
483            the drawing area too */
484         if (!selection_possible)
485                 return;
486
487         screen().hideCursor();
488
489         Row * cursorrow = bv_->text->cursor.row();
490         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
491 #if 0
492         // sorry for this but I have a strange error that the y value jumps at
493         // a certain point. This seems like an error in my xforms library or
494         // in some other local environment, but I would like to leave this here
495         // for the moment until I can remove this (Jug 20020418)
496         if (y_before < bv_->text->cursor.y())
497                 lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
498 #endif
499         // This is to allow jumping over large insets
500         if (cursorrow == bv_->text->cursor.row()) {
501                 if (y >= int(workarea().workHeight())) {
502                         bv_->text->cursorDown(bv_, false);
503                 } else if (y < 0) {
504                         bv_->text->cursorUp(bv_, false);
505                 }
506         }
507
508         if (!bv_->text->selection.set())
509                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
510
511         bv_->text->setSelection(bv_);
512         screen().toggleToggle(bv_->text, bv_);
513         fitCursor();
514         showCursor();
515 }
516
517
518 // Single-click on work area
519 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
520                                             mouse_button::state button)
521 {
522         if (!buffer_)
523                 return;
524
525         // ok ok, this is a hack (for xforms)
526         if (button == mouse_button::button4) {
527                 scroll(-lyxrc.wheel_jump);
528                 // We shouldn't go further down as we really should only do the
529                 // scrolling and be done with this. Otherwise we may open some
530                 // dialogs (Jug 20020424).
531                 return;
532         } else if (button == mouse_button::button5) {
533                 scroll(lyxrc.wheel_jump);
534                 // We shouldn't go further down as we really should only do the
535                 // scrolling and be done with this. Otherwise we may open some
536                 // dialogs (Jug 20020424).
537                 return;
538         }
539
540         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
541
542         // Middle button press pastes if we have a selection
543         // We do this here as if the selection was inside an inset
544         // it could get cleared on the unlocking of the inset so
545         // we have to check this first
546         bool paste_internally = false;
547         if (button == mouse_button::button2 && bv_->getLyXText()->selection.set()) {
548                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
549                 paste_internally = true;
550         }
551
552         int const screen_first = bv_->text->first_y;
553
554         if (bv_->theLockingInset()) {
555                 // We are in inset locking mode
556
557                 /* Check whether the inset was hit. If not reset mode,
558                    otherwise give the event to the inset */
559                 if (inset_hit == bv_->theLockingInset()) {
560                         bv_->theLockingInset()->
561                                 insetButtonPress(bv_, xpos, ypos, button);
562                         return;
563                 } else {
564                         bv_->unlockInset(bv_->theLockingInset());
565                 }
566         }
567
568         if (!inset_hit)
569                 selection_possible = true;
570         screen().hideCursor();
571
572         // Clear the selection
573         screen().toggleSelection(bv_->text, bv_);
574         bv_->text->clearSelection();
575         bv_->text->fullRebreak(bv_);
576         update();
577         updateScrollbar();
578
579         // Single left click in math inset?
580         if (isHighlyEditableInset(inset_hit)) {
581                 // Highly editable inset, like math
582                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
583                 selection_possible = false;
584                 owner_->updateLayoutChoice();
585                 owner_->message(inset->editMessage());
586                 //inset->edit(bv_, xpos, ypos, button);
587                 // We just have to lock the inset before calling a PressEvent on it!
588                 // we don't need the edit() call here! (Jug20020329)
589                 if (!bv_->lockInset(inset)) {
590                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
591                 }
592                 inset->insetButtonPress(bv_, xpos, ypos, button);
593                 return;
594         }
595         // I'm not sure we should continue here if we hit an inset (Jug20020403)
596
597         // Right click on a footnote flag opens float menu
598         if (button == mouse_button::button3) {
599                 selection_possible = false;
600                 return;
601         }
602
603         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
604                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
605         finishUndo();
606         bv_->text->selection.cursor = bv_->text->cursor;
607         bv_->text->cursor.x_fix(bv_->text->cursor.x());
608
609         owner_->updateLayoutChoice();
610         if (fitCursor()) {
611                 selection_possible = false;
612         }
613
614         // Insert primary selection with middle mouse
615         // if there is a local selection in the current buffer,
616         // insert this
617         if (button == mouse_button::button2) {
618                 if (paste_internally)
619                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
620                 else
621                         owner_->getLyXFunc()->dispatch(FuncRequest(LFUN_PASTESELECTION, "paragraph"));
622                 selection_possible = false;
623                 return;
624         }
625 }
626
627
628 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, mouse_button::state button)
629 {
630         if (!buffer_)
631                 return;
632
633         LyXText * text = bv_->getLyXText();
634
635         if (text->bv_owner && bv_->theLockingInset())
636                 return;
637
638         if (button == mouse_button::button1) {
639                 if (text->bv_owner) {
640                         screen().hideCursor();
641                         screen().toggleSelection(text, bv_);
642                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
643                         screen().toggleSelection(text, bv_, false);
644                 } else {
645                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
646                 }
647                 /* This will fit the cursor on the screen
648                  * if necessary */
649                 update(text, BufferView::SELECT|BufferView::FITCUR);
650                 workarea().haveSelection(bv_->getLyXText()->selection.set());
651         }
652 }
653
654
655 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, mouse_button::state button)
656 {
657         if (!buffer_)
658                 return;
659
660         LyXText * text = bv_->getLyXText();
661
662         if (text->bv_owner && bv_->theLockingInset())
663             return;
664
665         if (button == mouse_button::button1) {
666                 if (text->bv_owner) {
667                         screen().hideCursor();
668                         screen().toggleSelection(text, bv_);
669                 }
670                 text->cursorHome(bv_);
671                 text->selection.cursor = text->cursor;
672                 text->cursorEnd(bv_);
673                 text->setSelection(bv_);
674                 if (text->bv_owner) {
675                         screen().toggleSelection(text, bv_, false);
676                 }
677                 /* This will fit the cursor on the screen
678                  * if necessary */
679                 update(text, BufferView::SELECT|BufferView::FITCUR);
680                 workarea().haveSelection(bv_->getLyXText()->selection.set());
681         }
682 }
683
684
685 void BufferView::Pimpl::selectionRequested()
686 {
687         static string sel;
688
689         if (!available())
690                 return;
691
692         LyXText * text = bv_->getLyXText();
693
694         if (text->selection.set() &&
695                 (!bv_->text->xsel_cache.set() ||
696                  text->selection.start != bv_->text->xsel_cache.start ||
697                  text->selection.end != bv_->text->xsel_cache.end))
698         {
699                 bv_->text->xsel_cache = text->selection;
700                 sel = text->selectionAsString(bv_->buffer(), false);
701         } else if (!text->selection.set()) {
702                 sel = string();
703                 bv_->text->xsel_cache.set(false);
704         }
705         if (!sel.empty()) {
706                 workarea().putClipboard(sel);
707         }
708 }
709
710
711 void BufferView::Pimpl::selectionLost()
712 {
713         if (available()) {
714                 hideCursor();
715                 toggleSelection();
716                 bv_->getLyXText()->clearSelection();
717                 showCursor();
718                 bv_->text->xsel_cache.set(false);
719         }
720 }
721
722
723 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
724                                               mouse_button::state button)
725 {
726         // do nothing if we used the mouse wheel
727         if (!buffer_ || button == mouse_button::button4 || button == mouse_button::button5)
728                 return;
729
730         // If we hit an inset, we have the inset coordinates in these
731         // and inset_hit points to the inset.  If we do not hit an
732         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
733         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
734
735         if (bv_->theLockingInset()) {
736                 // We are in inset locking mode.
737
738                 /* LyX does a kind of work-area grabbing for insets.
739                    Only a ButtonPress FuncRequest outside the inset will
740                    force a insetUnlock. */
741                 bv_->theLockingInset()->
742                         insetButtonRelease(bv_, x, y, button);
743                 return;
744         }
745
746         selection_possible = false;
747
748         if (button == mouse_button::button2)
749                 return;
750
751         // finish selection
752         if (button == mouse_button::button1) {
753                 workarea().haveSelection(bv_->getLyXText()->selection.set());
754         }
755
756         switchKeyMap();
757         owner_->view_state_changed();
758         owner_->updateMenubar();
759         owner_->updateToolbar();
760
761         // Did we hit an editable inset?
762         if (inset_hit) {
763                 selection_possible = false;
764
765                 // if we reach this point with a selection, it
766                 // must mean we are currently selecting.
767                 // But we don't want to open the inset
768                 // because that is annoying for the user.
769                 // So just pretend we didn't hit it.
770                 // this is OK because a "kosher" ButtonRelease
771                 // will follow a ButtonPress that clears
772                 // the selection.
773                 // Note this also fixes selection drawing
774                 // problems if we end up opening an inset
775                 if (bv_->getLyXText()->selection.set())
776                         return;
777
778                 // CHECK fix this proper in 0.13
779                 // well, maybe 13.0 !!!!!!!!!
780
781                 // Following a ref shouldn't issue
782                 // a push on the undo-stack
783                 // anylonger, now that we have
784                 // keybindings for following
785                 // references and returning from
786                 // references.  IMHO though, it
787                 // should be the inset's own business
788                 // to push or not push on the undo
789                 // stack. They don't *have* to
790                 // alter the document...
791                 // (Joacim)
792                 // ...or maybe the SetCursorParUndo()
793                 // below isn't necessary at all anylonger?
794                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
795                         setCursorParUndo(bv_);
796                 }
797
798                 owner_->message(inset_hit->editMessage());
799
800                 if (isHighlyEditableInset(inset_hit)) {
801                         // Highly editable inset, like math
802                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
803                         inset->insetButtonRelease(bv_, x, y, button);
804                 } else {
805                         inset_hit->insetButtonRelease(bv_, x, y, button);
806                         // IMO this is a grosshack! Inset's should be changed so that
807                         // they call the actions they have to do with the insetButtonRel.
808                         // function and not in the edit(). This should be changed
809                         // (Jug 20020329)
810                         inset_hit->edit(bv_, x, y, button);
811                 }
812                 return;
813         }
814
815         // Maybe we want to edit a bibitem ale970302
816         if (bv_->text->cursor.par()->bibkey) {
817                 bool const is_rtl = bv_->text->cursor.par()->isRightToLeftPar(buffer_->params);
818                 int const width = bibitemMaxWidth(bv_, buffer_->params.getLyXTextClass().defaultfont());
819                 if ((is_rtl && x > bv_->text->workWidth(bv_)-20-width) ||
820                     (!is_rtl && x < 20+width)) {
821                         bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, mouse_button::none);
822                 }
823         }
824
825         return;
826 }
827
828
829 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
830                                        LyXCursor const & cursor) const
831 {
832         Paragraph /*const*/ & par = *cursor.par();
833         pos_type const pos = cursor.pos();
834
835         lyx::Assert(par.getInset(pos));
836
837         Inset const & inset(*par.getInset(pos));
838
839         LyXFont const & font = text.getFont(buffer_, &par, pos);
840
841         int const width = inset.width(bv_, font);
842         int const inset_x = font.isVisibleRightToLeft()
843                 ? (cursor.ix() - width) : cursor.ix();
844
845         return Box(
846                 inset_x + inset.scroll(),
847                 inset_x + width,
848                 cursor.iy() - inset.ascent(bv_, font),
849                 cursor.iy() + inset.descent(bv_, font));
850 }
851
852
853 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
854                                       LyXCursor const & cursor,
855                                       int & x, int & y) const
856 {
857         pos_type const pos(cursor.pos());
858         Paragraph /*const*/ & par(*cursor.par());
859
860         if (pos >= par.size() || !par.isInset(pos)) {
861                 return 0;
862         }
863
864         Inset /*const*/ * inset = par.getInset(pos);
865
866         if (!isEditableInset(inset)) {
867                 return 0;
868         }
869
870         Box b(insetDimensions(text, cursor));
871
872         if (!b.contained(x, y)) {
873                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
874                         << " box " << b << endl;
875                 return 0;
876         }
877
878         text.setCursor(bv_, &par, pos, true);
879
880         x -= b.x1;
881         // The origin of an inset is on the baseline
882         y -= text.cursor.iy();
883
884         return inset;
885 }
886
887
888 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
889 {
890         int y_tmp = y + text->first_y;
891
892         LyXCursor cursor;
893         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
894
895         Inset * inset(checkInset(*text, cursor, x, y_tmp));
896
897         if (inset) {
898                 y = y_tmp;
899                 return inset;
900         }
901
902         // look at previous position
903
904         if (cursor.pos() == 0) {
905                 return 0;
906         }
907
908         // move back one
909         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
910
911         inset = checkInset(*text, cursor, x, y_tmp);
912         if (inset) {
913                 y = y_tmp;
914         }
915         return inset;
916 }
917
918
919 void BufferView::Pimpl::workAreaResize()
920 {
921         static int work_area_width;
922         static int work_area_height;
923
924         bool const widthChange = workarea().workWidth() != work_area_width;
925         bool const heightChange = workarea().workHeight() != work_area_height;
926
927         // update from work area
928         work_area_width = workarea().workWidth();
929         work_area_height = workarea().workHeight();
930
931         if (buffer_ != 0) {
932                 if (widthChange) {
933                         // The visible LyXView need a resize
934                         resizeCurrentBuffer();
935
936                         // Remove all texts from the textcache
937                         // This is not _really_ what we want to do. What
938                         // we really want to do is to delete in textcache
939                         // that does not have a BufferView with matching
940                         // width, but as long as we have only one BufferView
941                         // deleting all gives the same result.
942                         if (lyxerr.debugging())
943                                 textcache.show(lyxerr, "Expose delete all");
944                         textcache.clear();
945                         // FIXME: this is aalready done in resizeCurrentBuffer() ??
946                         buffer_->resizeInsets(bv_);
947                 } else if (heightChange) {
948                         // fitCursor() ensures we don't jump back
949                         // to the start of the document on vertical
950                         // resize
951                         fitCursor();
952                 }
953         }
954
955         if (widthChange || heightChange) {
956                 repaint();
957         }
958
959         // always make sure that the scrollbar is sane.
960         updateScrollbar();
961         owner_->updateLayoutChoice();
962         return;
963 }
964
965
966 void BufferView::Pimpl::update()
967 {
968         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
969                 LyXText::text_status st = bv_->text->status();
970                 screen().update(bv_->text, bv_);
971                 bool fitc = false;
972                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
973                         bv_->text->fullRebreak(bv_);
974                         st = LyXText::NEED_MORE_REFRESH;
975                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
976                                              bv_->text->cursor.pos());
977                         if (bv_->text->selection.set()) {
978                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
979                                                      bv_->text->selection.start.par(),
980                                                      bv_->text->selection.start.pos());
981                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
982                                                      bv_->text->selection.end.par(),
983                                                      bv_->text->selection.end.pos());
984                         }
985                         fitc = true;
986                         bv_->text->status(bv_, st);
987                         screen().update(bv_->text, bv_);
988                 }
989                 // do this here instead of in the screen::update because of
990                 // the above loop!
991                 bv_->text->status(bv_, LyXText::UNCHANGED);
992                 if (fitc)
993                         fitCursor();
994         }
995 }
996
997 // Values used when calling update:
998 // -3 - update
999 // -2 - update, move sel_cursor if selection, fitcursor
1000 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1001 //  0 - update, move sel_cursor if selection, fitcursor
1002 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1003 //  3 - update, move sel_cursor if selection
1004 //
1005 // update -
1006 // a simple redraw of the parts that need refresh
1007 //
1008 // move sel_cursor if selection -
1009 // the text's sel_cursor is moved if there is selection is progress
1010 //
1011 // fitcursor -
1012 // fitCursor() is called and the scrollbar updated
1013 //
1014 // mark dirty -
1015 // the buffer is marked dirty.
1016 //
1017 // enum {
1018 //       UPDATE = 0,
1019 //       SELECT = 1,
1020 //       FITCUR = 2,
1021 //       CHANGE = 4
1022 // };
1023 //
1024 // UPDATE_ONLY = UPDATE;
1025 // UPDATE_SELECT = UPDATE | SELECT;
1026 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1027 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1028 //
1029 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1030 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1031 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1032 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1033 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1034
1035 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1036 {
1037         owner_->updateLayoutChoice();
1038
1039         if (!text->selection.set() && (f & SELECT)) {
1040                 text->selection.cursor = text->cursor;
1041         }
1042
1043         text->fullRebreak(bv_);
1044
1045         if (text->inset_owner) {
1046                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1047                 updateInset(text->inset_owner, false);
1048         } else {
1049                 update();
1050         }
1051
1052         if ((f & FITCUR)) {
1053                 fitCursor();
1054         }
1055
1056         if ((f & CHANGE)) {
1057                 buffer_->markDirty();
1058         }
1059 }
1060
1061
1062 // Callback for cursor timer
1063 void BufferView::Pimpl::cursorToggle()
1064 {
1065         if (!buffer_) {
1066                 cursor_timeout.restart();
1067                 return;
1068         }
1069
1070         /* FIXME */
1071         extern void reapSpellchecker(void);
1072         reapSpellchecker();
1073
1074         if (!bv_->theLockingInset()) {
1075                 screen().cursorToggle(bv_);
1076         } else {
1077                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1078         }
1079
1080         cursor_timeout.restart();
1081 }
1082
1083
1084 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1085 {
1086         if (!text->cursor.row()->previous()) {
1087                 if (text->first_y > 0) {
1088                         int new_y = bv_->text->first_y - workarea().workHeight();
1089                         screen().draw(bv_->text, bv_, new_y < 0 ? 0 : new_y);
1090                         updateScrollbar();
1091                 }
1092                 return;
1093         }
1094
1095         int y = text->first_y;
1096         Row * cursorrow = text->cursor.row();
1097
1098         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y);
1099         finishUndo();
1100
1101         int new_y;
1102         if (cursorrow == bv_->text->cursor.row()) {
1103                 // we have a row which is higher than the workarea so we leave the
1104                 // cursor on the start of the row and move only the draw up as soon
1105                 // as we move the cursor or do something while inside the row (it may
1106                 // span several workarea-heights) we'll move to the top again, but this
1107                 // is better than just jump down and only display part of the row.
1108                 new_y = bv_->text->first_y - workarea().workHeight();
1109         } else {
1110                 if (text->inset_owner) {
1111                         new_y = bv_->text->cursor.iy()
1112                                 + bv_->theLockingInset()->insetInInsetY() + y
1113                                 + text->cursor.row()->height()
1114                                 - workarea().workHeight() + 1;
1115                 } else {
1116                         new_y = text->cursor.y()
1117                                 - text->cursor.row()->baseline()
1118                                 + text->cursor.row()->height()
1119                                 - workarea().workHeight() + 1;
1120                 }
1121         }
1122         screen().draw(bv_->text, bv_,  new_y < 0 ? 0 : new_y);
1123         if (text->cursor.row()->previous()) {
1124                 LyXCursor cur;
1125                 text->setCursor(bv_, cur, text->cursor.row()->previous()->par(),
1126                                                 text->cursor.row()->previous()->pos(), false);
1127                 if (cur.y() > text->first_y) {
1128                         text->cursorUp(bv_, true);
1129                 }
1130         }
1131         updateScrollbar();
1132 }
1133
1134
1135 void BufferView::Pimpl::cursorNext(LyXText * text)
1136 {
1137         if (!text->cursor.row()->next()) {
1138                 int y = text->cursor.y() - text->cursor.row()->baseline() +
1139                         text->cursor.row()->height();
1140                 if (y > int(text->first_y + workarea().workHeight())) {
1141                         screen().draw(bv_->text, bv_,
1142                                                   bv_->text->first_y + workarea().workHeight());
1143                         updateScrollbar();
1144                 }
1145                 return;
1146         }
1147
1148         int y = text->first_y + workarea().workHeight();
1149         if (text->inset_owner && !text->first_y) {
1150                 y -= (bv_->text->cursor.iy()
1151                           - bv_->text->first_y
1152                           + bv_->theLockingInset()->insetInInsetY());
1153         }
1154
1155         text->getRowNearY(y);
1156
1157         Row * cursorrow = text->cursor.row();
1158         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea().workHeight());
1159         finishUndo();
1160
1161         int new_y;
1162         if (cursorrow == bv_->text->cursor.row()) {
1163                 // we have a row which is higher than the workarea so we leave the
1164                 // cursor on the start of the row and move only the draw down as soon
1165                 // as we move the cursor or do something while inside the row (it may
1166                 // span several workarea-heights) we'll move to the top again, but this
1167                 // is better than just jump down and only display part of the row.
1168                 new_y = bv_->text->first_y + workarea().workHeight();
1169         } else {
1170                 if (text->inset_owner) {
1171                         new_y = bv_->text->cursor.iy()
1172                                 + bv_->theLockingInset()->insetInInsetY()
1173                                 + y - text->cursor.row()->baseline();
1174                 } else {
1175                         new_y =  text->cursor.y() - text->cursor.row()->baseline();
1176                 }
1177         }
1178         screen().draw(bv_->text, bv_, new_y);
1179         if (text->cursor.row()->next()) {
1180                 LyXCursor cur;
1181                 text->setCursor(bv_, cur, text->cursor.row()->next()->par(),
1182                                                 text->cursor.row()->next()->pos(), false);
1183                 if (cur.y() < int(text->first_y + workarea().workHeight())) {
1184                         text->cursorDown(bv_, true);
1185                 }
1186         }
1187         updateScrollbar();
1188 }
1189
1190
1191 bool BufferView::Pimpl::available() const
1192 {
1193         if (buffer_ && bv_->text)
1194                 return true;
1195         return false;
1196 }
1197
1198
1199 void BufferView::Pimpl::beforeChange(LyXText * text)
1200 {
1201         toggleSelection();
1202         text->clearSelection();
1203 }
1204
1205
1206 void BufferView::Pimpl::savePosition(unsigned int i)
1207 {
1208         if (i >= saved_positions_num)
1209                 return;
1210         saved_positions[i] = Position(buffer_->fileName(),
1211                                       bv_->text->cursor.par()->id(),
1212                                       bv_->text->cursor.pos());
1213         if (i > 0) {
1214                 ostringstream str;
1215                 str << _("Saved bookmark") << ' ' << i;
1216                 owner_->message(str.str().c_str());
1217         }
1218 }
1219
1220
1221 void BufferView::Pimpl::restorePosition(unsigned int i)
1222 {
1223         if (i >= saved_positions_num)
1224                 return;
1225
1226         string const fname = saved_positions[i].filename;
1227
1228         beforeChange(bv_->text);
1229
1230         if (fname != buffer_->fileName()) {
1231                 Buffer * b = bufferlist.exists(fname) ?
1232                         bufferlist.getBuffer(fname) :
1233                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1234                 if (b != 0) buffer(b);
1235         }
1236
1237         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1238         if (!par)
1239                 return;
1240
1241         bv_->text->setCursor(bv_, par,
1242                              min(par->size(), saved_positions[i].par_pos));
1243
1244         update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1245         if (i > 0) {
1246                 ostringstream str;
1247                 str << _("Moved to bookmark") << ' ' << i;
1248                 owner_->message(str.str().c_str());
1249         }
1250 }
1251
1252
1253 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1254 {
1255         if (i >= saved_positions_num)
1256                 return false;
1257
1258         return !saved_positions[i].filename.empty();
1259 }
1260
1261
1262 void BufferView::Pimpl::switchKeyMap()
1263 {
1264         if (!lyxrc.rtl_support)
1265                 return;
1266
1267         LyXText * text = bv_->getLyXText();
1268         if (text->real_current_font.isRightToLeft()
1269             && !(bv_->theLockingInset()
1270                  && bv_->theLockingInset()->lyxCode()== Inset::ERT_CODE))
1271         {
1272                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1273                         owner_->getIntl()->KeyMapSec();
1274         } else {
1275                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1276                         owner_->getIntl()->KeyMapPrim();
1277         }
1278 }
1279
1280
1281 void BufferView::Pimpl::insetUnlock()
1282 {
1283         if (bv_->theLockingInset()) {
1284                 bv_->theLockingInset()->insetUnlock(bv_);
1285                 bv_->theLockingInset(0);
1286                 finishUndo();
1287         }
1288 }
1289
1290
1291 void BufferView::Pimpl::showCursor()
1292 {
1293         if (bv_->theLockingInset())
1294                 bv_->theLockingInset()->showInsetCursor(bv_);
1295         else
1296                 screen().showCursor(bv_->text, bv_);
1297 }
1298
1299
1300 void BufferView::Pimpl::hideCursor()
1301 {
1302         if (!bv_->theLockingInset())
1303                 screen().hideCursor();
1304 }
1305
1306
1307 void BufferView::Pimpl::toggleSelection(bool b)
1308 {
1309         if (bv_->theLockingInset())
1310                 bv_->theLockingInset()->toggleSelection(bv_, b);
1311         screen().toggleSelection(bv_->text, bv_, b);
1312 }
1313
1314
1315 void BufferView::Pimpl::toggleToggle()
1316 {
1317         screen().toggleToggle(bv_->text, bv_);
1318 }
1319
1320
1321 void BufferView::Pimpl::center()
1322 {
1323         LyXText * t = bv_->text;
1324
1325         beforeChange(t);
1326         int const half_height = workarea().workHeight() / 2;
1327         int new_y = 0;
1328
1329         if (t->cursor.y() > half_height) {
1330                 new_y = t->cursor.y() - half_height;
1331         }
1332
1333         // FIXME: can we do this w/o calling screen directly ?
1334         // This updates first_y but means the fitCursor() call
1335         // from the update(FITCUR) doesn't realise that we might
1336         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
1337         // the scrollbar to be updated as it should, so we have
1338         // to do it manually. Any operation that does a center()
1339         // and also might have moved first_y must make sure to call
1340         // updateScrollbar() currently. Never mind that this is a
1341         // pretty obfuscated way of updating t->first_y
1342         screen().draw(t, bv_, new_y);
1343
1344         update(t, BufferView::SELECT | BufferView::FITCUR);
1345 }
1346
1347
1348 void BufferView::Pimpl::pasteClipboard(bool asPara)
1349 {
1350         if (!buffer_)
1351                 return;
1352
1353         screen().hideCursor();
1354         beforeChange(bv_->text);
1355
1356         string const clip(workarea().getClipboard());
1357
1358         if (clip.empty())
1359                 return;
1360
1361         if (asPara) {
1362                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1363         } else {
1364                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1365         }
1366         bv_->getLyXText()->clearSelection();
1367         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1368 }
1369
1370
1371 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1372 {
1373         workarea().putClipboard(stuff);
1374 }
1375
1376
1377 /*
1378  * Dispatch functions for actions which can be valid for BufferView->text
1379  * and/or InsetText->text!!!
1380  */
1381
1382
1383 inline
1384 void BufferView::Pimpl::moveCursorUpdate(bool selecting, bool fitcur)
1385 {
1386         LyXText * lt = bv_->getLyXText();
1387
1388         if (selecting || lt->selection.mark()) {
1389                 lt->setSelection(bv_);
1390                 if (lt->bv_owner)
1391                         toggleToggle();
1392                 else
1393                         updateInset(lt->inset_owner, false);
1394         }
1395         if (lt->bv_owner) {
1396                 if (fitcur)
1397                         update(lt, BufferView::SELECT|BufferView::FITCUR);
1398                 else
1399                         update(lt, BufferView::SELECT);
1400                 showCursor();
1401         } else if (bv_->text->status() != LyXText::UNCHANGED) {
1402                 bv_->theLockingInset()->hideInsetCursor(bv_);
1403                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1404                 showCursor();
1405         }
1406
1407         if (!lt->selection.set())
1408                 workarea().haveSelection(false);
1409
1410         switchKeyMap();
1411 }
1412
1413
1414 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1415 {
1416         LyXCursor cursor = bv_->getLyXText()->cursor;
1417         Buffer::inset_iterator it =
1418                 find_if(Buffer::inset_iterator(
1419                         cursor.par(), cursor.pos()),
1420                         buffer_->inset_iterator_end(),
1421                         lyx::compare_memfun(&Inset::lyxCode, code));
1422         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1423 }
1424
1425
1426 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1427 {
1428         string filename = filen;
1429
1430         if (filename.empty()) {
1431                 // Launch a file browser
1432                 string initpath = lyxrc.document_path;
1433
1434                 if (available()) {
1435                         string const trypath = owner_->buffer()->filePath();
1436                         // If directory is writeable, use this as default.
1437                         if (IsDirWriteable(trypath))
1438                                 initpath = trypath;
1439                 }
1440
1441                 FileDialog fileDlg(bv_->owner(),
1442                                    _("Select LyX document to insert"),
1443                         LFUN_FILE_INSERT,
1444                         make_pair(string(_("Documents|#o#O")),
1445                                   string(lyxrc.document_path)),
1446                         make_pair(string(_("Examples|#E#e")),
1447                                   string(AddPath(system_lyxdir, "examples"))));
1448
1449                 FileDialog::Result result =
1450                         fileDlg.Select(initpath,
1451                                        _("*.lyx| LyX Documents (*.lyx)"));
1452
1453                 if (result.first == FileDialog::Later)
1454                         return;
1455
1456                 filename = result.second;
1457
1458                 // check selected filename
1459                 if (filename.empty()) {
1460                         owner_->message(_("Canceled."));
1461                         return;
1462                 }
1463         }
1464
1465         // get absolute path of file and add ".lyx" to the filename if
1466         // necessary
1467         filename = FileSearch(string(), filename, "lyx");
1468
1469         string const disp_fn(MakeDisplayPath(filename));
1470
1471         ostringstream s1;
1472         s1 << _("Inserting document") << ' '
1473            << disp_fn << " ...";
1474         owner_->message(s1.str().c_str());
1475         bool const res = bv_->insertLyXFile(filename);
1476         if (res) {
1477                 ostringstream str;
1478                 str << _("Document") << ' ' << disp_fn
1479                     << ' ' << _("inserted.");
1480                 owner_->message(str.str().c_str());
1481         } else {
1482                 ostringstream str;
1483                 str << _("Could not insert document") << ' '
1484                     << disp_fn;
1485                 owner_->message(str.str().c_str());
1486         }
1487 }
1488
1489
1490 bool BufferView::Pimpl::dispatch(FuncRequest const & ev)
1491 {
1492         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1493           << ev.action <<"] arg[" << ev.argument << "]" << endl;
1494
1495         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
1496
1497         switch (ev.action) {
1498                 // --- Misc -------------------------------------------
1499         case LFUN_APPENDIX:
1500         {
1501                 if (available()) {
1502                         LyXText * lt = bv_->getLyXText();
1503                         lt->toggleAppendix(bv_);
1504                         update(lt,
1505                                BufferView::SELECT
1506                                | BufferView::FITCUR
1507                                | BufferView::CHANGE);
1508                 }
1509         }
1510         break;
1511
1512         case LFUN_TOC_INSERT:
1513         {
1514                 InsetCommandParams p;
1515                 p.setCmdName("tableofcontents");
1516                 Inset * inset = new InsetTOC(p);
1517                 if (!insertInset(inset, tclass.defaultLayoutName()))
1518                         delete inset;
1519                 break;
1520         }
1521
1522         case LFUN_SCROLL_INSET:
1523                 // this is not handled here as this funktion is only aktive
1524                 // if we have a locking_inset and that one is (or contains)
1525                 // a tabular-inset
1526                 break;
1527
1528         case LFUN_INSET_GRAPHICS:
1529         {
1530                 Inset * new_inset = new InsetGraphics;
1531                 if (!insertInset(new_inset)) {
1532                         delete new_inset;
1533                 } else {
1534                         // this is need because you don't use a inset->Edit()
1535                         updateInset(new_inset, true);
1536                         new_inset->edit(bv_);
1537                 }
1538                 break;
1539         }
1540
1541         case LFUN_PASTE:
1542                 bv_->paste();
1543                 switchKeyMap();
1544                 break;
1545
1546         case LFUN_PASTESELECTION:
1547                 pasteClipboard(ev.argument == "paragraph");
1548                 break;
1549
1550         case LFUN_CUT:
1551                 bv_->cut();
1552                 break;
1553
1554         case LFUN_COPY:
1555                 bv_->copy();
1556                 break;
1557
1558         case LFUN_LAYOUT_COPY:
1559                 bv_->copyEnvironment();
1560                 break;
1561
1562         case LFUN_LAYOUT_PASTE:
1563                 bv_->pasteEnvironment();
1564                 switchKeyMap();
1565                 break;
1566
1567         case LFUN_GOTOERROR:
1568                 gotoInset(Inset::ERROR_CODE, false);
1569                 break;
1570
1571         case LFUN_GOTONOTE:
1572                 gotoInset(Inset::NOTE_CODE, false);
1573                 break;
1574
1575         case LFUN_REFERENCE_GOTO:
1576         {
1577                 vector<Inset::Code> tmp;
1578                 tmp.push_back(Inset::LABEL_CODE);
1579                 tmp.push_back(Inset::REF_CODE);
1580                 gotoInset(tmp, true);
1581                 break;
1582         }
1583
1584         case LFUN_HYPHENATION:
1585                 specialChar(InsetSpecialChar::HYPHENATION);
1586                 break;
1587
1588         case LFUN_LIGATURE_BREAK:
1589                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1590                 break;
1591
1592         case LFUN_LDOTS:
1593                 specialChar(InsetSpecialChar::LDOTS);
1594                 break;
1595
1596         case LFUN_END_OF_SENTENCE:
1597                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1598                 break;
1599
1600         case LFUN_MENU_SEPARATOR:
1601                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1602                 break;
1603
1604         case LFUN_HFILL:
1605                 hfill();
1606                 break;
1607
1608         case LFUN_DEPTH_MIN:
1609                 changeDepth(bv_, bv_->getLyXText(), -1);
1610                 break;
1611
1612         case LFUN_DEPTH_PLUS:
1613                 changeDepth(bv_, bv_->getLyXText(), 1);
1614                 break;
1615
1616         case LFUN_FREE:
1617                 owner_->getDialogs()->setUserFreeFont();
1618                 break;
1619
1620         case LFUN_FILE_INSERT:
1621                 MenuInsertLyXFile(ev.argument);
1622                 break;
1623
1624         case LFUN_FILE_INSERT_ASCII_PARA:
1625                 InsertAsciiFile(bv_, ev.argument, true);
1626                 break;
1627
1628         case LFUN_FILE_INSERT_ASCII:
1629                 InsertAsciiFile(bv_, ev.argument, false);
1630                 break;
1631
1632         case LFUN_LAYOUT:
1633         {
1634                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1635                                     << ev.argument << endl;
1636
1637                 // This is not the good solution to the empty argument
1638                 // problem, but it will hopefully suffice for 1.2.0.
1639                 // The correct solution would be to augument the
1640                 // function list/array with information about what
1641                 // functions needs arguments and their type.
1642                 if (ev.argument.empty()) {
1643                         owner_->getLyXFunc()->setErrorMessage(
1644                                 _("LyX function 'layout' needs an argument."));
1645                         break;
1646                 }
1647
1648                 // Derive layout number from given argument (string)
1649                 // and current buffer's textclass (number). */
1650                 bool hasLayout = tclass.hasLayout(ev.argument);
1651                 string layout = ev.argument;
1652
1653                 // If the entry is obsolete, use the new one instead.
1654                 if (hasLayout) {
1655                         string const & obs = tclass[layout]->obsoleted_by();
1656                         if (!obs.empty())
1657                                 layout = obs;
1658                 }
1659
1660                 if (!hasLayout) {
1661                         owner_->getLyXFunc()->setErrorMessage(
1662                                 string(N_("Layout ")) + ev.argument +
1663                                 N_(" not known"));
1664                         break;
1665                 }
1666
1667                 bool change_layout = (current_layout != layout);
1668                 LyXText * lt = bv_->getLyXText();
1669                 if (!change_layout && lt->selection.set() &&
1670                         lt->selection.start.par() != lt->selection.end.par())
1671                 {
1672                         Paragraph * spar = lt->selection.start.par();
1673                         Paragraph * epar = lt->selection.end.par()->next();
1674                         while(spar != epar) {
1675                                 if (spar->layout()->name() != current_layout) {
1676                                         change_layout = true;
1677                                         break;
1678                                 }
1679                         }
1680                 }
1681                 if (change_layout) {
1682                         hideCursor();
1683                         current_layout = layout;
1684                         update(lt,
1685                                BufferView::SELECT
1686                                | BufferView::FITCUR);
1687                         lt->setLayout(bv_, layout);
1688                         owner_->setLayout(layout);
1689                         update(lt,
1690                                BufferView::SELECT
1691                                | BufferView::FITCUR
1692                                | BufferView::CHANGE);
1693                         switchKeyMap();
1694                 }
1695         }
1696         break;
1697
1698         case LFUN_LANGUAGE:
1699                 lang(bv_, ev.argument);
1700                 switchKeyMap();
1701                 owner_->view_state_changed();
1702                 break;
1703
1704         case LFUN_EMPH:
1705                 emph(bv_);
1706                 owner_->view_state_changed();
1707                 break;
1708
1709         case LFUN_BOLD:
1710                 bold(bv_);
1711                 owner_->view_state_changed();
1712                 break;
1713
1714         case LFUN_NOUN:
1715                 noun(bv_);
1716                 owner_->view_state_changed();
1717                 break;
1718
1719         case LFUN_CODE:
1720                 code(bv_);
1721                 owner_->view_state_changed();
1722                 break;
1723
1724         case LFUN_SANS:
1725                 sans(bv_);
1726                 owner_->view_state_changed();
1727                 break;
1728
1729         case LFUN_ROMAN:
1730                 roman(bv_);
1731                 owner_->view_state_changed();
1732                 break;
1733
1734         case LFUN_DEFAULT:
1735                 styleReset(bv_);
1736                 owner_->view_state_changed();
1737                 break;
1738
1739         case LFUN_UNDERLINE:
1740                 underline(bv_);
1741                 owner_->view_state_changed();
1742                 break;
1743
1744         case LFUN_FONT_SIZE:
1745                 fontSize(bv_, ev.argument);
1746                 owner_->view_state_changed();
1747                 break;
1748
1749         case LFUN_FONT_STATE:
1750                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1751                 break;
1752
1753         case LFUN_UPCASE_WORD:
1754         {
1755                 LyXText * lt = bv_->getLyXText();
1756
1757                 update(lt,
1758                        BufferView::SELECT
1759                        | BufferView::FITCUR);
1760                 lt->changeCase(bv_, LyXText::text_uppercase);
1761                 if (lt->inset_owner)
1762                         updateInset(lt->inset_owner, true);
1763                 update(lt,
1764                        BufferView::SELECT
1765                        | BufferView::FITCUR
1766                        | BufferView::CHANGE);
1767         }
1768         break;
1769
1770         case LFUN_LOWCASE_WORD:
1771         {
1772                 LyXText * lt = bv_->getLyXText();
1773
1774                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1775                 lt->changeCase(bv_, LyXText::text_lowercase);
1776                 if (lt->inset_owner)
1777                         updateInset(lt->inset_owner, true);
1778                 update(lt,
1779                        BufferView::SELECT
1780                        | BufferView::FITCUR
1781                        | BufferView::CHANGE);
1782         }
1783         break;
1784
1785         case LFUN_CAPITALIZE_WORD:
1786         {
1787                 LyXText * lt = bv_->getLyXText();
1788
1789                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1790                 lt->changeCase(bv_, LyXText::text_capitalization);
1791                 if (lt->inset_owner)
1792                         updateInset(lt->inset_owner, true);
1793                 update(lt,
1794                        BufferView::SELECT
1795                        | BufferView::FITCUR
1796                        | BufferView::CHANGE);
1797         }
1798         break;
1799
1800         case LFUN_TRANSPOSE_CHARS:
1801         {
1802                 LyXText * lt = bv_->getLyXText();
1803
1804                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1805                 lt->transposeChars(*bv_);
1806                 if (lt->inset_owner)
1807                         updateInset(lt->inset_owner, true);
1808                 update(lt,
1809                        BufferView::SELECT
1810                        | BufferView::FITCUR
1811                        | BufferView::CHANGE);
1812         }
1813         break;
1814
1815
1816         case LFUN_INSERT_LABEL:
1817                 MenuInsertLabel(bv_, ev.argument);
1818                 break;
1819
1820         case LFUN_REF_INSERT:
1821                 if (ev.argument.empty()) {
1822                         InsetCommandParams p("ref");
1823                         owner_->getDialogs()->createRef(p.getAsString());
1824                 } else {
1825                         InsetCommandParams p;
1826                         p.setFromString(ev.argument);
1827
1828                         InsetRef * inset = new InsetRef(p, *buffer_);
1829                         if (!insertInset(inset))
1830                                 delete inset;
1831                         else
1832                                 updateInset(inset, true);
1833                 }
1834                 break;
1835
1836         case LFUN_BOOKMARK_SAVE:
1837                 savePosition(strToUnsignedInt(ev.argument));
1838                 break;
1839
1840         case LFUN_BOOKMARK_GOTO:
1841                 restorePosition(strToUnsignedInt(ev.argument));
1842                 break;
1843
1844         case LFUN_REF_GOTO:
1845         {
1846                 string label = ev.argument;
1847                 if (label.empty()) {
1848                         InsetRef * inset =
1849                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1850                         if (inset) {
1851                                 label = inset->getContents();
1852                                 savePosition(0);
1853                         }
1854                 }
1855
1856                 if (!label.empty()) {
1857                         //bv_->savePosition(0);
1858                         if (!bv_->gotoLabel(label))
1859                                 Alert::alert(_("Error"),
1860                                            _("Couldn't find this label"),
1861                                            _("in current document."));
1862                 }
1863         }
1864         break;
1865
1866                 // --- Cursor Movements -----------------------------
1867         case LFUN_RIGHT:
1868         {
1869                 LyXText * lt = bv_->getLyXText();
1870
1871                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1872                 if (!lt->selection.mark())
1873                         beforeChange(lt);
1874                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1875                 if (is_rtl)
1876                         lt->cursorLeft(bv_, false);
1877                 if (lt->cursor.pos() < lt->cursor.par()->size()
1878                     && lt->cursor.par()->isInset(lt->cursor.pos())
1879                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1880                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1881                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1882                         if (is_rtl)
1883                                 tmpinset->edit(bv_, false);
1884                         else
1885                                 tmpinset->edit(bv_);
1886                         break;
1887                 }
1888                 if (!is_rtl)
1889                         lt->cursorRight(bv_, false);
1890                 finishUndo();
1891                 moveCursorUpdate(false);
1892                 owner_->view_state_changed();
1893         }
1894         break;
1895
1896         case LFUN_LEFT:
1897         {
1898                 // This is soooo ugly. Isn`t it possible to make
1899                 // it simpler? (Lgb)
1900                 LyXText * lt = bv_->getLyXText();
1901                 bool const is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1902                 if (!lt->selection.mark())
1903                         beforeChange(lt);
1904                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1905                 LyXCursor const cur = lt->cursor;
1906                 if (!is_rtl)
1907                         lt->cursorLeft(bv_, false);
1908                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1909                     lt->cursor.pos() < lt->cursor.par()->size() &&
1910                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
1911                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1912                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1913                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1914                         if (is_rtl)
1915                                 tmpinset->edit(bv_);
1916                         else
1917                                 tmpinset->edit(bv_, false);
1918                         break;
1919                 }
1920                 if  (is_rtl)
1921                         lt->cursorRight(bv_, false);
1922
1923                 finishUndo();
1924                 moveCursorUpdate(false);
1925                 owner_->view_state_changed();
1926         }
1927         break;
1928
1929         case LFUN_UP:
1930         {
1931                 LyXText * lt = bv_->getLyXText();
1932
1933                 if (!lt->selection.mark())
1934                         beforeChange(lt);
1935                 update(lt, BufferView::UPDATE);
1936                 lt->cursorUp(bv_);
1937                 finishUndo();
1938                 moveCursorUpdate(false);
1939                 owner_->view_state_changed();
1940         }
1941         break;
1942
1943         case LFUN_DOWN:
1944         {
1945                 LyXText * lt = bv_->getLyXText();
1946
1947                 if (!lt->selection.mark())
1948                         beforeChange(lt);
1949                 update(lt, BufferView::UPDATE);
1950                 lt->cursorDown(bv_);
1951                 finishUndo();
1952                 moveCursorUpdate(false);
1953                 owner_->view_state_changed();
1954         }
1955         break;
1956
1957         case LFUN_UP_PARAGRAPH:
1958         {
1959                 LyXText * lt = bv_->getLyXText();
1960
1961                 if (!lt->selection.mark())
1962                         beforeChange(lt);
1963                 update(lt, BufferView::UPDATE);
1964                 lt->cursorUpParagraph(bv_);
1965                 finishUndo();
1966                 moveCursorUpdate(false);
1967                 owner_->view_state_changed();
1968         }
1969         break;
1970
1971         case LFUN_DOWN_PARAGRAPH:
1972         {
1973                 LyXText * lt = bv_->getLyXText();
1974
1975                 if (!lt->selection.mark())
1976                         beforeChange(lt);
1977                 update(lt, BufferView::UPDATE);
1978                 lt->cursorDownParagraph(bv_);
1979                 finishUndo();
1980                 moveCursorUpdate(false);
1981                 owner_->view_state_changed();
1982         }
1983         break;
1984
1985         case LFUN_PRIOR:
1986         {
1987                 LyXText * lt = bv_->getLyXText();
1988
1989                 if (!lt->selection.mark())
1990                         beforeChange(lt);
1991                 update(lt, BufferView::UPDATE);
1992                 cursorPrevious(lt);
1993                 finishUndo();
1994                 moveCursorUpdate(false, false);
1995                 owner_->view_state_changed();
1996         }
1997         break;
1998
1999         case LFUN_NEXT:
2000         {
2001                 LyXText * lt = bv_->getLyXText();
2002
2003                 if (!lt->selection.mark())
2004                         beforeChange(lt);
2005                 update(lt, BufferView::UPDATE);
2006                 cursorNext(lt);
2007                 finishUndo();
2008                 moveCursorUpdate(false, false);
2009                 owner_->view_state_changed();
2010         }
2011         break;
2012
2013         case LFUN_HOME:
2014         {
2015                 LyXText * lt = bv_->getLyXText();
2016
2017                 if (!lt->selection.mark())
2018                         beforeChange(lt);
2019                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2020                 lt->cursorHome(bv_);
2021                 finishUndo();
2022                 moveCursorUpdate(false);
2023                 owner_->view_state_changed();
2024         }
2025         break;
2026
2027         case LFUN_END:
2028         {
2029                 LyXText * lt = bv_->getLyXText();
2030
2031                 if (!lt->selection.mark())
2032                         beforeChange(lt);
2033                 update(lt,
2034                        BufferView::SELECT|BufferView::FITCUR);
2035                 lt->cursorEnd(bv_);
2036                 finishUndo();
2037                 moveCursorUpdate(false);
2038                 owner_->view_state_changed();
2039         }
2040         break;
2041
2042         case LFUN_SHIFT_TAB:
2043         case LFUN_TAB:
2044         {
2045                 LyXText * lt = bv_->getLyXText();
2046
2047                 if (!lt->selection.mark())
2048                         beforeChange(lt);
2049                 update(lt,
2050                        BufferView::SELECT|BufferView::FITCUR);
2051                 lt->cursorTab(bv_);
2052                 finishUndo();
2053                 moveCursorUpdate(false);
2054                 owner_->view_state_changed();
2055         }
2056         break;
2057
2058         case LFUN_WORDRIGHT:
2059         {
2060                 LyXText * lt = bv_->getLyXText();
2061
2062                 if (!lt->selection.mark())
2063                         beforeChange(lt);
2064                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2065                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2066                         lt->cursorLeftOneWord(bv_);
2067                 else
2068                         lt->cursorRightOneWord(bv_);
2069                 finishUndo();
2070                 moveCursorUpdate(false);
2071                 owner_->view_state_changed();
2072         }
2073         break;
2074
2075         case LFUN_WORDLEFT:
2076         {
2077                 LyXText * lt = bv_->getLyXText();
2078
2079                 if (!lt->selection.mark())
2080                         beforeChange(lt);
2081                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2082                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2083                         lt->cursorRightOneWord(bv_);
2084                 else
2085                         lt->cursorLeftOneWord(bv_);
2086                 finishUndo();
2087                 moveCursorUpdate(false);
2088                 owner_->view_state_changed();
2089         }
2090         break;
2091
2092         case LFUN_BEGINNINGBUF:
2093         {
2094                 LyXText * lt = bv_->getLyXText();
2095
2096                 if (!lt->selection.mark())
2097                         beforeChange(lt);
2098                 update(lt,
2099                        BufferView::SELECT|BufferView::FITCUR);
2100                 lt->cursorTop(bv_);
2101                 finishUndo();
2102                 moveCursorUpdate(false);
2103                 owner_->view_state_changed();
2104         }
2105         break;
2106
2107         case LFUN_ENDBUF:
2108         {
2109                 LyXText * lt = bv_->getLyXText();
2110
2111                 if (!lt->selection.mark())
2112                         beforeChange(lt);
2113                 update(lt,
2114                        BufferView::SELECT|BufferView::FITCUR);
2115                 lt->cursorBottom(bv_);
2116                 finishUndo();
2117                 moveCursorUpdate(false);
2118                 owner_->view_state_changed();
2119         }
2120         break;
2121
2122                 /* cursor selection ---------------------------- */
2123         case LFUN_RIGHTSEL:
2124         {
2125                 LyXText * lt = bv_->getLyXText();
2126
2127                 update(lt,
2128                        BufferView::SELECT|BufferView::FITCUR);
2129                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2130                         lt->cursorLeft(bv_);
2131                 else
2132                         lt->cursorRight(bv_);
2133                 finishUndo();
2134                 moveCursorUpdate(true);
2135                 owner_->view_state_changed();
2136         }
2137         break;
2138
2139         case LFUN_LEFTSEL:
2140         {
2141                 LyXText * lt = bv_->getLyXText();
2142
2143                 update(lt,
2144                        BufferView::SELECT|BufferView::FITCUR);
2145                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2146                         lt->cursorRight(bv_);
2147                 else
2148                         lt->cursorLeft(bv_);
2149                 finishUndo();
2150                 moveCursorUpdate(true);
2151                 owner_->view_state_changed();
2152         }
2153         break;
2154
2155         case LFUN_UPSEL:
2156         {
2157                 LyXText * lt = bv_->getLyXText();
2158
2159                 update(lt,
2160                        BufferView::SELECT|BufferView::FITCUR);
2161                 lt->cursorUp(bv_, true);
2162                 finishUndo();
2163                 moveCursorUpdate(true);
2164                 owner_->view_state_changed();
2165         }
2166         break;
2167
2168         case LFUN_DOWNSEL:
2169         {
2170                 LyXText * lt = bv_->getLyXText();
2171
2172                 update(lt,
2173                        BufferView::SELECT|BufferView::FITCUR);
2174                 lt->cursorDown(bv_, true);
2175                 finishUndo();
2176                 moveCursorUpdate(true);
2177                 owner_->view_state_changed();
2178         }
2179         break;
2180
2181         case LFUN_UP_PARAGRAPHSEL:
2182         {
2183                 LyXText * lt = bv_->getLyXText();
2184
2185                 update(lt,
2186                        BufferView::SELECT|BufferView::FITCUR);
2187                 lt->cursorUpParagraph(bv_);
2188                 finishUndo();
2189                 moveCursorUpdate(true);
2190                 owner_->view_state_changed();
2191         }
2192         break;
2193
2194         case LFUN_DOWN_PARAGRAPHSEL:
2195         {
2196                 LyXText * lt = bv_->getLyXText();
2197
2198                 update(lt,
2199                        BufferView::SELECT|BufferView::FITCUR);
2200                 lt->cursorDownParagraph(bv_);
2201                 finishUndo();
2202                 moveCursorUpdate(true);
2203                 owner_->view_state_changed();
2204         }
2205         break;
2206
2207         case LFUN_PRIORSEL:
2208         {
2209                 LyXText * lt = bv_->getLyXText();
2210
2211                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2212                 cursorPrevious(lt);
2213                 finishUndo();
2214                 moveCursorUpdate(true);
2215                 owner_->view_state_changed();
2216         }
2217         break;
2218
2219         case LFUN_NEXTSEL:
2220         {
2221                 LyXText * lt = bv_->getLyXText();
2222
2223                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2224                 cursorNext(lt);
2225                 finishUndo();
2226                 moveCursorUpdate(true);
2227                 owner_->view_state_changed();
2228         }
2229         break;
2230
2231         case LFUN_HOMESEL:
2232         {
2233                 LyXText * lt = bv_->getLyXText();
2234
2235                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2236                 lt->cursorHome(bv_);
2237                 finishUndo();
2238                 moveCursorUpdate(true);
2239                 owner_->view_state_changed();
2240         }
2241         break;
2242
2243         case LFUN_ENDSEL:
2244         {
2245                 LyXText * lt = bv_->getLyXText();
2246
2247                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2248                 lt->cursorEnd(bv_);
2249                 finishUndo();
2250                 moveCursorUpdate(true);
2251                 owner_->view_state_changed();
2252         }
2253         break;
2254
2255         case LFUN_WORDRIGHTSEL:
2256         {
2257                 LyXText * lt = bv_->getLyXText();
2258
2259                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2260                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2261                         lt->cursorLeftOneWord(bv_);
2262                 else
2263                         lt->cursorRightOneWord(bv_);
2264                 finishUndo();
2265                 moveCursorUpdate(true);
2266                 owner_->view_state_changed();
2267         }
2268         break;
2269
2270         case LFUN_WORDLEFTSEL:
2271         {
2272                 LyXText * lt = bv_->getLyXText();
2273
2274                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2275                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2276                         lt->cursorRightOneWord(bv_);
2277                 else
2278                         lt->cursorLeftOneWord(bv_);
2279                 finishUndo();
2280                 moveCursorUpdate(true);
2281                 owner_->view_state_changed();
2282         }
2283         break;
2284
2285         case LFUN_BEGINNINGBUFSEL:
2286         {
2287                 LyXText * lt = bv_->getLyXText();
2288
2289                 if (lt->inset_owner)
2290                         break;
2291                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2292                 lt->cursorTop(bv_);
2293                 finishUndo();
2294                 moveCursorUpdate(true);
2295                 owner_->view_state_changed();
2296         }
2297         break;
2298
2299         case LFUN_ENDBUFSEL:
2300         {
2301                 LyXText * lt = bv_->getLyXText();
2302
2303                 if (lt->inset_owner)
2304                         break;
2305                 update(lt,
2306                        BufferView::SELECT|BufferView::FITCUR);
2307                 lt->cursorBottom(bv_);
2308                 finishUndo();
2309                 moveCursorUpdate(true);
2310                 owner_->view_state_changed();
2311         }
2312         break;
2313
2314                 // --- text changing commands ------------------------
2315         case LFUN_BREAKLINE:
2316         {
2317                 LyXText * lt = bv_->getLyXText();
2318
2319                 beforeChange(lt);
2320                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2321                 update(lt,
2322                        BufferView::SELECT
2323                        | BufferView::FITCUR
2324                        | BufferView::CHANGE);
2325                 lt->setCursor(bv_, lt->cursor.par(), lt->cursor.pos());
2326                 moveCursorUpdate(false);
2327         }
2328         break;
2329
2330         case LFUN_PROTECTEDSPACE:
2331         {
2332                 LyXText * lt = bv_->getLyXText();
2333                 LyXLayout_ptr const & style = lt->cursor.par()->layout();
2334
2335                 if (style->free_spacing) {
2336                         lt->insertChar(bv_, ' ');
2337                         update(lt,
2338                                BufferView::SELECT
2339                                | BufferView::FITCUR
2340                                | BufferView::CHANGE);
2341                 } else {
2342                         specialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
2343                 }
2344                 moveCursorUpdate(false);
2345         }
2346         break;
2347
2348         case LFUN_SETMARK:
2349         {
2350                 LyXText * lt = bv_->getLyXText();
2351
2352                 if (lt->selection.mark()) {
2353                         beforeChange(lt);
2354                         update(lt,
2355                                BufferView::SELECT
2356                                | BufferView::FITCUR);
2357                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2358                 } else {
2359                         beforeChange(lt);
2360                         lt->selection.mark(true);
2361                         update(lt,
2362                                BufferView::SELECT
2363                                | BufferView::FITCUR);
2364                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2365                 }
2366                 lt->selection.cursor = lt->cursor;
2367         }
2368         break;
2369
2370         case LFUN_DELETE:
2371         {
2372                 LyXText * lt = bv_->getLyXText();
2373
2374                 if (!lt->selection.set()) {
2375                         lt->Delete(bv_);
2376                         lt->selection.cursor = lt->cursor;
2377                         update(lt,
2378                                BufferView::SELECT
2379                                | BufferView::FITCUR
2380                                | BufferView::CHANGE);
2381                         // It is possible to make it a lot faster still
2382                         // just comment out the line below...
2383                         showCursor();
2384                 } else {
2385                         bv_->cut(false);
2386                 }
2387                 moveCursorUpdate(false);
2388                 owner_->view_state_changed();
2389                 switchKeyMap();
2390         }
2391         break;
2392
2393         case LFUN_DELETE_SKIP:
2394         {
2395                 LyXText * lt = bv_->getLyXText();
2396
2397                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2398
2399                 LyXCursor cursor = lt->cursor;
2400
2401                 if (!lt->selection.set()) {
2402                         if (cursor.pos() == cursor.par()->size()) {
2403                                 lt->cursorRight(bv_);
2404                                 cursor = lt->cursor;
2405                                 if (cursor.pos() == 0
2406                                     && !(cursor.par()->params().spaceTop()
2407                                          == VSpace (VSpace::NONE))) {
2408                                         lt->setParagraph
2409                                                 (bv_,
2410                                                  cursor.par()->params().lineTop(),
2411                                                  cursor.par()->params().lineBottom(),
2412                                                  cursor.par()->params().pagebreakTop(),
2413                                                  cursor.par()->params().pagebreakBottom(),
2414                                                  VSpace(VSpace::NONE),
2415                                                  cursor.par()->params().spaceBottom(),
2416                                                  cursor.par()->params().spacing(),
2417                                                  cursor.par()->params().align(),
2418                                                  cursor.par()->params().labelWidthString(), 0);
2419                                         lt->cursorLeft(bv_);
2420                                         update(lt,
2421                                                BufferView::SELECT
2422                                                | BufferView::FITCUR
2423                                                | BufferView::CHANGE);
2424                                 } else {
2425                                         lt->cursorLeft(bv_);
2426                                         lt->Delete(bv_);
2427                                         lt->selection.cursor = lt->cursor;
2428                                         update(lt,
2429                                                BufferView::SELECT
2430                                                | BufferView::FITCUR
2431                                                | BufferView::CHANGE);
2432                                 }
2433                         } else {
2434                                 lt->Delete(bv_);
2435                                 lt->selection.cursor = lt->cursor;
2436                                 update(lt,
2437                                        BufferView::SELECT
2438                                        | BufferView::FITCUR
2439                                        | BufferView::CHANGE);
2440                         }
2441                 } else {
2442                         bv_->cut(false);
2443                 }
2444         }
2445         break;
2446
2447         /* -------> Delete word forward. */
2448         case LFUN_DELETE_WORD_FORWARD:
2449                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2450                 bv_->getLyXText()->deleteWordForward(bv_);
2451                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2452                 moveCursorUpdate(false);
2453                 owner_->view_state_changed();
2454                 break;
2455
2456                 /* -------> Delete word backward. */
2457         case LFUN_DELETE_WORD_BACKWARD:
2458         {
2459                 LyXText * lt = bv_->getLyXText();
2460
2461                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2462                 lt->deleteWordBackward(bv_);
2463                 update(lt,
2464                        BufferView::SELECT
2465                        | BufferView::FITCUR
2466                        | BufferView::CHANGE);
2467                 moveCursorUpdate(false);
2468                 owner_->view_state_changed();
2469         }
2470         break;
2471
2472                 /* -------> Kill to end of line. */
2473         case LFUN_DELETE_LINE_FORWARD:
2474         {
2475                 LyXText * lt = bv_->getLyXText();
2476
2477                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2478                 lt->deleteLineForward(bv_);
2479                 update(lt,
2480                        BufferView::SELECT
2481                        | BufferView::FITCUR
2482                        | BufferView::CHANGE);
2483                 moveCursorUpdate(false);
2484         }
2485         break;
2486
2487                 /* -------> Set mark off. */
2488         case LFUN_MARK_OFF:
2489         {
2490                 LyXText * lt = bv_->getLyXText();
2491
2492                 beforeChange(lt);
2493                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2494                 lt->selection.cursor = lt->cursor;
2495                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2496         }
2497         break;
2498
2499                 /* -------> Set mark on. */
2500         case LFUN_MARK_ON:
2501         {
2502                 LyXText * lt = bv_->getLyXText();
2503
2504                 beforeChange(lt);
2505                 lt->selection.mark(true);
2506                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2507                 lt->selection.cursor = lt->cursor;
2508                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2509         }
2510         break;
2511
2512         case LFUN_BACKSPACE:
2513         {
2514                 LyXText * lt = bv_->getLyXText();
2515
2516                 if (!lt->selection.set()) {
2517                         if (owner_->getIntl()->getTransManager().backspace()) {
2518                                 lt->backspace(bv_);
2519                                 lt->selection.cursor = lt->cursor;
2520                                 update(lt,
2521                                        BufferView::SELECT
2522                                        | BufferView::FITCUR
2523                                        | BufferView::CHANGE);
2524                                 // It is possible to make it a lot faster still
2525                                 // just comment out the line below...
2526                                 showCursor();
2527                         }
2528                 } else {
2529                         bv_->cut(false);
2530                 }
2531                 owner_->view_state_changed();
2532                 switchKeyMap();
2533         }
2534         break;
2535
2536         case LFUN_BACKSPACE_SKIP:
2537         {
2538                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2539                 LyXText * lt = bv_->getLyXText();
2540
2541                 LyXCursor cursor = lt->cursor;
2542
2543                 if (!lt->selection.set()) {
2544                         if (cursor.pos() == 0
2545                             && !(cursor.par()->params().spaceTop()
2546                                  == VSpace (VSpace::NONE))) {
2547                                 lt->setParagraph
2548                                         (bv_,
2549                                          cursor.par()->params().lineTop(),
2550                                          cursor.par()->params().lineBottom(),
2551                                          cursor.par()->params().pagebreakTop(),
2552                                          cursor.par()->params().pagebreakBottom(),
2553                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2554                                          cursor.par()->params().spacing(),
2555                                          cursor.par()->params().align(),
2556                                          cursor.par()->params().labelWidthString(), 0);
2557                                 update(lt,
2558                                        BufferView::SELECT
2559                                        | BufferView::FITCUR
2560                                        | BufferView::CHANGE);
2561                         } else {
2562                                 lt->backspace(bv_);
2563                                 lt->selection.cursor = cursor;
2564                                 update(lt,
2565                                        BufferView::SELECT
2566                                        | BufferView::FITCUR
2567                                        | BufferView::CHANGE);
2568                         }
2569                 } else
2570                         bv_->cut(false);
2571         }
2572         break;
2573
2574         case LFUN_BREAKPARAGRAPH:
2575         {
2576                 LyXText * lt = bv_->getLyXText();
2577
2578                 beforeChange(lt);
2579                 lt->breakParagraph(bv_, 0);
2580                 update(lt,
2581                        BufferView::SELECT
2582                        | BufferView::FITCUR
2583                        | BufferView::CHANGE);
2584                 lt->selection.cursor = lt->cursor;
2585                 switchKeyMap();
2586                 owner_->view_state_changed();
2587                 break;
2588         }
2589
2590         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2591         {
2592                 LyXText * lt = bv_->getLyXText();
2593
2594                 beforeChange(lt);
2595                 lt->breakParagraph(bv_, 1);
2596                 update(lt,
2597                        BufferView::SELECT
2598                        | BufferView::FITCUR
2599                        | BufferView::CHANGE);
2600                 lt->selection.cursor = lt->cursor;
2601                 switchKeyMap();
2602                 owner_->view_state_changed();
2603                 break;
2604         }
2605
2606         case LFUN_BREAKPARAGRAPH_SKIP:
2607         {
2608                 // When at the beginning of a paragraph, remove
2609                 // indentation and add a "defskip" at the top.
2610                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2611                 LyXText * lt = bv_->getLyXText();
2612
2613                 LyXCursor cursor = lt->cursor;
2614
2615                 beforeChange(lt);
2616                 if (cursor.pos() == 0) {
2617                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2618                                 lt->setParagraph
2619                                         (bv_,
2620                                          cursor.par()->params().lineTop(),
2621                                          cursor.par()->params().lineBottom(),
2622                                          cursor.par()->params().pagebreakTop(),
2623                                          cursor.par()->params().pagebreakBottom(),
2624                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2625                                          cursor.par()->params().spacing(),
2626                                          cursor.par()->params().align(),
2627                                          cursor.par()->params().labelWidthString(), 1);
2628                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2629                         }
2630                 }
2631                 else {
2632                         lt->breakParagraph(bv_, 0);
2633                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2634                 }
2635
2636                 update(lt,
2637                        BufferView::SELECT
2638                        | BufferView::FITCUR
2639                        | BufferView::CHANGE);
2640                 lt->selection.cursor = cursor;
2641                 switchKeyMap();
2642                 owner_->view_state_changed();
2643         }
2644         break;
2645
2646         case LFUN_PARAGRAPH_SPACING:
2647         {
2648                 LyXText * lt = bv_->getLyXText();
2649
2650                 Paragraph * par = lt->cursor.par();
2651                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2652                 float cur_value = 1.0;
2653                 if (cur_spacing == Spacing::Other) {
2654                         cur_value = par->params().spacing().getValue();
2655                 }
2656
2657                 istringstream istr(ev.argument.c_str());
2658
2659                 string tmp;
2660                 istr >> tmp;
2661                 Spacing::Space new_spacing = cur_spacing;
2662                 float new_value = cur_value;
2663                 if (tmp.empty()) {
2664                         lyxerr << "Missing argument to `paragraph-spacing'"
2665                                << endl;
2666                 } else if (tmp == "single") {
2667                         new_spacing = Spacing::Single;
2668                 } else if (tmp == "onehalf") {
2669                         new_spacing = Spacing::Onehalf;
2670                 } else if (tmp == "double") {
2671                         new_spacing = Spacing::Double;
2672                 } else if (tmp == "other") {
2673                         new_spacing = Spacing::Other;
2674                         float tmpval = 0.0;
2675                         istr >> tmpval;
2676                         lyxerr << "new_value = " << tmpval << endl;
2677                         if (tmpval != 0.0)
2678                                 new_value = tmpval;
2679                 } else if (tmp == "default") {
2680                         new_spacing = Spacing::Default;
2681                 } else {
2682                         lyxerr << _("Unknown spacing argument: ")
2683                                << ev.argument << endl;
2684                 }
2685                 if (cur_spacing != new_spacing || cur_value != new_value) {
2686                         par->params().spacing(Spacing(new_spacing, new_value));
2687                         lt->redoParagraph(bv_);
2688                         update(lt,
2689                                BufferView::SELECT
2690                                | BufferView::FITCUR
2691                                | BufferView::CHANGE);
2692                 }
2693         }
2694         break;
2695
2696         case LFUN_INSET_TOGGLE:
2697         {
2698                 LyXText * lt = bv_->getLyXText();
2699                 hideCursor();
2700                 beforeChange(lt);
2701                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2702                 lt->toggleInset(bv_);
2703                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2704                 switchKeyMap();
2705         }
2706                 break;
2707
2708         case LFUN_QUOTE:
2709                 smartQuote();
2710                 break;
2711
2712         case LFUN_HTMLURL:
2713         case LFUN_URL:
2714         {
2715                 InsetCommandParams p;
2716                 if (ev.action == LFUN_HTMLURL)
2717                         p.setCmdName("htmlurl");
2718                 else
2719                         p.setCmdName("url");
2720                 owner_->getDialogs()->createUrl(p.getAsString());
2721         }
2722         break;
2723
2724         case LFUN_INSERT_URL:
2725         {
2726                 InsetCommandParams p;
2727                 p.setFromString(ev.argument);
2728
2729                 InsetUrl * inset = new InsetUrl(p);
2730                 if (!insertInset(inset))
2731                         delete inset;
2732                 else
2733                         updateInset(inset, true);
2734         }
2735         break;
2736
2737         case LFUN_INSET_ERT:
2738                 insertAndEditInset(new InsetERT(buffer_->params));
2739                 break;
2740
2741         case LFUN_INSET_EXTERNAL:
2742                 insertAndEditInset(new InsetExternal);
2743                 break;
2744
2745         case LFUN_INSET_FOOTNOTE:
2746                 insertAndEditInset(new InsetFoot(buffer_->params));
2747                 break;
2748
2749         case LFUN_INSET_MARGINAL:
2750                 insertAndEditInset(new InsetMarginal(buffer_->params));
2751                 break;
2752
2753         case LFUN_INSET_MINIPAGE:
2754                 insertAndEditInset(new InsetMinipage(buffer_->params));
2755                 break;
2756
2757         case LFUN_INSERT_NOTE:
2758                 insertAndEditInset(new InsetNote(buffer_->params));
2759                 break;
2760
2761         case LFUN_INSET_FLOAT:
2762                 // check if the float type exist
2763                 if (floatList.typeExist(ev.argument)) {
2764                         insertAndEditInset(new InsetFloat(buffer_->params,
2765                                                           ev.argument));
2766                 } else {
2767                         lyxerr << "Non-existent float type: "
2768                                << ev.argument << endl;
2769                 }
2770                 break;
2771
2772         case LFUN_INSET_WIDE_FLOAT:
2773                 // check if the float type exist
2774                 if (floatList.typeExist(ev.argument)) {
2775                         InsetFloat * new_inset =
2776                                 new InsetFloat(buffer_->params, ev.argument);
2777                         new_inset->wide(true);
2778                         insertAndEditInset(new_inset);
2779                 } else {
2780                         lyxerr << "Non-existent float type: "
2781                                << ev.argument << endl;
2782                 }
2783                 break;
2784
2785 #if 0
2786         case LFUN_INSET_LIST:
2787                 insertAndEditInset(new InsetList);
2788                 break;
2789
2790         case LFUN_INSET_THEOREM:
2791                 insertAndEditInset(new InsetTheorem);
2792                 break;
2793 #endif
2794
2795         case LFUN_INSET_CAPTION:
2796         {
2797                 // Do we have a locking inset...
2798                 if (bv_->theLockingInset()) {
2799                         lyxerr << "Locking inset code: "
2800                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2801                         InsetCaption * new_inset =
2802                                 new InsetCaption(buffer_->params);
2803                         new_inset->setOwner(bv_->theLockingInset());
2804                         new_inset->setAutoBreakRows(true);
2805                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2806                         new_inset->setFrameColor(0, LColor::captionframe);
2807                         if (insertInset(new_inset))
2808                                 new_inset->edit(bv_);
2809                         else
2810                                 delete new_inset;
2811                 }
2812         }
2813         break;
2814
2815         case LFUN_TABULAR_INSERT:
2816         {
2817                 if (ev.argument.empty()) {
2818                         owner_->getDialogs()->showTabularCreate();
2819                         break;
2820                 }
2821  
2822                 int r = 2;
2823                 int c = 2;
2824                 ::sscanf(ev.argument.c_str(),"%d%d", &r, &c);
2825                 InsetTabular * new_inset =
2826                         new InsetTabular(*buffer_, r, c);
2827                 bool const rtl =
2828                         bv_->getLyXText()->real_current_font.isRightToLeft();
2829                 if (!open_new_inset(new_inset, rtl))
2830                         delete new_inset;
2831         }
2832         break;
2833
2834         // --- lyxserver commands ----------------------------
2835
2836         case LFUN_CHARATCURSOR:
2837         {
2838                 pos_type pos = bv_->getLyXText()->cursor.pos();
2839                 if (pos < bv_->getLyXText()->cursor.par()->size())
2840                         owner_->getLyXFunc()->setMessage(
2841                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2842                 else
2843                         owner_->getLyXFunc()->setMessage("EOF");
2844         }
2845         break;
2846
2847         case LFUN_GETXY:
2848                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2849                                                  + ' '
2850                                                  + tostr(bv_->getLyXText()->cursor.y()));
2851                 break;
2852
2853         case LFUN_SETXY:
2854         {
2855                 int x = 0;
2856                 int y = 0;
2857                 if (::sscanf(ev.argument.c_str(), " %d %d", &x, &y) != 2) {
2858                         lyxerr << "SETXY: Could not parse coordinates in '"
2859                                << ev.argument << std::endl;
2860                 }
2861                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2862         }
2863         break;
2864
2865         case LFUN_GETLAYOUT:
2866                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout()));
2867                 break;
2868
2869         case LFUN_GETFONT:
2870         {
2871                 LyXFont & font = bv_->getLyXText()->current_font;
2872                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2873                         owner_->getLyXFunc()->setMessage("E");
2874                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2875                         owner_->getLyXFunc()->setMessage("N");
2876                 else
2877                         owner_->getLyXFunc()->setMessage("0");
2878
2879         }
2880         break;
2881
2882         // --- accented characters ---------------------------
2883
2884         case LFUN_UMLAUT:
2885         case LFUN_CIRCUMFLEX:
2886         case LFUN_GRAVE:
2887         case LFUN_ACUTE:
2888         case LFUN_TILDE:
2889         case LFUN_CEDILLA:
2890         case LFUN_MACRON:
2891         case LFUN_DOT:
2892         case LFUN_UNDERDOT:
2893         case LFUN_UNDERBAR:
2894         case LFUN_CARON:
2895         case LFUN_SPECIAL_CARON:
2896         case LFUN_BREVE:
2897         case LFUN_TIE:
2898         case LFUN_HUNG_UMLAUT:
2899         case LFUN_CIRCLE:
2900         case LFUN_OGONEK:
2901                 if (ev.argument.empty()) {
2902                         // As always...
2903                         owner_->getLyXFunc()->handleKeyFunc(ev.action);
2904                 } else {
2905                         owner_->getLyXFunc()->handleKeyFunc(ev.action);
2906                         owner_->getIntl()->getTransManager()
2907                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
2908                         update(bv_->getLyXText(),
2909                                BufferView::SELECT
2910                                | BufferView::FITCUR
2911                                | BufferView::CHANGE);
2912                 }
2913                 break;
2914
2915         case LFUN_MATH:
2916                 mathDispatch(bv_, ev.argument);
2917                 break;
2918
2919         case LFUN_MATH_MACRO:
2920                 mathDispatchMathMacro(bv_, ev.argument);
2921                 break;
2922
2923         case LFUN_MATH_DELIM:
2924                 mathDispatchMathDelim(bv_, ev.argument);
2925                 break;
2926
2927         case LFUN_INSERT_MATRIX:
2928                 mathDispatchInsertMatrix(bv_, ev.argument);
2929                 break;
2930
2931         case LFUN_INSERT_MATH:
2932                 mathDispatchInsertMath(bv_, ev.argument);
2933                 break;
2934
2935         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2936                 mathDispatchMathImportSelection(bv_, ev.argument);
2937                 break;
2938
2939         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2940                 mathDispatchMathDisplay(bv_, ev.argument);
2941                 break;
2942
2943         case LFUN_MATH_MODE:             // Open or create an inlined math inset
2944                 mathDispatchMathMode(bv_, ev.argument);
2945                 break;
2946
2947         case LFUN_GREEK:                 // Insert a single greek letter
2948                 mathDispatchGreek(bv_, ev.argument);
2949                 break;
2950
2951         case LFUN_CITATION_INSERT:
2952         {
2953                 InsetCommandParams p;
2954                 p.setFromString(ev.argument);
2955
2956                 InsetCitation * inset = new InsetCitation(p);
2957                 if (!insertInset(inset))
2958                         delete inset;
2959                 else
2960                         updateInset(inset, true);
2961         }
2962         break;
2963
2964         case LFUN_INSERT_BIBTEX:
2965         {
2966                 // ale970405+lasgoutt970425
2967                 // The argument can be up to two tokens separated
2968                 // by a space. The first one is the bibstyle.
2969                 string const db       = token(ev.argument, ' ', 0);
2970                 string const bibstyle = token(ev.argument, ' ', 1);
2971
2972                 InsetCommandParams p("BibTeX", db, bibstyle);
2973                 InsetBibtex * inset = new InsetBibtex(p);
2974
2975                 if (insertInset(inset)) {
2976                         if (ev.argument.empty())
2977                                 inset->edit(bv_);
2978                 } else
2979                         delete inset;
2980         }
2981         break;
2982
2983         // BibTeX data bases
2984         case LFUN_BIBDB_ADD:
2985         {
2986                 InsetBibtex * inset =
2987                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2988                 if (inset) {
2989                         inset->addDatabase(ev.argument);
2990                 }
2991         }
2992         break;
2993
2994         case LFUN_BIBDB_DEL:
2995         {
2996                 InsetBibtex * inset =
2997                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2998                 if (inset) {
2999                         inset->delDatabase(ev.argument);
3000                 }
3001         }
3002         break;
3003
3004         case LFUN_BIBTEX_STYLE:
3005         {
3006                 InsetBibtex * inset =
3007                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3008                 if (inset) {
3009                         inset->setOptions(ev.argument);
3010                 }
3011         }
3012         break;
3013
3014         case LFUN_INDEX_INSERT:
3015         {
3016                 string entry = ev.argument;
3017                 if (entry.empty()) {
3018                         entry = bv_->getLyXText()->getStringToIndex(bv_);
3019                 }
3020
3021                 if (entry.empty()) {
3022                         owner_->getDialogs()->createIndex();
3023                         break;
3024                 }
3025
3026                 InsetIndex * inset = new InsetIndex(InsetCommandParams("index", entry));
3027
3028                 if (!insertInset(inset)) {
3029                         delete inset;
3030                 } else {
3031                         updateInset(inset, true);
3032                 }
3033         }
3034         break;
3035
3036         case LFUN_INDEX_PRINT:
3037         {
3038                 InsetCommandParams p("printindex");
3039                 Inset * inset = new InsetPrintIndex(p);
3040                 if (!insertInset(inset, tclass.defaultLayoutName()))
3041                         delete inset;
3042         }
3043         break;
3044
3045         case LFUN_PARENTINSERT:
3046         {
3047                 InsetCommandParams p("lyxparent", ev.argument);
3048                 Inset * inset = new InsetParent(p, *buffer_);
3049                 if (!insertInset(inset, tclass.defaultLayoutName()))
3050                         delete inset;
3051         }
3052
3053         break;
3054
3055         case LFUN_CHILD_INSERT:
3056         {
3057                 InsetInclude::Params p;
3058                 p.cparams.setFromString(ev.argument);
3059                 p.masterFilename_ = buffer_->fileName();
3060
3061                 InsetInclude * inset = new InsetInclude(p);
3062                 if (!insertInset(inset))
3063                         delete inset;
3064                 else {
3065                         updateInset(inset, true);
3066                         bv_->owner()->getDialogs()->showInclude(inset);
3067                 }
3068         }
3069         break;
3070
3071         case LFUN_FLOAT_LIST:
3072                 if (floatList.typeExist(ev.argument)) {
3073                         Inset * inset = new InsetFloatList(ev.argument);
3074                         if (!insertInset(inset, tclass.defaultLayoutName()))
3075                                 delete inset;
3076                 } else {
3077                         lyxerr << "Non-existent float type: "
3078                                << ev.argument << endl;
3079                 }
3080                 break;
3081
3082         case LFUN_THESAURUS_ENTRY:
3083         {
3084                 string arg = ev.argument;
3085
3086                 if (arg.empty()) {
3087                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3088                                                                    false);
3089
3090                         // FIXME
3091                         if (arg.size() > 100 || arg.empty()) {
3092                                 // Get word or selection
3093                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3094                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3095                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3096                         }
3097                 }
3098
3099                 bv_->owner()->getDialogs()->showThesaurus(arg);
3100         }
3101                 break;
3102
3103         case LFUN_SELFINSERT:
3104         {
3105                 if (ev.argument.empty()) break;
3106
3107                 /* Automatically delete the currently selected
3108                  * text and replace it with what is being
3109                  * typed in now. Depends on lyxrc settings
3110                  * "auto_region_delete", which defaults to
3111                  * true (on). */
3112
3113                 LyXText * lt = bv_->getLyXText();
3114
3115                 if (lyxrc.auto_region_delete) {
3116                         if (lt->selection.set()) {
3117                                 lt->cutSelection(bv_, false, false);
3118                                 bv_->update(lt,
3119                                             BufferView::SELECT
3120                                             | BufferView::FITCUR
3121                                             | BufferView::CHANGE);
3122                         }
3123                         workarea().haveSelection(false);
3124                 }
3125
3126                 beforeChange(lt);
3127                 LyXFont const old_font(lt->real_current_font);
3128
3129                 string::const_iterator cit = ev.argument.begin();
3130                 string::const_iterator end = ev.argument.end();
3131                 for (; cit != end; ++cit) {
3132                         owner_->getIntl()->getTransManager().
3133                                 TranslateAndInsert(*cit, lt);
3134                 }
3135
3136                 bv_->update(lt,
3137                             BufferView::SELECT
3138                             | BufferView::FITCUR
3139                             | BufferView::CHANGE);
3140
3141                 lt->selection.cursor = lt->cursor;
3142                 moveCursorUpdate(false);
3143
3144                 // real_current_font.number can change so we need to
3145                 // update the minibuffer
3146                 if (old_font != lt->real_current_font)
3147                         owner_->view_state_changed();
3148                 //return string();
3149         }
3150         break;
3151
3152         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3153         {
3154                 time_t now_time_t = time(NULL);
3155                 struct tm * now_tm = localtime(&now_time_t);
3156                 setlocale(LC_TIME, "");
3157                 string arg;
3158                 if (!ev.argument.empty())
3159                         arg = ev.argument;
3160                 else
3161                         arg = lyxrc.date_insert_format;
3162                 char datetmp[32];
3163                 int const datetmp_len =
3164                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3165
3166                 LyXText * lt = bv_->getLyXText();
3167
3168                 for (int i = 0; i < datetmp_len; i++) {
3169                         lt->insertChar(bv_, datetmp[i]);
3170                         update(lt,
3171                                BufferView::SELECT
3172                                | BufferView::FITCUR
3173                                | BufferView::CHANGE);
3174                 }
3175
3176                 lt->selection.cursor = lt->cursor;
3177                 moveCursorUpdate(false);
3178         }
3179         break;
3180
3181         case LFUN_UNKNOWN_ACTION:
3182                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3183                 break;
3184
3185         default:
3186                 return false;
3187         } // end of switch
3188
3189         return true;
3190 }
3191
3192
3193 void BufferView::Pimpl::newline()
3194 {
3195         if (available()) {
3196                 LyXText * lt = bv_->getLyXText();
3197                 hideCursor();
3198                 update(lt,
3199                        BufferView::SELECT
3200                        | BufferView::FITCUR);
3201                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3202                 update(lt,
3203                        BufferView::SELECT
3204                        | BufferView::FITCUR
3205                        | BufferView::CHANGE);
3206         }
3207 }
3208
3209
3210 void BufferView::Pimpl::hfill()
3211 {
3212         if (available()) {
3213                 LyXText * lt = bv_->getLyXText();
3214                 hideCursor();
3215                 update(lt,
3216                        BufferView::SELECT
3217                        | BufferView::FITCUR);
3218                 lt->insertChar(bv_, Paragraph::META_HFILL);
3219                 update(lt,
3220                        BufferView::SELECT
3221                        | BufferView::FITCUR
3222                        | BufferView::CHANGE);
3223         }
3224 }
3225
3226
3227 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3228 {
3229         if (available()) {
3230                 LyXText * lt = bv_->getLyXText();
3231
3232                 hideCursor();
3233                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3234                 InsetSpecialChar * new_inset =
3235                         new InsetSpecialChar(kind);
3236                 if (!insertInset(new_inset))
3237                         delete new_inset;
3238                 else
3239                         updateInset(new_inset, true);
3240         }
3241 }
3242
3243
3244 void BufferView::Pimpl::smartQuote()
3245 {
3246         LyXText const * lt = bv_->getLyXText();
3247         Paragraph const * par = lt->cursor.par();
3248         pos_type pos = lt->cursor.pos();
3249         char c;
3250
3251         if (!pos
3252             || (par->isInset(pos - 1)
3253                 && par->getInset(pos - 1)->isSpace()))
3254                 c = ' ';
3255         else
3256                 c = par->getChar(pos - 1);
3257
3258
3259         hideCursor();
3260
3261         LyXLayout_ptr const & style = par->layout();
3262
3263         if (style->pass_thru ||
3264                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3265                 bv_->owner()->getLyXFunc()
3266                         ->dispatch(FuncRequest(LFUN_SELFINSERT, "\""));
3267 }
3268
3269
3270 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3271 {
3272 #if 0
3273         if (insertInset(inset))
3274                 inset->edit(bv_);
3275         else
3276                 delete inset;
3277 #else
3278         bool gotsel = false;
3279
3280         if (bv_->getLyXText()->selection.set()) {
3281                 bv_->getLyXText()->cutSelection(bv_, true, false);
3282                 gotsel = true;
3283         }
3284
3285         if (insertInset(inset)) {
3286                 inset->edit(bv_);
3287                 if (gotsel)
3288                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION);
3289         }
3290         else
3291                 delete inset;
3292 #endif
3293 }
3294
3295
3296 // Open and lock an updatable inset
3297 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3298 {
3299         LyXText * lt = bv_->getLyXText();
3300
3301         beforeChange(lt);
3302         finishUndo();
3303         if (!insertInset(new_inset)) {
3304                 delete new_inset;
3305                 return false;
3306         }
3307         new_inset->edit(bv_, !behind);
3308         return true;
3309 }
3310
3311
3312 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3313 {
3314         // if we are in a locking inset we should try to insert the
3315         // inset there otherwise this is a illegal function now
3316         if (bv_->theLockingInset()) {
3317                 if (bv_->theLockingInset()->insetAllowed(inset))
3318                     return bv_->theLockingInset()->insertInset(bv_, inset);
3319                 return false;
3320         }
3321
3322         // not quite sure if we want this...
3323         setCursorParUndo(bv_);
3324         freezeUndo();
3325
3326         beforeChange(bv_->text);
3327         if (!lout.empty()) {
3328                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3329                 bv_->text->breakParagraph(bv_);
3330                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3331
3332                 if (bv_->text->cursor.par()->size()) {
3333                         bv_->text->cursorLeft(bv_);
3334
3335                         bv_->text->breakParagraph(bv_);
3336                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3337                 }
3338
3339                 string lres = lout;
3340                 LyXTextClass const & tclass =
3341                         buffer_->params.getLyXTextClass();
3342                 bool hasLayout = tclass.hasLayout(lres);
3343                 string lay = tclass.defaultLayoutName();
3344
3345                 if (hasLayout != false) {
3346                         // layout found
3347                         lay = lres;
3348                 } else {
3349                         // layout not fount using default
3350                         lay = tclass.defaultLayoutName();
3351                 }
3352
3353                 bv_->text->setLayout(bv_, lay);
3354
3355                 bv_->text->setParagraph(bv_, 0, 0,
3356                                    0, 0,
3357                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3358                                    Spacing(),
3359                                    LYX_ALIGN_LAYOUT,
3360                                    string(),
3361                                    0);
3362                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3363         }
3364
3365         bv_->text->insertInset(bv_, inset);
3366         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3367
3368         unFreezeUndo();
3369         return true;
3370 }
3371
3372
3373 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3374 {
3375         if (!inset || !available())
3376                 return;
3377
3378         // first check for locking insets
3379         if (bv_->theLockingInset()) {
3380                 if (bv_->theLockingInset() == inset) {
3381                         if (bv_->text->updateInset(bv_, inset)) {
3382                                 update();
3383                                 if (mark_dirty) {
3384                                         buffer_->markDirty();
3385                                 }
3386                                 updateScrollbar();
3387                                 return;
3388                         }
3389                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3390                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3391                                 update();
3392                                 if (mark_dirty) {
3393                                         buffer_->markDirty();
3394                                 }
3395                                 updateScrollbar();
3396                                 return;
3397                         }
3398                 }
3399         }
3400
3401         // then check if the inset is a top_level inset (has no owner)
3402         // if yes do the update as always otherwise we have to update the
3403         // toplevel inset where this inset is inside
3404         Inset * tl_inset = inset;
3405         while(tl_inset->owner())
3406                 tl_inset = tl_inset->owner();
3407         hideCursor();
3408         if (tl_inset == inset) {
3409                 update(bv_->text, BufferView::UPDATE);
3410                 if (bv_->text->updateInset(bv_, inset)) {
3411                         if (mark_dirty) {
3412                                 update(bv_->text,
3413                                        BufferView::SELECT
3414                                        | BufferView::FITCUR
3415                                        | BufferView::CHANGE);
3416                         } else {
3417                                 update(bv_->text, SELECT);
3418                         }
3419                         return;
3420                 }
3421         } else if (static_cast<UpdatableInset *>(tl_inset)
3422                            ->updateInsetInInset(bv_, inset))
3423         {
3424                         if (bv_->text->updateInset(bv_,  tl_inset)) {
3425                                 update();
3426                                 updateScrollbar();
3427                         }
3428         }
3429 }
3430
3431
3432 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3433                                   bool same_content)
3434 {
3435         if (!available()) return;
3436
3437         hideCursor();
3438         beforeChange(bv_->text);
3439         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3440
3441         LyXCursor const & cursor = bv_->text->cursor;
3442
3443         string contents;
3444         if (same_content &&
3445             cursor.par()->isInset(cursor.pos())) {
3446                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3447                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3448                     != codes.end())
3449                         contents =
3450                                 static_cast<InsetCommand const *>(inset)->getContents();
3451         }
3452
3453
3454         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3455                 if (bv_->text->cursor.pos()
3456                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3457                         LyXCursor tmp = bv_->text->cursor;
3458                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3459                         bv_->text->cursor.pos(0);
3460                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3461                                 bv_->text->cursor = tmp;
3462                                 bv_->owner()->message(_("No more insets"));
3463                         }
3464                 } else {
3465                         bv_->owner()->message(_("No more insets"));
3466                 }
3467         }
3468         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3469         bv_->text->selection.cursor = bv_->text->cursor;
3470 }
3471
3472
3473 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3474 {
3475         gotoInset(vector<Inset::Code>(1, code), same_content);
3476 }