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