]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Forgot to restore this before committing 18494. This fixes bug 3725.
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         // If we are closing current buffer, switch to the first in
187         // buffer list.
188         if (!b) {
189                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
190                                     << " No Buffer!" << endl;
191                 // We are closing the buffer, use the first buffer as current
192                 buffer_ = theBufferList().first();
193         } else {
194                 // Set current buffer
195                 buffer_ = b;
196         }
197
198         // Reset old cursor
199         cursor_ = Cursor(*this);
200         anchor_ref_ = 0;
201         offset_ref_ = 0;
202
203         if (buffer_) {
204                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
205                                     << "Buffer addr: " << buffer_ << endl;
206                 cursor_.push(buffer_->inset());
207                 cursor_.resetAnchor();
208                 buffer_->text().setCurrentFont(cursor_);
209                 if (buffer_->getCursor().size() > 0 &&
210                     buffer_->getAnchor().size() > 0)
211                 {
212                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
213                         cursor_.resetAnchor();
214                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
215                         cursor_.setSelection();
216                         // do not set selection to the new buffer because we
217                         // only paste recent selection.
218                 }
219         }
220
221         if (buffer_)
222                 updateMetrics(false);    
223
224         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
225                 graphics::Previews::get().generateBufferPreviews(*buffer_);
226 }
227
228
229 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
230 {
231         // File already open?
232         if (theBufferList().exists(filename.absFilename())) {
233                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
234                 docstring text = bformat(_("The document %1$s is already "
235                                                      "loaded.\n\nDo you want to revert "
236                                                      "to the saved version?"), file);
237                 int const ret = Alert::prompt(_("Revert to saved document?"),
238                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
239
240                 if (ret != 0) {
241                         setBuffer(theBufferList().getBuffer(filename.absFilename()));
242                         return true;
243                 }
244                 // FIXME: should be LFUN_REVERT
245                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
246                         return false;
247                 // Fall through to new load. (Asger)
248                 buffer_ = 0;
249         }
250
251         Buffer * b = 0;
252
253         if (isFileReadable(filename)) {
254                 b = theBufferList().newBuffer(filename.absFilename());
255                 if (!lyx::loadLyXFile(b, filename)) {
256                         theBufferList().release(b);
257                         return false;
258                 }
259         } else {
260                 docstring text = bformat(_("The document %1$s does not yet "
261                                                      "exist.\n\nDo you want to create "
262                                                      "a new document?"), from_utf8(filename.absFilename()));
263                 int const ret = Alert::prompt(_("Create new document?"),
264                          text, 0, 1, _("&Create"), _("Cancel"));
265
266                 if (ret == 0) {
267                         b = newFile(filename.absFilename(), string(), true);
268                         if (!b)
269                                 return false;
270                 } else
271                         return false;
272         }
273
274         setBuffer(b);
275         // Send the "errors" signal in case of parsing errors
276         b->errors("Parse");
277
278         // Update the labels and section numbering.
279         updateLabels(*buffer_);
280         // scroll to the position when the file was last closed
281         if (lyxrc.use_lastfilepos) {
282                 pit_type pit;
283                 pos_type pos;
284                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
285                 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
286                 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
287                         if (fitCursor())
288                                 updateMetrics(false);
289                         buffer_->text().setCurrentFont(cursor_);
290                 }
291         }
292
293         if (tolastfiles)
294                 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
295
296         return true;
297 }
298
299
300 void BufferView::resize()
301 {
302         if (!buffer_)
303                 return;
304
305         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
306
307         updateMetrics(false);
308         switchKeyMap();
309 }
310
311
312 bool BufferView::fitCursor()
313 {
314         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
315                 frontend::FontMetrics const & fm =
316                         theFontMetrics(cursor_.getFont());
317                 int const asc = fm.maxAscent();
318                 int const des = fm.maxDescent();
319                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
320                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
321                         return false;
322         }
323         center();
324         return true;
325 }
326
327
328 bool BufferView::multiParSel()
329 {
330         if (!cursor_.selection())
331                 return false;
332         bool ret = multiparsel_cache_;
333         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
334         // Either this, or previous selection spans paragraphs
335         return ret || multiparsel_cache_;
336 }
337
338
339 bool BufferView::update(Update::flags flags)
340 {
341         // last_inset_ points to the last visited inset. This pointer may become
342         // invalid because of keyboard editing. Since all such operations
343         // causes screen update(), I reset last_inset_ to avoid such a problem.
344         last_inset_ = 0;
345         // This is close to a hot-path.
346         LYXERR(Debug::DEBUG)
347                 << BOOST_CURRENT_FUNCTION
348                 << "[fitcursor = " << (flags & Update::FitCursor)
349                 << ", forceupdate = " << (flags & Update::Force)
350                 << ", singlepar = " << (flags & Update::SinglePar)
351                 << "]  buffer: " << buffer_ << endl;
352
353         // Check needed to survive LyX startup
354         if (!buffer_)
355                 return false;
356
357         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
358
359         // Update macro store
360         if (!(cursor().inMathed() && cursor().inMacroMode()))
361                 buffer_->buildMacros();
362
363         // Now do the first drawing step if needed. This consists on updating
364         // the CoordCache in updateMetrics().
365         // The second drawing step is done in WorkArea::redraw() if needed.
366
367         // Case when no explicit update is requested.
368         if (!flags) {
369                 // no need to redraw anything.
370                 metrics_info_.update_strategy = NoScreenUpdate;
371                 return false;
372         }
373
374         if (flags == Update::Decoration) {
375                 metrics_info_.update_strategy = DecorationUpdate;
376                 return true;
377         }
378
379         if (flags == Update::FitCursor 
380                 || flags == (Update::Decoration | Update::FitCursor)) {
381                 bool const fit_cursor = fitCursor();
382                 // tell the frontend to update the screen if needed.
383                 if (fit_cursor) {
384                         updateMetrics(false);
385                         return true;
386                 }
387                 if (flags & Update::Decoration) {
388                         metrics_info_.update_strategy = DecorationUpdate;
389                         return true;
390                 }
391                 // no screen update is needed.
392                 metrics_info_.update_strategy = NoScreenUpdate;
393                 return false;
394         }
395
396         bool full_metrics = flags & Update::Force;
397         if (flags & Update::MultiParSel)
398                 full_metrics |= multiParSel();
399
400         bool const single_par = !full_metrics;
401         updateMetrics(single_par);
402
403         if (flags & Update::FitCursor && fitCursor())
404                 updateMetrics(false);
405
406         // tell the frontend to update the screen.
407         return true;
408 }
409
410
411 void BufferView::updateScrollbar()
412 {
413         if (!buffer_) {
414                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
415                                      << " no text in updateScrollbar" << endl;
416                 scrollbarParameters_.reset();
417                 return;
418         }
419
420         Text & t = buffer_->text();
421         TextMetrics & tm = text_metrics_[&t];
422
423         int const parsize = int(t.paragraphs().size() - 1);
424         if (anchor_ref_ >  parsize)  {
425                 anchor_ref_ = parsize;
426                 offset_ref_ = 0;
427         }
428
429         LYXERR(Debug::GUI)
430                 << BOOST_CURRENT_FUNCTION
431                 << " Updating scrollbar: height: " << t.paragraphs().size()
432                 << " curr par: " << cursor_.bottom().pit()
433                 << " default height " << defaultRowHeight() << endl;
434
435         // It would be better to fix the scrollbar to understand
436         // values in [0..1] and divide everything by wh
437
438         // estimated average paragraph height:
439         if (wh_ == 0)
440                 wh_ = height_ / 4;
441
442         int h = tm.parMetrics(anchor_ref_).height();
443
444         // Normalize anchor/offset (MV):
445         while (offset_ref_ > h && anchor_ref_ < parsize) {
446                 anchor_ref_++;
447                 offset_ref_ -= h;
448                 h = tm.parMetrics(anchor_ref_).height();
449         }
450         // Look at paragraph heights on-screen
451         int sumh = 0;
452         int nh = 0;
453         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
454                 if (sumh > height_)
455                         break;
456                 int const h2 = tm.parMetrics(pit).height();
457                 sumh += h2;
458                 nh++;
459         }
460
461         BOOST_ASSERT(nh);
462         int const hav = sumh / nh;
463         // More realistic average paragraph height
464         if (hav > wh_)
465                 wh_ = hav;
466
467         BOOST_ASSERT(h);
468         scrollbarParameters_.height = (parsize + 1) * wh_;
469         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
470         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
471 }
472
473
474 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 {
476         return scrollbarParameters_;
477 }
478
479
480 void BufferView::scrollDocView(int value)
481 {
482         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
483                            << "[ value = " << value << "]" << endl;
484
485         if (!buffer_)
486                 return;
487
488         Text & t = buffer_->text();
489         TextMetrics & tm = text_metrics_[&t];
490
491         float const bar = value / float(wh_ * t.paragraphs().size());
492
493         anchor_ref_ = int(bar * t.paragraphs().size());
494         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
495                 anchor_ref_ = int(t.paragraphs().size()) - 1;
496
497         tm.redoParagraph(anchor_ref_);
498         int const h = tm.parMetrics(anchor_ref_).height();
499         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
500         updateMetrics(false);
501 }
502
503
504 void BufferView::setCursorFromScrollbar()
505 {
506         if (!buffer_)
507                 return;
508
509         Text & t = buffer_->text();
510
511         int const height = 2 * defaultRowHeight();
512         int const first = height;
513         int const last = height_ - height;
514         Cursor & cur = cursor_;
515
516         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
517
518         switch (st) {
519         case bv_funcs::CUR_ABOVE:
520                 // We reset the cursor because bv_funcs::status() does not
521                 // work when the cursor is within mathed.
522                 cur.reset(buffer_->inset());
523                 t.setCursorFromCoordinates(cur, 0, first);
524                 cur.clearSelection();
525                 break;
526         case bv_funcs::CUR_BELOW:
527                 // We reset the cursor because bv_funcs::status() does not
528                 // work when the cursor is within mathed.
529                 cur.reset(buffer_->inset());
530                 t.setCursorFromCoordinates(cur, 0, last);
531                 cur.clearSelection();
532                 break;
533         case bv_funcs::CUR_INSIDE:
534                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
535                 int const newy = min(last, max(y, first));
536                 if (y != newy) {
537                         cur.reset(buffer_->inset());
538                         t.setCursorFromCoordinates(cur, 0, newy);
539                 }
540         }
541 }
542
543
544 Change const BufferView::getCurrentChange() const
545 {
546         if (!cursor_.selection())
547                 return Change(Change::UNCHANGED);
548
549         DocIterator dit = cursor_.selectionBegin();
550         return dit.paragraph().lookupChange(dit.pos());
551 }
552
553
554 void BufferView::saveBookmark(unsigned int idx)
555 {
556         // tenatively save bookmark, id and pos will be used to
557         // acturately locate a bookmark in a 'live' lyx session.
558         // pit and pos will be updated with bottom level pit/pos 
559         // when lyx exits.
560         LyX::ref().session().bookmarks().save(
561                 FileName(buffer_->fileName()),
562                 cursor_.bottom().pit(),
563                 cursor_.bottom().pos(),
564                 cursor_.paragraph().id(),
565                 cursor_.pos(),
566                 idx
567         );
568         if (idx)
569                 // emit message signal.
570                 message(_("Save bookmark"));
571 }
572
573
574 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
575         int top_id, pos_type top_pos)
576 {
577         cursor_.clearSelection();
578
579         // if a valid par_id is given, try it first
580         // This is the case for a 'live' bookmark when unique paragraph ID
581         // is used to track bookmarks.
582         if (top_id > 0) {
583                 ParIterator par = buffer_->getParFromID(top_id);
584                 if (par != buffer_->par_iterator_end()) {
585                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
586                         // Some slices of the iterator may not be
587                         // reachable (e.g. closed collapsable inset)
588                         // so the dociterator may need to be
589                         // shortened. Otherwise, setCursor may crash
590                         // lyx when the cursor can not be set to these
591                         // insets.
592                         size_t const n = dit.depth();
593                         for (size_t i = 0; i < n; ++i)
594                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
595                                         dit.resize(i);
596                                         break;
597                                 }
598                         setCursor(dit);
599                         // Note: return bottom (document) level pit.
600                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
601                 }
602         }
603         // if top_id == 0, or searching through top_id failed
604         // This is the case for a 'restored' bookmark when only bottom 
605         // (document level) pit was saved. Because of this, bookmark
606         // restoration is inaccurate. If a bookmark was within an inset,
607         // it will be restored to the left of the outmost inset that contains
608         // the bookmark.
609         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
610                 DocIterator it = doc_iterator_begin(buffer_->inset());
611                 it.pit() = bottom_pit;
612                 it.pos() = min(bottom_pos, it.paragraph().size());
613                 setCursor(it);
614                 return boost::make_tuple(it.pit(), it.pos(), 
615                                          it.paragraph().id());
616         }
617         // both methods fail
618         return boost::make_tuple(pit_type(0), pos_type(0), 0);
619 }
620
621
622 void BufferView::switchKeyMap()
623 {
624         if (!lyxrc.rtl_support)
625                 return;
626
627         if (cursor_.innerText()->real_current_font.isRightToLeft()) {
628                 if (intl_->keymap == Intl::PRIMARY)
629                         intl_->keyMapSec();
630         } else {
631                 if (intl_->keymap == Intl::SECONDARY)
632                         intl_->keyMapPrim();
633         }
634 }
635
636
637 int BufferView::workWidth() const
638 {
639         return width_;
640 }
641
642
643 void BufferView::center()
644 {
645         CursorSlice & bot = cursor_.bottom();
646         TextMetrics & tm = text_metrics_[bot.text()];
647         pit_type const pit = bot.pit();
648         tm.redoParagraph(pit);
649         ParagraphMetrics const & pm = tm.parMetrics(pit);
650         anchor_ref_ = pit;
651         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
652                 + pm.ascent() - height_ / 2;
653 }
654
655
656 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
657 {
658         FuncStatus flag;
659
660         switch (cmd.action) {
661
662         case LFUN_UNDO:
663                 flag.enabled(!buffer_->undostack().empty());
664                 break;
665         case LFUN_REDO:
666                 flag.enabled(!buffer_->redostack().empty());
667                 break;
668         case LFUN_FILE_INSERT:
669         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
670         case LFUN_FILE_INSERT_PLAINTEXT:
671         case LFUN_BOOKMARK_SAVE:
672                 // FIXME: Actually, these LFUNS should be moved to Text
673                 flag.enabled(cursor_.inTexted());
674                 break;
675         case LFUN_FONT_STATE:
676         case LFUN_LABEL_INSERT:
677         case LFUN_PARAGRAPH_GOTO:
678         // FIXME handle non-trivially
679         case LFUN_OUTLINE_UP:
680         case LFUN_OUTLINE_DOWN:
681         case LFUN_OUTLINE_IN:
682         case LFUN_OUTLINE_OUT:
683         case LFUN_NOTE_NEXT:
684         case LFUN_REFERENCE_NEXT:
685         case LFUN_WORD_FIND:
686         case LFUN_WORD_REPLACE:
687         case LFUN_MARK_OFF:
688         case LFUN_MARK_ON:
689         case LFUN_MARK_TOGGLE:
690         case LFUN_SCREEN_RECENTER:
691         case LFUN_BIBTEX_DATABASE_ADD:
692         case LFUN_BIBTEX_DATABASE_DEL:
693         case LFUN_WORDS_COUNT:
694         case LFUN_NEXT_INSET_TOGGLE:
695                 flag.enabled(true);
696                 break;
697
698         case LFUN_LABEL_GOTO: {
699                 flag.enabled(!cmd.argument().empty()
700                     || getInsetByCode<InsetRef>(cursor_, Inset::REF_CODE));
701                 break;
702         }
703
704         case LFUN_CHANGES_TRACK:
705                 flag.enabled(true);
706                 flag.setOnOff(buffer_->params().trackChanges);
707                 break;
708
709         case LFUN_CHANGES_OUTPUT:
710                 flag.enabled(buffer_);
711                 flag.setOnOff(buffer_->params().outputChanges);
712                 break;
713
714         case LFUN_CHANGES_MERGE:
715         case LFUN_CHANGE_NEXT:
716         case LFUN_ALL_CHANGES_ACCEPT:
717         case LFUN_ALL_CHANGES_REJECT:
718                 // TODO: context-sensitive enabling of LFUNs
719                 // In principle, these command should only be enabled if there
720                 // is a change in the document. However, without proper
721                 // optimizations, this will inevitably result in poor performance.
722                 flag.enabled(buffer_);
723                 break;
724
725         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
726                 flag.setOnOff(buffer_->params().compressed);
727                 break;
728         }
729
730         default:
731                 flag.enabled(false);
732         }
733
734         return flag;
735 }
736
737
738 Update::flags BufferView::dispatch(FuncRequest const & cmd)
739 {
740         //lyxerr << BOOST_CURRENT_FUNCTION
741         //       << [ cmd = " << cmd << "]" << endl;
742
743         // Make sure that the cached BufferView is correct.
744         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
745                 << " action[" << cmd.action << ']'
746                 << " arg[" << to_utf8(cmd.argument()) << ']'
747                 << " x[" << cmd.x << ']'
748                 << " y[" << cmd.y << ']'
749                 << " button[" << cmd.button() << ']'
750                 << endl;
751
752         // FIXME: this should not be possible.
753         if (!buffer_)
754                 return Update::None;
755
756         Cursor & cur = cursor_;
757         // Default Update flags.
758         Update::flags updateFlags = Update::Force | Update::FitCursor;
759
760         switch (cmd.action) {
761
762         case LFUN_UNDO:
763                 cur.message(_("Undo"));
764                 cur.clearSelection();
765                 if (!textUndo(*this)) {
766                         cur.message(_("No further undo information"));
767                         updateFlags = Update::None;
768                 }
769                 switchKeyMap();
770                 break;
771
772         case LFUN_REDO:
773                 cur.message(_("Redo"));
774                 cur.clearSelection();
775                 if (!textRedo(*this)) {
776                         cur.message(_("No further redo information"));
777                         updateFlags = Update::None;
778                 }
779                 switchKeyMap();
780                 break;
781
782         case LFUN_FILE_INSERT:
783                 // FIXME UNICODE
784                 menuInsertLyXFile(to_utf8(cmd.argument()));
785                 break;
786
787         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
788                 // FIXME UNICODE
789                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
790                 break;
791
792         case LFUN_FILE_INSERT_PLAINTEXT:
793                 // FIXME UNICODE
794                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
795                 break;
796
797         case LFUN_FONT_STATE:
798                 cur.message(cur.currentState());
799                 break;
800
801         case LFUN_BOOKMARK_SAVE:
802                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
803                 break;
804
805         case LFUN_LABEL_GOTO: {
806                 docstring label = cmd.argument();
807                 if (label.empty()) {
808                         InsetRef * inset =
809                                 getInsetByCode<InsetRef>(cursor_,
810                                                          Inset::REF_CODE);
811                         if (inset) {
812                                 label = inset->getParam("reference");
813                                 // persistent=false: use temp_bookmark
814                                 saveBookmark(0);
815                         }
816                 }
817
818                 if (!label.empty())
819                         gotoLabel(label);
820                 break;
821         }
822
823         case LFUN_PARAGRAPH_GOTO: {
824                 int const id = convert<int>(to_utf8(cmd.argument()));
825                 int i = 0;
826                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
827                         ParIterator par = b->getParFromID(id);
828                         if (par == b->par_iterator_end()) {
829                                 LYXERR(Debug::INFO)
830                                         << "No matching paragraph found! ["
831                                         << id << "]." << endl;
832                         } else {
833                                 LYXERR(Debug::INFO)
834                                         << "Paragraph " << par->id()
835                                         << " found in buffer `"
836                                         << b->fileName() << "'." << endl;
837
838                                 if (b == buffer_) {
839                                         // Set the cursor
840                                         setCursor(makeDocIterator(par, 0));
841                                         switchKeyMap();
842                                 } else {
843                                         // Switch to other buffer view and resend cmd
844                                         theLyXFunc().dispatch(FuncRequest(
845                                                 LFUN_BUFFER_SWITCH, b->fileName()));
846                                         theLyXFunc().dispatch(cmd);
847                                         updateFlags = Update::None;
848                                 }
849                                 break;
850                         }
851                         ++i;
852                 }
853                 break;
854         }
855
856         case LFUN_OUTLINE_UP:
857                 toc::outline(toc::Up, cursor_);
858                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
859                 updateLabels(*buffer_);
860                 break;
861         case LFUN_OUTLINE_DOWN:
862                 toc::outline(toc::Down, cursor_);
863                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
864                 updateLabels(*buffer_);
865                 break;
866         case LFUN_OUTLINE_IN:
867                 toc::outline(toc::In, cursor_);
868                 updateLabels(*buffer_);
869                 break;
870         case LFUN_OUTLINE_OUT:
871                 toc::outline(toc::Out, cursor_);
872                 updateLabels(*buffer_);
873                 break;
874
875         case LFUN_NOTE_NEXT:
876                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
877                 break;
878
879         case LFUN_REFERENCE_NEXT: {
880                 vector<Inset_code> tmp;
881                 tmp.push_back(Inset::LABEL_CODE);
882                 tmp.push_back(Inset::REF_CODE);
883                 bv_funcs::gotoInset(this, tmp, true);
884                 break;
885         }
886
887         case LFUN_CHANGES_TRACK:
888                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
889                 break;
890
891         case LFUN_CHANGES_OUTPUT:
892                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
893                 if (buffer_->params().outputChanges) {
894                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
895                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
896                                           LaTeXFeatures::isAvailable("xcolor");
897                 
898                         if (!dvipost && !xcolorsoul) {
899                                 Alert::warning(_("Changes not shown in LaTeX output"),
900                                                _("Changes will not be highlighted in LaTeX output, "
901                                                  "because neither dvipost nor xcolor/soul are installed.\n"
902                                                  "Please install these packages or redefine "
903                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
904                         } else if (!xcolorsoul) {
905                                 Alert::warning(_("Changes not shown in LaTeX output"),
906                                                _("Changes will not be highlighted in LaTeX output "
907                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
908                                                  "Please install both packages or redefine "
909                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
910                         }
911                 }
912                 break;
913
914         case LFUN_CHANGE_NEXT:
915                 findNextChange(this);
916                 break;
917
918         case LFUN_CHANGES_MERGE:
919                 if (findNextChange(this))
920                         showDialog("changes");
921                 break;
922
923         case LFUN_ALL_CHANGES_ACCEPT:
924                 // select complete document
925                 cursor_.reset(buffer_->inset());
926                 cursor_.selHandle(true);
927                 buffer_->text().cursorBottom(cursor_);
928                 // accept everything in a single step to support atomic undo
929                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
930                 break;
931
932         case LFUN_ALL_CHANGES_REJECT:
933                 // select complete document
934                 cursor_.reset(buffer_->inset());
935                 cursor_.selHandle(true);
936                 buffer_->text().cursorBottom(cursor_);
937                 // reject everything in a single step to support atomic undo
938                 // Note: reject does not work recursively; the user may have to repeat the operation
939                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
940                 break;
941
942         case LFUN_WORD_FIND:
943                 find(this, cmd);
944                 break;
945
946         case LFUN_WORD_REPLACE:
947                 replace(this, cmd);
948                 break;
949
950         case LFUN_MARK_OFF:
951                 cur.clearSelection();
952                 cur.resetAnchor();
953                 cur.message(from_utf8(N_("Mark off")));
954                 break;
955
956         case LFUN_MARK_ON:
957                 cur.clearSelection();
958                 cur.mark() = true;
959                 cur.resetAnchor();
960                 cur.message(from_utf8(N_("Mark on")));
961                 break;
962
963         case LFUN_MARK_TOGGLE:
964                 cur.clearSelection();
965                 if (cur.mark()) {
966                         cur.mark() = false;
967                         cur.message(from_utf8(N_("Mark removed")));
968                 } else {
969                         cur.mark() = true;
970                         cur.message(from_utf8(N_("Mark set")));
971                 }
972                 cur.resetAnchor();
973                 break;
974
975         case LFUN_SCREEN_RECENTER:
976                 center();
977                 break;
978
979         case LFUN_BIBTEX_DATABASE_ADD: {
980                 Cursor tmpcur = cursor_;
981                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
982                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
983                                                 Inset::BIBTEX_CODE);
984                 if (inset) {
985                         if (inset->addDatabase(to_utf8(cmd.argument())))
986                                 buffer_->updateBibfilesCache();
987                 }
988                 break;
989         }
990
991         case LFUN_BIBTEX_DATABASE_DEL: {
992                 Cursor tmpcur = cursor_;
993                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
994                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
995                                                 Inset::BIBTEX_CODE);
996                 if (inset) {
997                         if (inset->delDatabase(to_utf8(cmd.argument())))
998                                 buffer_->updateBibfilesCache();
999                 }
1000                 break;
1001         }
1002
1003         case LFUN_WORDS_COUNT: {
1004                 DocIterator from, to;
1005                 if (cur.selection()) {
1006                         from = cur.selectionBegin();
1007                         to = cur.selectionEnd();
1008                 } else {
1009                         from = doc_iterator_begin(buffer_->inset());
1010                         to = doc_iterator_end(buffer_->inset());
1011                 }
1012                 int const count = countWords(from, to);
1013                 docstring message;
1014                 if (count != 1) {
1015                         if (cur.selection())
1016                                 message = bformat(_("%1$d words in selection."),
1017                                           count);
1018                                 else
1019                                         message = bformat(_("%1$d words in document."),
1020                                                           count);
1021                 }
1022                 else {
1023                         if (cur.selection())
1024                                 message = _("One word in selection.");
1025                         else
1026                                 message = _("One word in document.");
1027                 }
1028
1029                 Alert::information(_("Count words"), message);
1030         }
1031                 break;
1032
1033         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1034                 // turn compression on/off
1035                 buffer_->params().compressed = !buffer_->params().compressed;
1036                 break;
1037
1038         case LFUN_NEXT_INSET_TOGGLE: {
1039                 // this is the real function we want to invoke
1040                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1041                 // if there is an inset at cursor, see whether it
1042                 // wants to toggle.
1043                 Inset * inset = cur.nextInset();
1044                 if (inset && inset->isActive()) {
1045                         Cursor tmpcur = cur;
1046                         tmpcur.pushLeft(*inset);
1047                         inset->dispatch(tmpcur, tmpcmd);
1048                         if (tmpcur.result().dispatched()) {
1049                                 cur.dispatched();
1050                         }
1051                 }
1052                 // if it did not work, try the underlying inset.
1053                 if (!cur.result().dispatched())
1054                         cur.dispatch(tmpcmd);
1055
1056                 if (cur.result().dispatched())
1057                         cur.clearSelection();
1058
1059                 break;
1060         }
1061
1062         default:
1063                 updateFlags = Update::None;
1064         }
1065
1066         return updateFlags;
1067 }
1068
1069
1070 docstring const BufferView::requestSelection()
1071 {
1072         if (!buffer_)
1073                 return docstring();
1074
1075         Cursor & cur = cursor_;
1076
1077         if (!cur.selection()) {
1078                 xsel_cache_.set = false;
1079                 return docstring();
1080         }
1081
1082         if (!xsel_cache_.set ||
1083             cur.top() != xsel_cache_.cursor ||
1084             cur.anchor_.top() != xsel_cache_.anchor)
1085         {
1086                 xsel_cache_.cursor = cur.top();
1087                 xsel_cache_.anchor = cur.anchor_.top();
1088                 xsel_cache_.set = cur.selection();
1089                 return cur.selectionAsString(false);
1090         }
1091         return docstring();
1092 }
1093
1094
1095 void BufferView::clearSelection()
1096 {
1097         if (buffer_) {
1098                 cursor_.clearSelection();
1099                 // Clear the selection buffer. Otherwise a subsequent
1100                 // middle-mouse-button paste would use the selection buffer,
1101                 // not the more current external selection.
1102                 cap::clearSelection();
1103                 xsel_cache_.set = false;
1104                 // The buffer did not really change, but this causes the
1105                 // redraw we need because we cleared the selection above.
1106                 buffer_->changed();
1107         }
1108 }
1109
1110
1111 void BufferView::workAreaResize(int width, int height)
1112 {
1113         // Update from work area
1114         width_ = width;
1115         height_ = height;
1116
1117         // The complete text metrics will be redone.
1118         text_metrics_.clear();
1119
1120         if (buffer_)
1121                 resize();
1122 }
1123
1124
1125 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1126 {
1127         pit_type pit = text.getPitNearY(*this, y);
1128         BOOST_ASSERT(pit != -1);
1129         Paragraph const & par = text.getPar(pit);
1130
1131         LYXERR(Debug::DEBUG)
1132                 << BOOST_CURRENT_FUNCTION
1133                 << ": x: " << x
1134                 << " y: " << y
1135                 << "  pit: " << pit
1136                 << endl;
1137         InsetList::const_iterator iit = par.insetlist.begin();
1138         InsetList::const_iterator iend = par.insetlist.end();
1139         for (; iit != iend; ++iit) {
1140                 Inset * const inset = iit->inset;
1141                 if (inset->covers(*this, x, y)) {
1142                         if (!inset->descendable())
1143                                 // No need to go further down if the inset is not 
1144                                 // descendable.
1145                                 return inset;
1146
1147                         size_t cell_number = inset->nargs();
1148                         // Check all the inner cell.
1149                         for (size_t i = 0; i != cell_number; ++i) {
1150                                 Text const * inner_text = inset->getText(i);
1151                                 if (inner_text) {
1152                                         // Try deeper.
1153                                         Inset const * inset_deeper = 
1154                                                 getCoveringInset(*inner_text, x, y);
1155                                         if (inset_deeper)
1156                                                 return inset_deeper;
1157                                 }
1158                         }
1159
1160                         LYXERR(Debug::DEBUG)
1161                                 << BOOST_CURRENT_FUNCTION
1162                                 << ": Hit inset: " << inset << endl;
1163                         return inset;
1164                 }
1165         }
1166         LYXERR(Debug::DEBUG)
1167                 << BOOST_CURRENT_FUNCTION
1168                 << ": No inset hit. " << endl;
1169         return 0;
1170 }
1171
1172
1173 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1174 {
1175         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1176
1177         // This is only called for mouse related events including
1178         // LFUN_FILE_OPEN generated by drag-and-drop.
1179         FuncRequest cmd = cmd0;
1180
1181         // E.g. Qt mouse press when no buffer
1182         if (!buffer_)
1183                 return false;
1184
1185         Cursor cur(*this);
1186         cur.push(buffer_->inset());
1187         cur.selection() = cursor_.selection();
1188
1189         // Either the inset under the cursor or the
1190         // surrounding Text will handle this event.
1191
1192         // make sure we stay within the screen...
1193         cmd.y = min(max(cmd.y, -1), height_);
1194         
1195         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1196                 
1197                 // Get inset under mouse, if there is one.
1198                 Inset const * covering_inset = 
1199                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1200                 if (covering_inset == last_inset_)
1201                         // Same inset, no need to do anything...
1202                         return false;
1203
1204                 bool need_redraw = false;
1205                 // const_cast because of setMouseHover().
1206                 Inset * inset = const_cast<Inset *>(covering_inset);
1207                 if (last_inset_)
1208                         // Remove the hint on the last hovered inset (if any).
1209                         need_redraw |= last_inset_->setMouseHover(false);
1210                 if (inset)
1211                         // Highlighted the newly hovered inset (if any).
1212                         need_redraw |= inset->setMouseHover(true);
1213                 last_inset_ = inset;
1214
1215                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1216                 // not expose the button for redraw. We adjust here the metrics dimension
1217                 // to enable a full redraw.
1218                 // FIXME: It is possible to redraw only the area around the button!
1219                 if (need_redraw 
1220                         && metrics_info_.update_strategy == SingleParUpdate) {
1221                         // FIXME: It should be possible to redraw only the area around 
1222                         // the button by doing this:
1223                         //
1224                         //metrics_info_.singlepar = false;
1225                         //metrics_info_.y1 = ymin of button;
1226                         //metrics_info_.y2 = ymax of button;
1227                         //
1228                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1229                         // between background updates and text updates. So we use the hammer
1230                         // solution for now. We could also avoid the updateMetrics() below
1231                         // by using the first and last pit of the CoordCache. Have a look
1232                         // at Text::getPitNearY() to see what I mean.
1233                         //
1234                         //metrics_info_.pit1 = first pit of CoordCache;
1235                         //metrics_info_.pit2 = last pit of CoordCache;
1236                         //metrics_info_.singlepar = false;
1237                         //metrics_info_.y1 = 0;
1238                         //metrics_info_.y2 = height_;
1239                         //
1240                         updateMetrics(false);
1241                 }
1242
1243                 // This event (moving without mouse click) is not passed further.
1244                 // This should be changed if it is further utilized.
1245                 return need_redraw;
1246         }
1247         
1248         // Build temporary cursor.
1249         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1250
1251         // Put anchor at the same position.
1252         cur.resetAnchor();
1253
1254         // Try to dispatch to an non-editable inset near this position
1255         // via the temp cursor. If the inset wishes to change the real
1256         // cursor it has to do so explicitly by using
1257         //  cur.bv().cursor() = cur;  (or similar)
1258         if (inset) {
1259                 inset->dispatch(cur, cmd);
1260         }
1261
1262         // Now dispatch to the temporary cursor. If the real cursor should
1263         // be modified, the inset's dispatch has to do so explicitly.
1264         if (!cur.result().dispatched())
1265                 cur.dispatch(cmd);
1266
1267         // Redraw if requested and necessary.
1268         if (cur.result().dispatched() && cur.result().update())
1269                 return update(cur.result().update());
1270
1271         return false;
1272 }
1273
1274
1275 void BufferView::scroll(int /*lines*/)
1276 {
1277 //      if (!buffer_)
1278 //              return;
1279 //
1280 //      Text const * t = &buffer_->text();
1281 //      int const line_height = defaultRowHeight();
1282 //
1283 //      // The new absolute coordinate
1284 //      int new_top_y = top_y() + lines * line_height;
1285 //
1286 //      // Restrict to a valid value
1287 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1288 //      new_top_y = std::max(0, new_top_y);
1289 //
1290 //      scrollDocView(new_top_y);
1291 //
1292 }
1293
1294
1295 void BufferView::setCursorFromRow(int row)
1296 {
1297         int tmpid = -1;
1298         int tmppos = -1;
1299
1300         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1301
1302         if (tmpid == -1)
1303                 buffer_->text().setCursor(cursor_, 0, 0);
1304         else
1305                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1306 }
1307
1308
1309 void BufferView::gotoLabel(docstring const & label)
1310 {
1311         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1312                 vector<docstring> labels;
1313                 it->getLabelList(*buffer_, labels);
1314                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1315                         setCursor(it);
1316                         update();
1317                         return;
1318                 }
1319         }
1320 }
1321
1322
1323 TextMetrics const & BufferView::textMetrics(Text const * t) const
1324 {
1325         return const_cast<BufferView *>(this)->textMetrics(t);
1326 }
1327
1328
1329 TextMetrics & BufferView::textMetrics(Text const * t)
1330 {
1331         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1332         if (tmc_it == text_metrics_.end()) {
1333                 tmc_it = text_metrics_.insert(
1334                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1335         }       
1336         return tmc_it->second;
1337 }
1338
1339
1340 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1341                 pit_type pit) const
1342 {
1343         return textMetrics(t).parMetrics(pit);
1344 }
1345
1346
1347 int BufferView::workHeight() const
1348 {
1349         return height_;
1350 }
1351
1352
1353 void BufferView::setCursor(DocIterator const & dit)
1354 {
1355         size_t const n = dit.depth();
1356         for (size_t i = 0; i < n; ++i)
1357                 dit[i].inset().edit(cursor_, true);
1358
1359         cursor_.setCursor(dit);
1360         cursor_.selection() = false;
1361 }
1362
1363
1364 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1365 {
1366         // Would be wrong to delete anything if we have a selection.
1367         if (cur.selection())
1368                 return false;
1369
1370         bool need_anchor_change = false;
1371         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1372                 need_anchor_change);
1373
1374         if (need_anchor_change)
1375                 cur.resetAnchor();
1376         
1377         if (!changed)
1378                 return false;
1379
1380         updateLabels(*buffer_);
1381
1382         updateMetrics(false);
1383         buffer_->changed();
1384         return true;
1385 }
1386
1387
1388 bool BufferView::mouseSetCursor(Cursor & cur)
1389 {
1390         BOOST_ASSERT(&cur.bv() == this);
1391
1392         // Has the cursor just left the inset?
1393         bool badcursor = false;
1394         bool leftinset = (&cursor_.inset() != &cur.inset());
1395         if (leftinset)
1396                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1397
1398         // do the dEPM magic if needed
1399         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1400         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1401         // the leftinset bool would not be necessary (badcursor instead).
1402         bool update = leftinset;
1403         if (!badcursor && cursor_.inTexted())
1404                 update |= checkDepm(cur, cursor_);
1405
1406         // if the cursor was in an empty script inset and the new
1407         // position is in the nucleus of the inset, notifyCursorLeaves
1408         // will kill the script inset itself. So we check all the
1409         // elements of the cursor to make sure that they are correct.
1410         // For an example, see bug 2933: 
1411         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1412         // The code below could maybe be moved to a DocIterator method.
1413         //lyxerr << "cur before " << cur <<std::endl;
1414         DocIterator dit(cur.inset());
1415         dit.push_back(cur.bottom());
1416         size_t i = 1;
1417         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1418                 dit.push_back(cur[i]);
1419                 ++i;
1420         }
1421         //lyxerr << "5 cur after" << dit <<std::endl;
1422
1423         cursor_.setCursor(dit);
1424         cursor_.clearSelection();
1425         finishUndo();
1426         return update;
1427 }
1428
1429
1430 void BufferView::putSelectionAt(DocIterator const & cur,
1431                                 int length, bool backwards)
1432 {
1433         cursor_.clearSelection();
1434
1435         setCursor(cur);
1436
1437         if (length) {
1438                 if (backwards) {
1439                         cursor_.pos() += length;
1440                         cursor_.setSelection(cursor_, -length);
1441                 } else
1442                         cursor_.setSelection(cursor_, length);
1443                 cap::saveSelection(cursor_);
1444         }
1445 }
1446
1447
1448 Cursor & BufferView::cursor()
1449 {
1450         return cursor_;
1451 }
1452
1453
1454 Cursor const & BufferView::cursor() const
1455 {
1456         return cursor_;
1457 }
1458
1459
1460 pit_type BufferView::anchor_ref() const
1461 {
1462         return anchor_ref_;
1463 }
1464
1465
1466 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1467 {
1468         return metrics_info_;
1469 }
1470
1471
1472 // FIXME: We should split-up updateMetrics() for the singlepar case.
1473 void BufferView::updateMetrics(bool singlepar)
1474 {
1475         Text & buftext = buffer_->text();
1476         TextMetrics & tm = textMetrics(&buftext);
1477         pit_type size = int(buftext.paragraphs().size());
1478
1479         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1480                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1481                 offset_ref_ = 0;
1482         }
1483         
1484         // If the paragraph metrics has changed, we can not
1485         // use the singlepar optimisation.
1486         if (singlepar
1487                 // In Single Paragraph mode, rebreak only
1488                 // the (main text, not inset!) paragraph containing the cursor.
1489                 // (if this paragraph contains insets etc., rebreaking will
1490                 // recursively descend)
1491                 && tm.redoParagraph(cursor_.bottom().pit()))
1492                 singlepar = false;
1493
1494         pit_type const pit = anchor_ref_;
1495         int pit1 = pit;
1496         int pit2 = pit;
1497         size_t const npit = buftext.paragraphs().size();
1498
1499         // Rebreak anchor paragraph.
1500         if (!singlepar)
1501                 tm.redoParagraph(pit);
1502         
1503         // Clear out the position cache in case of full screen redraw.
1504         if (!singlepar)
1505                 coord_cache_.clear();
1506
1507         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1508
1509         // Redo paragraphs above anchor if necessary.
1510         int y1 = y0;
1511         while (y1 > 0 && pit1 > 0) {
1512                 y1 -= tm.parMetrics(pit1).ascent();
1513                 --pit1;
1514                 if (!singlepar)
1515                         tm.redoParagraph(pit1);
1516                 y1 -= tm.parMetrics(pit1).descent();
1517         }
1518
1519
1520         // Take care of ascent of first line
1521         y1 -= tm.parMetrics(pit1).ascent();
1522
1523         // Normalize anchor for next time
1524         anchor_ref_ = pit1;
1525         offset_ref_ = -y1;
1526
1527         // Grey at the beginning is ugly
1528         if (pit1 == 0 && y1 > 0) {
1529                 y0 -= y1;
1530                 y1 = 0;
1531                 anchor_ref_ = 0;
1532         }
1533
1534         // Redo paragraphs below the anchor if necessary.
1535         int y2 = y0;
1536         while (y2 < height_ && pit2 < int(npit) - 1) {
1537                 y2 += tm.parMetrics(pit2).descent();
1538                 ++pit2;
1539                 if (!singlepar)
1540                         tm.redoParagraph(pit2);
1541                 y2 += tm.parMetrics(pit2).ascent();
1542         }
1543
1544         // Take care of descent of last line
1545         y2 += tm.parMetrics(pit2).descent();
1546
1547         // The coordinates of all these paragraphs are correct, cache them
1548         int y = y1;
1549         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1550         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1551                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1552                 y += pm.ascent();
1553                 parPos[pit] = Point(0, y);
1554                 if (singlepar && pit == cursor_.bottom().pit()) {
1555                         // In Single Paragraph mode, collect here the
1556                         // y1 and y2 of the (one) paragraph the cursor is in
1557                         y1 = y - pm.ascent();
1558                         y2 = y + pm.descent();
1559                 }
1560                 y += pm.descent();
1561         }
1562
1563         if (singlepar) {
1564                 // collect cursor paragraph iter bounds
1565                 pit1 = cursor_.bottom().pit();
1566                 pit2 = cursor_.bottom().pit();
1567         }
1568
1569         LYXERR(Debug::DEBUG)
1570                 << BOOST_CURRENT_FUNCTION
1571                 << " y1: " << y1
1572                 << " y2: " << y2
1573                 << " pit1: " << pit1
1574                 << " pit2: " << pit2
1575                 << " npit: " << npit
1576                 << " singlepar: " << singlepar
1577                 << "size: " << size
1578                 << endl;
1579
1580         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
1581                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1582
1583         if (lyxerr.debugging(Debug::WORKAREA)) {
1584                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1585                 coord_cache_.dump();
1586         }
1587 }
1588
1589
1590 void BufferView::menuInsertLyXFile(string const & filenm)
1591 {
1592         BOOST_ASSERT(cursor_.inTexted());
1593         string filename = filenm;
1594
1595         if (filename.empty()) {
1596                 // Launch a file browser
1597                 // FIXME UNICODE
1598                 string initpath = lyxrc.document_path;
1599
1600                 if (buffer_) {
1601                         string const trypath = buffer_->filePath();
1602                         // If directory is writeable, use this as default.
1603                         if (isDirWriteable(FileName(trypath)))
1604                                 initpath = trypath;
1605                 }
1606
1607                 // FIXME UNICODE
1608                 FileDialog fileDlg(_("Select LyX document to insert"),
1609                         LFUN_FILE_INSERT,
1610                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1611                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1612
1613                 FileDialog::Result result =
1614                         fileDlg.open(from_utf8(initpath),
1615                                      FileFilterList(_("LyX Documents (*.lyx)")),
1616                                      docstring());
1617
1618                 if (result.first == FileDialog::Later)
1619                         return;
1620
1621                 // FIXME UNICODE
1622                 filename = to_utf8(result.second);
1623
1624                 // check selected filename
1625                 if (filename.empty()) {
1626                         // emit message signal.
1627                         message(_("Canceled."));
1628                         return;
1629                 }
1630         }
1631
1632         // Get absolute path of file and add ".lyx"
1633         // to the filename if necessary
1634         filename = fileSearch(string(), filename, "lyx").absFilename();
1635
1636         docstring const disp_fn = makeDisplayPath(filename);
1637         // emit message signal.
1638         message(bformat(_("Inserting document %1$s..."), disp_fn));
1639
1640         docstring res;
1641         Buffer buf("", false);
1642         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1643                 ErrorList & el = buffer_->errorList("Parse");
1644                 // Copy the inserted document error list into the current buffer one.
1645                 el = buf.errorList("Parse");
1646                 recordUndo(cursor_);
1647                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1648                                              buf.params().textclass, el);
1649                 res = _("Document %1$s inserted.");
1650         } else
1651                 res = _("Could not insert document %1$s");
1652
1653         // emit message signal.
1654         message(bformat(res, disp_fn));
1655         buffer_->errors("Parse");
1656         resize();
1657 }
1658
1659 } // namespace lyx