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