]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
add a \unbind keyword and a few utility functions (unbind, write, delkey) to KeyMap...
[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 "CoordCache.h"
24 #include "Cursor.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 "LyX.h"
39 #include "lyxfind.h"
40 #include "LyXFunc.h"
41 #include "Layout.h"
42 #include "LyXRC.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Session.h"
49 #include "Text.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TexRow.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetRef.h"
60 #include "insets/InsetText.h"
61
62 #include "frontends/alert.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/Package.h"
75 #include "support/types.h"
76 #include "support/fs_extras.h"
77
78 #include <boost/bind.hpp>
79 #include <boost/current_function.hpp>
80 #include <boost/next_prior.hpp>
81 #include <boost/filesystem/operations.hpp>
82
83 #include <cerrno>
84 #include <fstream>
85 #include <functional>
86 #include <vector>
87
88 using std::distance;
89 using std::endl;
90 using std::ifstream;
91 using std::istringstream;
92 using std::istream_iterator;
93 using std::make_pair;
94 using std::min;
95 using std::max;
96 using std::mem_fun_ref;
97 using std::string;
98 using std::vector;
99
100 namespace fs = boost::filesystem;
101
102 namespace lyx {
103
104 using support::addPath;
105 using support::bformat;
106 using support::FileFilterList;
107 using support::FileName;
108 using support::fileSearch;
109 using support::makeDisplayPath;
110 using support::makeAbsPath;
111 using support::package;
112
113 namespace Alert = frontend::Alert;
114
115 namespace {
116
117 /// Return an inset of this class if it exists at the current cursor position
118 template <class T>
119 T * getInsetByCode(Cursor const & cur, InsetCode code)
120 {
121         DocIterator it = cur;
122         Inset * inset = it.nextInset();
123         if (inset && inset->lyxCode() == code)
124                 return static_cast<T*>(inset);
125         return 0;
126 }
127
128
129 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
130         bool same_content);
131
132 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
133         string const & contents)
134 {
135         DocIterator tmpdit = dit;
136
137         while (tmpdit) {
138                 Inset const * inset = tmpdit.nextInset();
139                 if (inset
140                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
141                     && (contents.empty() ||
142                     static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
143                         dit = tmpdit;
144                         return true;
145                 }
146                 tmpdit.forwardInset();
147         }
148
149         return false;
150 }
151
152
153 /// Looks for next inset with one of the the given code
154 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
155         bool same_content)
156 {
157         string contents;
158         DocIterator tmpdit = dit;
159         tmpdit.forwardInset();
160         if (!tmpdit)
161                 return false;
162
163         if (same_content) {
164                 Inset const * inset = tmpdit.nextInset();
165                 if (inset
166                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
167                         contents = static_cast<InsetCommand const *>(inset)->getContents();
168                 }
169         }
170
171         if (!findNextInset(tmpdit, codes, contents)) {
172                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
173                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
174                         if (!findNextInset(tmpdit, codes, contents))
175                                 return false;
176                 } else
177                         return false;
178         }
179
180         dit = tmpdit;
181         return true;
182 }
183
184
185 /// Looks for next inset with the given code
186 void findInset(DocIterator & dit, InsetCode code, bool same_content)
187 {
188         findInset(dit, vector<InsetCode>(1, code), same_content);
189 }
190
191
192 /// Moves cursor to the next inset with one of the given codes.
193 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
194                bool same_content)
195 {
196         Cursor tmpcur = bv->cursor();
197         if (!findInset(tmpcur, codes, same_content)) {
198                 bv->cursor().message(_("No more insets"));
199                 return;
200         }
201
202         tmpcur.clearSelection();
203         bv->setCursor(tmpcur);
204 }
205
206
207 /// Moves cursor to the next inset with given code.
208 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
209 {
210         gotoInset(bv, vector<InsetCode>(1, code), same_content);
211 }
212
213
214
215 /// the type of outline operation
216 enum OutlineOp {
217         OutlineUp, // Move this header with text down
218         OutlineDown,   // Move this header with text up
219         OutlineIn, // Make this header deeper
220         OutlineOut // Make this header shallower
221 };
222
223
224 void outline(OutlineOp mode, Cursor & cur)
225 {
226         Buffer & buf = cur.buffer();
227         pit_type & pit = cur.pit();
228         ParagraphList & pars = buf.text().paragraphs();
229         ParagraphList::iterator bgn = pars.begin();
230         // The first paragraph of the area to be copied:
231         ParagraphList::iterator start = boost::next(bgn, pit);
232         // The final paragraph of area to be copied:
233         ParagraphList::iterator finish = start;
234         ParagraphList::iterator end = pars.end();
235
236         TextClass::const_iterator lit =
237                 buf.params().getTextClass().begin();
238         TextClass::const_iterator const lend =
239                 buf.params().getTextClass().end();
240
241         int const thistoclevel = start->layout()->toclevel;
242         int toclevel;
243         switch (mode) {
244                 case OutlineUp: {
245                         // Move out (down) from this section header
246                         if (finish != end)
247                                 ++finish;
248                         // Seek the one (on same level) below
249                         for (; finish != end; ++finish) {
250                                 toclevel = finish->layout()->toclevel;
251                                 if (toclevel != Layout::NOT_IN_TOC
252                                     && toclevel <= thistoclevel) {
253                                         break;
254                                 }
255                         }
256                         ParagraphList::iterator dest = start;
257                         // Move out (up) from this header
258                         if (dest == bgn)
259                                 break;
260                         // Search previous same-level header above
261                         do {
262                                 --dest;
263                                 toclevel = dest->layout()->toclevel;
264                         } while(dest != bgn
265                                 && (toclevel == Layout::NOT_IN_TOC
266                                     || toclevel > thistoclevel));
267                         // Not found; do nothing
268                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
269                                 break;
270                         pit_type const newpit = std::distance(bgn, dest);
271                         pit_type const len = std::distance(start, finish);
272                         pit_type const deletepit = pit + len;
273                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
274                         pars.insert(dest, start, finish);
275                         start = boost::next(pars.begin(), deletepit);
276                         pit = newpit;
277                         pars.erase(start, finish);
278                         break;
279                 }
280                 case OutlineDown: {
281                         // Go down out of current header:
282                         if (finish != end)
283                                 ++finish;
284                         // Find next same-level header:
285                         for (; finish != end; ++finish) {
286                                 toclevel = finish->layout()->toclevel;
287                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
288                                         break;
289                         }
290                         ParagraphList::iterator dest = finish;
291                         // Go one down from *this* header:
292                         if (dest != end)
293                                 ++dest;
294                         else
295                                 break;
296                         // Go further down to find header to insert in front of:
297                         for (; dest != end; ++dest) {
298                                 toclevel = dest->layout()->toclevel;
299                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
300                                         break;
301                         }
302                         // One such was found:
303                         pit_type newpit = std::distance(bgn, dest);
304                         pit_type const len = std::distance(start, finish);
305                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
306                         pars.insert(dest, start, finish);
307                         start = boost::next(bgn, pit);
308                         pit = newpit - len;
309                         pars.erase(start, finish);
310                         break;
311                 }
312                 case OutlineIn:
313                         buf.undo().recordUndo(cur);
314                         for (; lit != lend; ++lit) {
315                                 if ((*lit)->toclevel == thistoclevel + 1 &&
316                                     start->layout()->labeltype == (*lit)->labeltype) {
317                                         start->layout((*lit));
318                                         break;
319                                 }
320                         }
321                         break;
322                 case OutlineOut:
323                         buf.undo().recordUndo(cur);
324                         for (; lit != lend; ++lit) {
325                                 if ((*lit)->toclevel == thistoclevel - 1 &&
326                                     start->layout()->labeltype == (*lit)->labeltype) {
327                                         start->layout((*lit));
328                                         break;
329                                 }
330                         }
331                         break;
332                 default:
333                         break;
334         }
335 }
336
337 /// A map from a Text to the associated text metrics
338 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
339
340 } // anon namespace
341
342
343 /////////////////////////////////////////////////////////////////////
344 //
345 // BufferView
346 //
347 /////////////////////////////////////////////////////////////////////
348
349 struct BufferView::Private
350 {
351         Private(BufferView & bv): wh_(0), cursor_(bv),
352                 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
353                 need_centering_(false), last_inset_(0), gui_(0)
354         {}
355
356         ///
357         ScrollbarParameters scrollbarParameters_;
358         ///
359         ViewMetricsInfo metrics_info_;
360         ///
361         CoordCache coord_cache_;
362
363         /// Estimated average par height for scrollbar.
364         int wh_;
365         /// this is used to handle XSelection events in the right manner.
366         struct {
367                 CursorSlice cursor;
368                 CursorSlice anchor;
369                 bool set;
370         } xsel_cache_;
371         ///
372         Cursor cursor_;
373         ///
374         bool multiparsel_cache_;
375         ///
376         pit_type anchor_ref_;
377         ///
378         int offset_ref_;
379         ///
380         bool need_centering_;
381
382         /// keyboard mapping object.
383         Intl intl_;
384
385         /// last visited inset.
386         /** kept to send setMouseHover(false).
387           * Not owned, so don't delete.
388           */
389         Inset * last_inset_;
390
391         mutable TextMetricsCache text_metrics_;
392
393         /// Whom to notify.
394         /** Not owned, so don't delete.
395           */
396         frontend::GuiBufferViewDelegate * gui_;
397 };
398
399
400 BufferView::BufferView(Buffer & buf)
401         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
402 {
403         d->xsel_cache_.set = false;
404         d->intl_.initKeyMapper(lyxrc.use_kbmap);
405
406         d->cursor_.push(buffer_.inset());
407         d->cursor_.resetAnchor();
408         d->cursor_.setCurrentFont();
409
410         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
411                 graphics::Previews::get().generateBufferPreviews(buffer_);
412 }
413
414
415 BufferView::~BufferView()
416 {
417         // current buffer is going to be switched-off, save cursor pos
418         // Ideally, the whole cursor stack should be saved, but session
419         // currently can only handle bottom (whole document) level pit and pos.
420         // That is to say, if a cursor is in a nested inset, it will be
421         // restore to the left of the top level inset.
422         LyX::ref().session().lastFilePos().save(
423                 support::FileName(buffer_.absFileName()),
424                 boost::tie(d->cursor_.bottom().pit(), d->cursor_.bottom().pos()) );
425
426         delete d;
427 }
428
429
430 Intl & BufferView::getIntl()
431 {
432         return d->intl_;
433 }
434
435
436 Intl const & BufferView::getIntl() const
437 {
438         return d->intl_;
439 }
440
441
442 CoordCache & BufferView::coordCache()
443 {
444         return d->coord_cache_;
445 }
446
447
448 CoordCache const & BufferView::coordCache() const
449 {
450         return d->coord_cache_;
451 }
452
453
454 Buffer & BufferView::buffer()
455 {
456         return buffer_;
457 }
458
459
460 Buffer const & BufferView::buffer() const
461 {
462         return buffer_;
463 }
464
465
466 bool BufferView::fitCursor()
467 {
468         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
469                 frontend::FontMetrics const & fm =
470                         theFontMetrics(d->cursor_.getFont());
471                 int const asc = fm.maxAscent();
472                 int const des = fm.maxDescent();
473                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
474                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
475                         return false;
476         }
477         center();
478         return true;
479 }
480
481
482 bool BufferView::multiParSel()
483 {
484         if (!d->cursor_.selection())
485                 return false;
486         bool ret = d->multiparsel_cache_;
487         d->multiparsel_cache_ = d->cursor_.selBegin().pit() != d->cursor_.selEnd().pit();
488         // Either this, or previous selection spans paragraphs
489         return ret || d->multiparsel_cache_;
490 }
491
492
493 void BufferView::processUpdateFlags(Update::flags flags)
494 {
495         // last_inset_ points to the last visited inset. This pointer may become
496         // invalid because of keyboard editing. Since all such operations
497         // causes screen update(), I reset last_inset_ to avoid such a problem.
498         d->last_inset_ = 0;
499         // This is close to a hot-path.
500         LYXERR(Debug::DEBUG)
501                 << BOOST_CURRENT_FUNCTION
502                 << "[fitcursor = " << (flags & Update::FitCursor)
503                 << ", forceupdate = " << (flags & Update::Force)
504                 << ", singlepar = " << (flags & Update::SinglePar)
505                 << "]  buffer: " << &buffer_ << endl;
506
507         // Update macro store
508         if (!(cursor().inMathed() && cursor().inMacroMode()))
509                 buffer_.buildMacros();
510
511         // Now do the first drawing step if needed. This consists on updating
512         // the CoordCache in updateMetrics().
513         // The second drawing step is done in WorkArea::redraw() if needed.
514
515         // Case when no explicit update is requested.
516         if (!flags) {
517                 // no need to redraw anything.
518                 d->metrics_info_.update_strategy = NoScreenUpdate;
519                 return;
520         }
521
522         if (flags == Update::Decoration) {
523                 d->metrics_info_.update_strategy = DecorationUpdate;
524                 buffer_.changed();
525                 return;
526         }
527
528         if (flags == Update::FitCursor
529                 || flags == (Update::Decoration | Update::FitCursor)) {
530                 bool const fit_cursor = fitCursor();
531                 // tell the frontend to update the screen if needed.
532                 if (fit_cursor) {
533                         updateMetrics(false);
534                         buffer_.changed();
535                         return;
536                 }
537                 if (flags & Update::Decoration) {
538                         d->metrics_info_.update_strategy = DecorationUpdate;
539                         buffer_.changed();
540                         return;
541                 }
542                 // no screen update is needed.
543                 d->metrics_info_.update_strategy = NoScreenUpdate;
544                 return;
545         }
546
547         bool full_metrics = flags & Update::Force;
548         if (flags & Update::MultiParSel)
549                 full_metrics |= multiParSel();
550
551         bool const single_par = !full_metrics;
552         updateMetrics(single_par);
553
554         if (!(flags & Update::FitCursor)) {
555                 buffer_.changed();
556                 return;
557         }
558
559         //FIXME: updateMetrics() does not update paragraph position
560         // This is done at draw() time. So we need a redraw!
561         buffer_.changed();
562         if (!fitCursor())
563                 // The screen has already been updated thanks to the
564                 // 'buffer_.changed()' call three line above. So no need
565                 // to redraw again.
566                 return;
567
568         // The screen has been recentered around the cursor position so
569         // refresh it:
570         updateMetrics(false);
571         buffer_.changed();
572 }
573
574
575 void BufferView::updateScrollbar()
576 {
577         Text & t = buffer_.text();
578         TextMetrics & tm = d->text_metrics_[&t];
579
580         int const parsize = int(t.paragraphs().size() - 1);
581         if (d->anchor_ref_ >  parsize)  {
582                 d->anchor_ref_ = parsize;
583                 d->offset_ref_ = 0;
584         }
585
586         LYXERR(Debug::GUI)
587                 << BOOST_CURRENT_FUNCTION
588                 << " Updating scrollbar: height: " << t.paragraphs().size()
589                 << " curr par: " << d->cursor_.bottom().pit()
590                 << " default height " << defaultRowHeight() << endl;
591
592         // It would be better to fix the scrollbar to understand
593         // values in [0..1] and divide everything by wh
594
595         // estimated average paragraph height:
596         if (d->wh_ == 0)
597                 d->wh_ = height_ / 4;
598
599         int h = tm.parMetrics(d->anchor_ref_).height();
600
601         // Normalize anchor/offset (MV):
602         while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
603                 d->anchor_ref_++;
604                 d->offset_ref_ -= h;
605                 h = tm.parMetrics(d->anchor_ref_).height();
606         }
607         // Look at paragraph heights on-screen
608         int sumh = 0;
609         int nh = 0;
610         for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
611                 if (sumh > height_)
612                         break;
613                 int const h2 = tm.parMetrics(pit).height();
614                 sumh += h2;
615                 nh++;
616         }
617
618         BOOST_ASSERT(nh);
619         int const hav = sumh / nh;
620         // More realistic average paragraph height
621         if (hav > d->wh_)
622                 d->wh_ = hav;
623
624         BOOST_ASSERT(h);
625         d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
626         d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
627         d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
628 }
629
630
631 ScrollbarParameters const & BufferView::scrollbarParameters() const
632 {
633         return d->scrollbarParameters_;
634 }
635
636
637 void BufferView::scrollDocView(int value)
638 {
639         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
640                            << "[ value = " << value << "]" << endl;
641
642         Text & t = buffer_.text();
643         TextMetrics & tm = d->text_metrics_[&t];
644
645         float const bar = value / float(d->wh_ * t.paragraphs().size());
646
647         d->anchor_ref_ = int(bar * t.paragraphs().size());
648         if (d->anchor_ref_ >  int(t.paragraphs().size()) - 1)
649                 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
650
651         tm.redoParagraph(d->anchor_ref_);
652         int const h = tm.parMetrics(d->anchor_ref_).height();
653         d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
654         updateMetrics(false);
655         buffer_.changed();
656 }
657
658
659 void BufferView::setCursorFromScrollbar()
660 {
661         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
662
663         int const height = 2 * defaultRowHeight();
664         int const first = height;
665         int const last = height_ - height;
666         Cursor & cur = d->cursor_;
667
668         switch (cursorStatus(cur)) {
669         case CUR_ABOVE:
670                 // We reset the cursor because cursorStatus() does not
671                 // work when the cursor is within mathed.
672                 cur.reset(buffer_.inset());
673                 tm.setCursorFromCoordinates(cur, 0, first);
674                 cur.clearSelection();
675                 break;
676         case CUR_BELOW:
677                 // We reset the cursor because cursorStatus() does not
678                 // work when the cursor is within mathed.
679                 cur.reset(buffer_.inset());
680                 tm.setCursorFromCoordinates(cur, 0, last);
681                 cur.clearSelection();
682                 break;
683         case CUR_INSIDE:
684                 int const y = getPos(cur, cur.boundary()).y_;
685                 int const newy = min(last, max(y, first));
686                 if (y != newy) {
687                         cur.reset(buffer_.inset());
688                         tm.setCursorFromCoordinates(cur, 0, newy);
689                 }
690         }
691 }
692
693
694 Change const BufferView::getCurrentChange() const
695 {
696         if (!d->cursor_.selection())
697                 return Change(Change::UNCHANGED);
698
699         DocIterator dit = d->cursor_.selectionBegin();
700         return dit.paragraph().lookupChange(dit.pos());
701 }
702
703
704 // this could be used elsewhere as well?
705 // FIXME: This does not work within mathed!
706 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
707 {
708         Point const p = getPos(dit, dit.boundary());
709         if (p.y_ < 0)
710                 return CUR_ABOVE;
711         if (p.y_ > workHeight())
712                 return CUR_BELOW;
713         return CUR_INSIDE;
714 }
715
716
717 void BufferView::saveBookmark(unsigned int idx)
718 {
719         // tenatively save bookmark, id and pos will be used to
720         // acturately locate a bookmark in a 'live' lyx session.
721         // pit and pos will be updated with bottom level pit/pos
722         // when lyx exits.
723         LyX::ref().session().bookmarks().save(
724                 FileName(buffer_.absFileName()),
725                 d->cursor_.bottom().pit(),
726                 d->cursor_.bottom().pos(),
727                 d->cursor_.paragraph().id(),
728                 d->cursor_.pos(),
729                 idx
730         );
731         if (idx)
732                 // emit message signal.
733                 message(_("Save bookmark"));
734 }
735
736
737 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
738         int top_id, pos_type top_pos)
739 {
740         bool success = false;
741         DocIterator doc_it;
742
743         d->cursor_.clearSelection();
744
745         // if a valid par_id is given, try it first
746         // This is the case for a 'live' bookmark when unique paragraph ID
747         // is used to track bookmarks.
748         if (top_id > 0) {
749                 ParIterator par = buffer_.getParFromID(top_id);
750                 if (par != buffer_.par_iterator_end()) {
751                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
752                         // Some slices of the iterator may not be
753                         // reachable (e.g. closed collapsable inset)
754                         // so the dociterator may need to be
755                         // shortened. Otherwise, setCursor may crash
756                         // lyx when the cursor can not be set to these
757                         // insets.
758                         size_t const n = doc_it.depth();
759                         for (size_t i = 0; i < n; ++i)
760                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
761                                         doc_it.resize(i);
762                                         break;
763                                 }
764                         success = true;
765                 }
766         }
767
768         // if top_id == 0, or searching through top_id failed
769         // This is the case for a 'restored' bookmark when only bottom
770         // (document level) pit was saved. Because of this, bookmark
771         // restoration is inaccurate. If a bookmark was within an inset,
772         // it will be restored to the left of the outmost inset that contains
773         // the bookmark.
774         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
775                 doc_it = doc_iterator_begin(buffer_.inset());
776                 doc_it.pit() = bottom_pit;
777                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
778                 success = true;
779         }
780
781         if (success) {
782                 // Note: only bottom (document) level pit is set.
783                 setCursor(doc_it);
784                 // set the current font.
785                 d->cursor_.setCurrentFont();
786                 // center the screen on this new position.
787                 center();
788         }
789
790         return success;
791 }
792
793
794 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
795 {
796         if (lyxrc.rtl_support) {
797                 if (d->cursor_.real_current_font.isRightToLeft()) {
798                         if (d->intl_.keymap == Intl::PRIMARY)
799                                 d->intl_.keyMapSec();
800                 } else {
801                         if (d->intl_.keymap == Intl::SECONDARY)
802                                 d->intl_.keyMapPrim();
803                 }
804         }
805
806         d->intl_.getTransManager().translateAndInsert(c, t, cur);
807 }
808
809
810 int BufferView::workWidth() const
811 {
812         return width_;
813 }
814
815
816 void BufferView::updateOffsetRef()
817 {
818         // No need to update d->offset_ref_ in this case.
819         if (!d->need_centering_)
820                 return;
821
822         // We are not properly started yet, delay until resizing is
823         // done.
824         if (height_ == 0)
825                 return;
826
827         CursorSlice & bot = d->cursor_.bottom();
828         TextMetrics & tm = d->text_metrics_[bot.text()];
829         ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
830         int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
831         d->offset_ref_ = y + pm.ascent() - height_ / 2;
832
833         d->need_centering_ = false;
834 }
835
836
837 void BufferView::center()
838 {
839         d->anchor_ref_ = d->cursor_.bottom().pit();
840         d->need_centering_ = true;
841 }
842
843
844 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
845 {
846         FuncStatus flag;
847
848         Cursor & cur = d->cursor_;
849
850         switch (cmd.action) {
851
852         case LFUN_UNDO:
853                 flag.enabled(buffer_.undo().hasUndoStack());
854                 break;
855         case LFUN_REDO:
856                 flag.enabled(buffer_.undo().hasRedoStack());
857                 break;
858         case LFUN_FILE_INSERT:
859         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
860         case LFUN_FILE_INSERT_PLAINTEXT:
861         case LFUN_BOOKMARK_SAVE:
862                 // FIXME: Actually, these LFUNS should be moved to Text
863                 flag.enabled(cur.inTexted());
864                 break;
865         case LFUN_FONT_STATE:
866         case LFUN_LABEL_INSERT:
867         case LFUN_INFO_INSERT:
868         case LFUN_PARAGRAPH_GOTO:
869         // FIXME handle non-trivially
870         case LFUN_OUTLINE_UP:
871         case LFUN_OUTLINE_DOWN:
872         case LFUN_OUTLINE_IN:
873         case LFUN_OUTLINE_OUT:
874         case LFUN_NOTE_NEXT:
875         case LFUN_REFERENCE_NEXT:
876         case LFUN_WORD_FIND:
877         case LFUN_WORD_REPLACE:
878         case LFUN_MARK_OFF:
879         case LFUN_MARK_ON:
880         case LFUN_MARK_TOGGLE:
881         case LFUN_SCREEN_RECENTER:
882         case LFUN_BIBTEX_DATABASE_ADD:
883         case LFUN_BIBTEX_DATABASE_DEL:
884         case LFUN_WORDS_COUNT:
885         case LFUN_NEXT_INSET_TOGGLE:
886                 flag.enabled(true);
887                 break;
888
889         case LFUN_LABEL_GOTO: {
890                 flag.enabled(!cmd.argument().empty()
891                     || getInsetByCode<InsetRef>(cur, REF_CODE));
892                 break;
893         }
894
895         case LFUN_CHANGES_TRACK:
896                 flag.enabled(true);
897                 flag.setOnOff(buffer_.params().trackChanges);
898                 break;
899
900         case LFUN_CHANGES_OUTPUT:
901                 flag.enabled(true);
902                 flag.setOnOff(buffer_.params().outputChanges);
903                 break;
904
905         case LFUN_CHANGES_MERGE:
906         case LFUN_CHANGE_NEXT:
907         case LFUN_ALL_CHANGES_ACCEPT:
908         case LFUN_ALL_CHANGES_REJECT:
909                 // TODO: context-sensitive enabling of LFUNs
910                 // In principle, these command should only be enabled if there
911                 // is a change in the document. However, without proper
912                 // optimizations, this will inevitably result in poor performance.
913                 flag.enabled(true);
914                 break;
915
916         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
917                 flag.setOnOff(buffer_.params().compressed);
918                 break;
919         }
920
921         case LFUN_SCREEN_UP:
922         case LFUN_SCREEN_DOWN:
923                 flag.enabled(true);
924                 break;
925
926         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
927         // everywhere else before this can enabled:
928         case LFUN_SCREEN_UP_SELECT:
929         case LFUN_SCREEN_DOWN_SELECT:
930                 flag.enabled(false);
931                 break;
932
933         case LFUN_LAYOUT_TABULAR:
934                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
935                 break;
936
937         case LFUN_LAYOUT:
938         case LFUN_LAYOUT_PARAGRAPH:
939                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
940                 break;
941
942         case LFUN_INSET_SETTINGS: {
943                 InsetCode code = cur.inset().lyxCode();
944                 bool enable = false;
945                 switch (code) {
946                         case TABULAR_CODE:
947                                 enable = cmd.argument() == "tabular";
948                                 break;
949                         case ERT_CODE:
950                                 enable = cmd.argument() == "ert";
951                                 break;
952                         case FLOAT_CODE:
953                                 enable = cmd.argument() == "float";
954                                 break;
955                         case WRAP_CODE:
956                                 enable = cmd.argument() == "wrap";
957                                 break;
958                         case NOTE_CODE:
959                                 enable = cmd.argument() == "note";
960                                 break;
961                         case BRANCH_CODE:
962                                 enable = cmd.argument() == "branch";
963                                 break;
964                         case BOX_CODE:
965                                 enable = cmd.argument() == "box";
966                                 break;
967                         case LISTINGS_CODE:
968                                 enable = cmd.argument() == "listings";
969                                 break;
970                         default:
971                                 break;
972                 }
973                 flag.enabled(enable);
974                 break;
975         }
976
977         case LFUN_DIALOG_SHOW_NEW_INSET:
978                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
979                         cur.inset().lyxCode() != LISTINGS_CODE);
980                 if (cur.inset().lyxCode() == CAPTION_CODE) {
981                         FuncStatus flag;
982                         if (cur.inset().getStatus(cur, cmd, flag))
983                                 return flag;
984                 }
985                 break;
986
987         default:
988                 flag.enabled(false);
989         }
990
991         return flag;
992 }
993
994
995 Update::flags BufferView::dispatch(FuncRequest const & cmd)
996 {
997         //lyxerr << BOOST_CURRENT_FUNCTION
998         //       << [ cmd = " << cmd << "]" << endl;
999
1000         // Make sure that the cached BufferView is correct.
1001         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
1002                 << " action[" << cmd.action << ']'
1003                 << " arg[" << to_utf8(cmd.argument()) << ']'
1004                 << " x[" << cmd.x << ']'
1005                 << " y[" << cmd.y << ']'
1006                 << " button[" << cmd.button() << ']'
1007                 << endl;
1008
1009         Cursor & cur = d->cursor_;
1010         // Default Update flags.
1011         Update::flags updateFlags = Update::Force | Update::FitCursor;
1012
1013         switch (cmd.action) {
1014
1015         case LFUN_UNDO:
1016                 cur.message(_("Undo"));
1017                 cur.clearSelection();
1018                 if (!cur.textUndo()) {
1019                         cur.message(_("No further undo information"));
1020                         updateFlags = Update::None;
1021                 }
1022                 break;
1023
1024         case LFUN_REDO:
1025                 cur.message(_("Redo"));
1026                 cur.clearSelection();
1027                 if (!cur.textRedo()) {
1028                         cur.message(_("No further redo information"));
1029                         updateFlags = Update::None;
1030                 }
1031                 break;
1032
1033         case LFUN_FILE_INSERT:
1034                 // FIXME UNICODE
1035                 menuInsertLyXFile(to_utf8(cmd.argument()));
1036                 break;
1037
1038         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1039                 // FIXME UNICODE
1040                 insertPlaintextFile(to_utf8(cmd.argument()), true);
1041                 break;
1042
1043         case LFUN_FILE_INSERT_PLAINTEXT:
1044                 // FIXME UNICODE
1045                 insertPlaintextFile(to_utf8(cmd.argument()), false);
1046                 break;
1047
1048         case LFUN_FONT_STATE:
1049                 cur.message(cur.currentState());
1050                 break;
1051
1052         case LFUN_BOOKMARK_SAVE:
1053                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1054                 break;
1055
1056         case LFUN_LABEL_GOTO: {
1057                 docstring label = cmd.argument();
1058                 if (label.empty()) {
1059                         InsetRef * inset =
1060                                 getInsetByCode<InsetRef>(d->cursor_,
1061                                                          REF_CODE);
1062                         if (inset) {
1063                                 label = inset->getParam("reference");
1064                                 // persistent=false: use temp_bookmark
1065                                 saveBookmark(0);
1066                         }
1067                 }
1068
1069                 if (!label.empty())
1070                         gotoLabel(label);
1071                 break;
1072         }
1073
1074         case LFUN_PARAGRAPH_GOTO: {
1075                 int const id = convert<int>(to_utf8(cmd.argument()));
1076                 int i = 0;
1077                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1078                         b = theBufferList().next(b)) {
1079
1080                         ParIterator par = b->getParFromID(id);
1081                         if (par == b->par_iterator_end()) {
1082                                 LYXERR(Debug::INFO)
1083                                         << "No matching paragraph found! ["
1084                                         << id << "]." << endl;
1085                         } else {
1086                                 LYXERR(Debug::INFO)
1087                                         << "Paragraph " << par->id()
1088                                         << " found in buffer `"
1089                                         << b->absFileName() << "'." << endl;
1090
1091                                 if (b == &buffer_) {
1092                                         // Set the cursor
1093                                         setCursor(makeDocIterator(par, 0));
1094                                 } else {
1095                                         // Switch to other buffer view and resend cmd
1096                                         theLyXFunc().dispatch(FuncRequest(
1097                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
1098                                         theLyXFunc().dispatch(cmd);
1099                                         updateFlags = Update::None;
1100                                 }
1101                                 break;
1102                         }
1103                         ++i;
1104                 }
1105                 break;
1106         }
1107
1108         case LFUN_OUTLINE_UP:
1109                 outline(OutlineUp, d->cursor_);
1110                 d->cursor_.text()->setCursor(d->cursor_, d->cursor_.pit(), 0);
1111                 updateLabels(buffer_);
1112                 break;
1113         case LFUN_OUTLINE_DOWN:
1114                 outline(OutlineDown, d->cursor_);
1115                 d->cursor_.text()->setCursor(d->cursor_, d->cursor_.pit(), 0);
1116                 updateLabels(buffer_);
1117                 break;
1118         case LFUN_OUTLINE_IN:
1119                 outline(OutlineIn, d->cursor_);
1120                 updateLabels(buffer_);
1121                 break;
1122         case LFUN_OUTLINE_OUT:
1123                 outline(OutlineOut, d->cursor_);
1124                 updateLabels(buffer_);
1125                 break;
1126
1127         case LFUN_NOTE_NEXT:
1128                 gotoInset(this, NOTE_CODE, false);
1129                 break;
1130
1131         case LFUN_REFERENCE_NEXT: {
1132                 vector<InsetCode> tmp;
1133                 tmp.push_back(LABEL_CODE);
1134                 tmp.push_back(REF_CODE);
1135                 gotoInset(this, tmp, true);
1136                 break;
1137         }
1138
1139         case LFUN_CHANGES_TRACK:
1140                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1141                 break;
1142
1143         case LFUN_CHANGES_OUTPUT:
1144                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1145                 if (buffer_.params().outputChanges) {
1146                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1147                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1148                                           LaTeXFeatures::isAvailable("xcolor");
1149
1150                         if (!dvipost && !xcolorsoul) {
1151                                 Alert::warning(_("Changes not shown in LaTeX output"),
1152                                                _("Changes will not be highlighted in LaTeX output, "
1153                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1154                                                  "Please install these packages or redefine "
1155                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1156                         } else if (!xcolorsoul) {
1157                                 Alert::warning(_("Changes not shown in LaTeX output"),
1158                                                _("Changes will not be highlighted in LaTeX output "
1159                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1160                                                  "Please install both packages or redefine "
1161                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1162                         }
1163                 }
1164                 break;
1165
1166         case LFUN_CHANGE_NEXT:
1167                 findNextChange(this);
1168                 break;
1169
1170         case LFUN_CHANGES_MERGE:
1171                 if (findNextChange(this))
1172                         showDialog("changes");
1173                 break;
1174
1175         case LFUN_ALL_CHANGES_ACCEPT:
1176                 // select complete document
1177                 d->cursor_.reset(buffer_.inset());
1178                 d->cursor_.selHandle(true);
1179                 buffer_.text().cursorBottom(d->cursor_);
1180                 // accept everything in a single step to support atomic undo
1181                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1182                 break;
1183
1184         case LFUN_ALL_CHANGES_REJECT:
1185                 // select complete document
1186                 d->cursor_.reset(buffer_.inset());
1187                 d->cursor_.selHandle(true);
1188                 buffer_.text().cursorBottom(d->cursor_);
1189                 // reject everything in a single step to support atomic undo
1190                 // Note: reject does not work recursively; the user may have to repeat the operation
1191                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1192                 break;
1193
1194         case LFUN_WORD_FIND:
1195                 find(this, cmd);
1196                 break;
1197
1198         case LFUN_WORD_REPLACE: {
1199                 bool has_deleted = false;
1200                 if (cur.selection()) {
1201                         DocIterator beg = cur.selectionBegin();
1202                         DocIterator end = cur.selectionEnd();
1203                         if (beg.pit() == end.pit()) {
1204                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1205                                         if (cur.paragraph().isDeleted(p))
1206                                                 has_deleted = true;
1207                                 }
1208                         }
1209                 }
1210                 replace(this, cmd, has_deleted);
1211                 break;
1212         }
1213
1214         case LFUN_MARK_OFF:
1215                 cur.clearSelection();
1216                 cur.resetAnchor();
1217                 cur.message(from_utf8(N_("Mark off")));
1218                 break;
1219
1220         case LFUN_MARK_ON:
1221                 cur.clearSelection();
1222                 cur.mark() = true;
1223                 cur.resetAnchor();
1224                 cur.message(from_utf8(N_("Mark on")));
1225                 break;
1226
1227         case LFUN_MARK_TOGGLE:
1228                 cur.clearSelection();
1229                 if (cur.mark()) {
1230                         cur.mark() = false;
1231                         cur.message(from_utf8(N_("Mark removed")));
1232                 } else {
1233                         cur.mark() = true;
1234                         cur.message(from_utf8(N_("Mark set")));
1235                 }
1236                 cur.resetAnchor();
1237                 break;
1238
1239         case LFUN_SCREEN_RECENTER:
1240                 center();
1241                 break;
1242
1243         case LFUN_BIBTEX_DATABASE_ADD: {
1244                 Cursor tmpcur = d->cursor_;
1245                 findInset(tmpcur, BIBTEX_CODE, false);
1246                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1247                                                 BIBTEX_CODE);
1248                 if (inset) {
1249                         if (inset->addDatabase(to_utf8(cmd.argument())))
1250                                 buffer_.updateBibfilesCache();
1251                 }
1252                 break;
1253         }
1254
1255         case LFUN_BIBTEX_DATABASE_DEL: {
1256                 Cursor tmpcur = d->cursor_;
1257                 findInset(tmpcur, BIBTEX_CODE, false);
1258                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1259                                                 BIBTEX_CODE);
1260                 if (inset) {
1261                         if (inset->delDatabase(to_utf8(cmd.argument())))
1262                                 buffer_.updateBibfilesCache();
1263                 }
1264                 break;
1265         }
1266
1267         case LFUN_WORDS_COUNT: {
1268                 DocIterator from, to;
1269                 if (cur.selection()) {
1270                         from = cur.selectionBegin();
1271                         to = cur.selectionEnd();
1272                 } else {
1273                         from = doc_iterator_begin(buffer_.inset());
1274                         to = doc_iterator_end(buffer_.inset());
1275                 }
1276                 int const count = countWords(from, to);
1277                 docstring message;
1278                 if (count != 1) {
1279                         if (cur.selection())
1280                                 message = bformat(_("%1$d words in selection."),
1281                                           count);
1282                                 else
1283                                         message = bformat(_("%1$d words in document."),
1284                                                           count);
1285                 }
1286                 else {
1287                         if (cur.selection())
1288                                 message = _("One word in selection.");
1289                         else
1290                                 message = _("One word in document.");
1291                 }
1292
1293                 Alert::information(_("Count words"), message);
1294         }
1295                 break;
1296
1297         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1298                 // turn compression on/off
1299                 buffer_.params().compressed = !buffer_.params().compressed;
1300                 break;
1301
1302         case LFUN_NEXT_INSET_TOGGLE: {
1303                 // this is the real function we want to invoke
1304                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1305                 // if there is an inset at cursor, see whether it
1306                 // wants to toggle.
1307                 Inset * inset = cur.nextInset();
1308                 if (inset) {
1309                         if (inset->isActive()) {
1310                                 Cursor tmpcur = cur;
1311                                 tmpcur.pushLeft(*inset);
1312                                 inset->dispatch(tmpcur, tmpcmd);
1313                                 if (tmpcur.result().dispatched()) {
1314                                         cur.dispatched();
1315                                 }
1316                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1317                                 inset->edit(cur, true);
1318                         }
1319                 }
1320                 // if it did not work, try the underlying inset.
1321                 if (!cur.result().dispatched())
1322                         cur.dispatch(tmpcmd);
1323
1324                 if (cur.result().dispatched())
1325                         cur.clearSelection();
1326
1327                 break;
1328         }
1329
1330         case LFUN_SCREEN_UP:
1331         case LFUN_SCREEN_DOWN: {
1332                 Point p = getPos(cur, cur.boundary());
1333                 if (p.y_ < 0 || p.y_ > height_) {
1334                         // The cursor is off-screen so recenter before proceeding.
1335                         center();
1336                         updateMetrics(false);
1337                         //FIXME: updateMetrics() does not update paragraph position
1338                         // This is done at draw() time. So we need a redraw!
1339                         buffer_.changed();
1340                         p = getPos(cur, cur.boundary());
1341                 }
1342                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1343                 cur.reset(buffer_.inset());
1344                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1345                 //FIXME: what to do with cur.x_target()?
1346                 cur.finishUndo();
1347                 // The metrics are already up to date. see scroll()
1348                 updateFlags = Update::None;
1349                 break;
1350         }
1351
1352         case LFUN_SCREEN_UP_SELECT:
1353         case LFUN_SCREEN_DOWN_SELECT: {
1354                 cur.selHandle(true);
1355                 size_t initial_depth = cur.depth();
1356                 Point const p = getPos(cur, cur.boundary());
1357                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1358                 // FIXME: We need to verify if the cursor stayed within an inset...
1359                 //cur.reset(buffer_.inset());
1360                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1361                 cur.finishUndo();
1362                 while (cur.depth() > initial_depth) {
1363                         cur.forwardInset();
1364                 }
1365                 // FIXME: we need to do a redraw again because of the selection
1366                 buffer_.changed();
1367                 updateFlags = Update::Force | Update::FitCursor;
1368                 break;
1369         }
1370
1371         default:
1372                 updateFlags = Update::None;
1373         }
1374
1375         return updateFlags;
1376 }
1377
1378
1379 docstring const BufferView::requestSelection()
1380 {
1381         Cursor & cur = d->cursor_;
1382
1383         if (!cur.selection()) {
1384                 d->xsel_cache_.set = false;
1385                 return docstring();
1386         }
1387
1388         if (!d->xsel_cache_.set ||
1389             cur.top() != d->xsel_cache_.cursor ||
1390             cur.anchor_.top() != d->xsel_cache_.anchor)
1391         {
1392                 d->xsel_cache_.cursor = cur.top();
1393                 d->xsel_cache_.anchor = cur.anchor_.top();
1394                 d->xsel_cache_.set = cur.selection();
1395                 return cur.selectionAsString(false);
1396         }
1397         return docstring();
1398 }
1399
1400
1401 void BufferView::clearSelection()
1402 {
1403         d->cursor_.clearSelection();
1404         // Clear the selection buffer. Otherwise a subsequent
1405         // middle-mouse-button paste would use the selection buffer,
1406         // not the more current external selection.
1407         cap::clearSelection();
1408         d->xsel_cache_.set = false;
1409         // The buffer did not really change, but this causes the
1410         // redraw we need because we cleared the selection above.
1411         buffer_.changed();
1412 }
1413
1414
1415 void BufferView::resize(int width, int height)
1416 {
1417         // Update from work area
1418         width_ = width;
1419         height_ = height;
1420
1421         updateMetrics(false);
1422 }
1423
1424
1425 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1426 {
1427         TextMetrics & tm = d->text_metrics_[&text];
1428         Inset * inset = tm.checkInsetHit(x, y);
1429         if (!inset)
1430                 return 0;
1431
1432         if (!inset->descendable())
1433                 // No need to go further down if the inset is not
1434                 // descendable.
1435                 return inset;
1436
1437         size_t cell_number = inset->nargs();
1438         // Check all the inner cell.
1439         for (size_t i = 0; i != cell_number; ++i) {
1440                 Text const * inner_text = inset->getText(i);
1441                 if (inner_text) {
1442                         // Try deeper.
1443                         Inset const * inset_deeper =
1444                                 getCoveringInset(*inner_text, x, y);
1445                         if (inset_deeper)
1446                                 return inset_deeper;
1447                 }
1448         }
1449
1450         return inset;
1451 }
1452
1453
1454 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1455 {
1456         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1457
1458         // This is only called for mouse related events including
1459         // LFUN_FILE_OPEN generated by drag-and-drop.
1460         FuncRequest cmd = cmd0;
1461
1462         Cursor cur(*this);
1463         cur.push(buffer_.inset());
1464         cur.selection() = d->cursor_.selection();
1465
1466         // Either the inset under the cursor or the
1467         // surrounding Text will handle this event.
1468
1469         // make sure we stay within the screen...
1470         cmd.y = min(max(cmd.y, -1), height_);
1471
1472         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1473
1474                 // Get inset under mouse, if there is one.
1475                 Inset const * covering_inset =
1476                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1477                 if (covering_inset == d->last_inset_)
1478                         // Same inset, no need to do anything...
1479                         return;
1480
1481                 bool need_redraw = false;
1482                 // const_cast because of setMouseHover().
1483                 Inset * inset = const_cast<Inset *>(covering_inset);
1484                 if (d->last_inset_)
1485                         // Remove the hint on the last hovered inset (if any).
1486                         need_redraw |= d->last_inset_->setMouseHover(false);
1487                 if (inset)
1488                         // Highlighted the newly hovered inset (if any).
1489                         need_redraw |= inset->setMouseHover(true);
1490                 d->last_inset_ = inset;
1491                 if (!need_redraw)
1492                         return;
1493
1494                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1495                 // not expose the button for redraw. We adjust here the metrics dimension
1496                 // to enable a full redraw in any case as this is not costly.
1497                 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
1498                 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1499                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1500                 int y1 = firstpm.second->position() - firstpm.second->ascent();
1501                 int y2 = lastpm.second->position() + lastpm.second->descent();
1502                 d->metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1503                         FullScreenUpdate, buffer_.text().paragraphs().size());
1504                 // Reinitialize anchor to first pit.
1505                 d->anchor_ref_ = firstpm.first;
1506                 d->offset_ref_ = -y1;
1507                 LYXERR(Debug::PAINTING)
1508                         << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1509                         << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1510                         << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1511
1512                 // This event (moving without mouse click) is not passed further.
1513                 // This should be changed if it is further utilized.
1514                 buffer_.changed();
1515                 return;
1516         }
1517
1518         // Build temporary cursor.
1519         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1520
1521         // Put anchor at the same position.
1522         cur.resetAnchor();
1523
1524         // Try to dispatch to an non-editable inset near this position
1525         // via the temp cursor. If the inset wishes to change the real
1526         // cursor it has to do so explicitly by using
1527         //  cur.bv().cursor() = cur;  (or similar)
1528         if (inset)
1529                 inset->dispatch(cur, cmd);
1530
1531         // Now dispatch to the temporary cursor. If the real cursor should
1532         // be modified, the inset's dispatch has to do so explicitly.
1533         if (!cur.result().dispatched())
1534                 cur.dispatch(cmd);
1535
1536         //Do we have a selection?
1537         theSelection().haveSelection(cursor().selection());
1538
1539         // If the command has been dispatched,
1540         if (cur.result().dispatched()
1541                 // an update is asked,
1542                 && cur.result().update())
1543                 processUpdateFlags(cur.result().update());
1544 }
1545
1546
1547 void BufferView::scroll(int y)
1548 {
1549         if (y > 0)
1550                 scrollDown(y);
1551         else if (y < 0)
1552                 scrollUp(-y);
1553 }
1554
1555
1556 void BufferView::scrollDown(int offset)
1557 {
1558         Text * text = &buffer_.text();
1559         TextMetrics & tm = d->text_metrics_[text];
1560         int ymax = height_ + offset;
1561         while (true) {
1562                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1563                 int bottom_pos = last.second->position() + last.second->descent();
1564                 if (last.first + 1 == int(text->paragraphs().size())) {
1565                         if (bottom_pos <= height_)
1566                                 return;
1567                         offset = min(offset, bottom_pos - height_);
1568                         break;
1569                 }
1570                 if (bottom_pos > ymax)
1571                         break;
1572                 tm.newParMetricsDown();
1573         }
1574         d->offset_ref_ += offset;
1575         updateMetrics(false);
1576         buffer_.changed();
1577 }
1578
1579
1580 void BufferView::scrollUp(int offset)
1581 {
1582         Text * text = &buffer_.text();
1583         TextMetrics & tm = d->text_metrics_[text];
1584         int ymin = - offset;
1585         while (true) {
1586                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1587                 int top_pos = first.second->position() - first.second->ascent();
1588                 if (first.first == 0) {
1589                         if (top_pos >= 0)
1590                                 return;
1591                         offset = min(offset, - top_pos);
1592                         break;
1593                 }
1594                 if (top_pos < ymin)
1595                         break;
1596                 tm.newParMetricsUp();
1597         }
1598         d->offset_ref_ -= offset;
1599         updateMetrics(false);
1600         buffer_.changed();
1601 }
1602
1603
1604 void BufferView::setCursorFromRow(int row)
1605 {
1606         int tmpid = -1;
1607         int tmppos = -1;
1608
1609         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1610
1611         d->cursor_.reset(buffer_.inset());
1612         if (tmpid == -1)
1613                 buffer_.text().setCursor(d->cursor_, 0, 0);
1614         else
1615                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1616 }
1617
1618
1619 void BufferView::gotoLabel(docstring const & label)
1620 {
1621         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1622                 vector<docstring> labels;
1623                 it->getLabelList(buffer_, labels);
1624                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1625                         setCursor(it);
1626                         processUpdateFlags(Update::FitCursor);
1627                         return;
1628                 }
1629         }
1630 }
1631
1632
1633 TextMetrics const & BufferView::textMetrics(Text const * t) const
1634 {
1635         return const_cast<BufferView *>(this)->textMetrics(t);
1636 }
1637
1638
1639 TextMetrics & BufferView::textMetrics(Text const * t)
1640 {
1641         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1642         if (tmc_it == d->text_metrics_.end()) {
1643                 tmc_it = d->text_metrics_.insert(
1644                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1645         }
1646         return tmc_it->second;
1647 }
1648
1649
1650 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1651                 pit_type pit) const
1652 {
1653         return textMetrics(t).parMetrics(pit);
1654 }
1655
1656
1657 int BufferView::workHeight() const
1658 {
1659         return height_;
1660 }
1661
1662
1663 void BufferView::setCursor(DocIterator const & dit)
1664 {
1665         size_t const n = dit.depth();
1666         for (size_t i = 0; i < n; ++i)
1667                 dit[i].inset().edit(d->cursor_, true);
1668
1669         d->cursor_.setCursor(dit);
1670         d->cursor_.selection() = false;
1671 }
1672
1673
1674 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1675 {
1676         // Would be wrong to delete anything if we have a selection.
1677         if (cur.selection())
1678                 return false;
1679
1680         bool need_anchor_change = false;
1681         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1682                 need_anchor_change);
1683
1684         if (need_anchor_change)
1685                 cur.resetAnchor();
1686
1687         if (!changed)
1688                 return false;
1689
1690         updateLabels(buffer_);
1691
1692         updateMetrics(false);
1693         buffer_.changed();
1694         return true;
1695 }
1696
1697
1698 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1699 {
1700         BOOST_ASSERT(&cur.bv() == this);
1701
1702         if (!select)
1703                 // this event will clear selection so we save selection for
1704                 // persistent selection
1705                 cap::saveSelection(cursor());
1706
1707         // Has the cursor just left the inset?
1708         bool badcursor = false;
1709         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1710         if (leftinset)
1711                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1712
1713         // FIXME: shift-mouse selection doesn't work well across insets.
1714         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1715
1716         // do the dEPM magic if needed
1717         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1718         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1719         // the leftinset bool would not be necessary (badcursor instead).
1720         bool update = leftinset;
1721         if (!do_selection && !badcursor && d->cursor_.inTexted())
1722                 update |= checkDepm(cur, d->cursor_);
1723
1724         // if the cursor was in an empty script inset and the new
1725         // position is in the nucleus of the inset, notifyCursorLeaves
1726         // will kill the script inset itself. So we check all the
1727         // elements of the cursor to make sure that they are correct.
1728         // For an example, see bug 2933:
1729         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1730         // The code below could maybe be moved to a DocIterator method.
1731         //lyxerr << "cur before " << cur <<std::endl;
1732         DocIterator dit(cur.inset());
1733         dit.push_back(cur.bottom());
1734         size_t i = 1;
1735         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1736                 dit.push_back(cur[i]);
1737                 ++i;
1738         }
1739         //lyxerr << "5 cur after" << dit <<std::endl;
1740
1741         d->cursor_.setCursor(dit);
1742         d->cursor_.boundary(cur.boundary());
1743         if (do_selection)
1744                 d->cursor_.setSelection();
1745         else
1746                 d->cursor_.clearSelection();
1747
1748         d->cursor_.finishUndo();
1749         return update;
1750 }
1751
1752
1753 void BufferView::putSelectionAt(DocIterator const & cur,
1754                                 int length, bool backwards)
1755 {
1756         d->cursor_.clearSelection();
1757
1758         setCursor(cur);
1759
1760         if (length) {
1761                 if (backwards) {
1762                         d->cursor_.pos() += length;
1763                         d->cursor_.setSelection(d->cursor_, -length);
1764                 } else
1765                         d->cursor_.setSelection(d->cursor_, length);
1766         }
1767 }
1768
1769
1770 Cursor & BufferView::cursor()
1771 {
1772         return d->cursor_;
1773 }
1774
1775
1776 Cursor const & BufferView::cursor() const
1777 {
1778         return d->cursor_;
1779 }
1780
1781
1782 pit_type BufferView::anchor_ref() const
1783 {
1784         return d->anchor_ref_;
1785 }
1786
1787
1788 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1789 {
1790         return d->metrics_info_;
1791 }
1792
1793
1794 bool BufferView::singleParUpdate()
1795 {
1796         Text & buftext = buffer_.text();
1797         pit_type const bottom_pit = d->cursor_.bottom().pit();
1798         TextMetrics & tm = textMetrics(&buftext);
1799         int old_height = tm.parMetrics(bottom_pit).height();
1800
1801         // In Single Paragraph mode, rebreak only
1802         // the (main text, not inset!) paragraph containing the cursor.
1803         // (if this paragraph contains insets etc., rebreaking will
1804         // recursively descend)
1805         tm.redoParagraph(bottom_pit);
1806         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1807         if (pm.height() != old_height)
1808                 // Paragraph height has changed so we cannot proceed to
1809                 // the singlePar optimisation.
1810                 return false;
1811
1812         int y1 = pm.position() - pm.ascent();
1813         int y2 = pm.position() + pm.descent();
1814         d->metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1815                 SingleParUpdate, buftext.paragraphs().size());
1816         LYXERR(Debug::PAINTING)
1817                 << BOOST_CURRENT_FUNCTION
1818                 << "\ny1: " << y1
1819                 << " y2: " << y2
1820                 << " pit: " << bottom_pit
1821                 << " singlepar: 1"
1822                 << endl;
1823         return true;
1824 }
1825
1826
1827 void BufferView::updateMetrics(bool singlepar)
1828 {
1829         if (singlepar && singleParUpdate())
1830                 // No need to update the full screen metrics.
1831                 return;
1832
1833         Text & buftext = buffer_.text();
1834         pit_type const npit = int(buftext.paragraphs().size());
1835
1836         if (d->anchor_ref_ > int(npit - 1)) {
1837                 d->anchor_ref_ = int(npit - 1);
1838                 d->offset_ref_ = 0;
1839         }
1840
1841         // Clear out the position cache in case of full screen redraw,
1842         d->coord_cache_.clear();
1843
1844         // Clear out paragraph metrics to avoid having invalid metrics
1845         // in the cache from paragraphs not relayouted below
1846         // The complete text metrics will be redone.
1847         d->text_metrics_.clear();
1848
1849         TextMetrics & tm = textMetrics(&buftext);
1850
1851         pit_type const pit = d->anchor_ref_;
1852         int pit1 = pit;
1853         int pit2 = pit;
1854
1855         // Rebreak anchor paragraph.
1856         tm.redoParagraph(pit);
1857
1858         // Take care of anchor offset if case a recentering is needed.
1859         updateOffsetRef();
1860
1861         int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1862
1863         // Redo paragraphs above anchor if necessary.
1864         int y1 = y0;
1865         while (y1 > 0 && pit1 > 0) {
1866                 y1 -= tm.parMetrics(pit1).ascent();
1867                 --pit1;
1868                 tm.redoParagraph(pit1);
1869                 y1 -= tm.parMetrics(pit1).descent();
1870         }
1871
1872         // Take care of ascent of first line
1873         y1 -= tm.parMetrics(pit1).ascent();
1874
1875         // Normalize anchor for next time
1876         d->anchor_ref_ = pit1;
1877         d->offset_ref_ = -y1;
1878
1879         // Grey at the beginning is ugly
1880         if (pit1 == 0 && y1 > 0) {
1881                 y0 -= y1;
1882                 y1 = 0;
1883                 d->anchor_ref_ = 0;
1884         }
1885
1886         // Redo paragraphs below the anchor if necessary.
1887         int y2 = y0;
1888         while (y2 < height_ && pit2 < int(npit) - 1) {
1889                 y2 += tm.parMetrics(pit2).descent();
1890                 ++pit2;
1891                 tm.redoParagraph(pit2);
1892                 y2 += tm.parMetrics(pit2).ascent();
1893         }
1894
1895         // Take care of descent of last line
1896         y2 += tm.parMetrics(pit2).descent();
1897
1898         LYXERR(Debug::PAINTING)
1899                 << BOOST_CURRENT_FUNCTION
1900                 << "\n y1: " << y1
1901                 << " y2: " << y2
1902                 << " pit1: " << pit1
1903                 << " pit2: " << pit2
1904                 << " npit: " << npit
1905                 << " singlepar: 0"
1906                 << endl;
1907
1908         d->metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1909                 FullScreenUpdate, npit);
1910
1911         if (lyxerr.debugging(Debug::WORKAREA)) {
1912                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1913                 d->coord_cache_.dump();
1914         }
1915 }
1916
1917
1918 void BufferView::menuInsertLyXFile(string const & filenm)
1919 {
1920         BOOST_ASSERT(d->cursor_.inTexted());
1921         string filename = filenm;
1922
1923         if (filename.empty()) {
1924                 // Launch a file browser
1925                 // FIXME UNICODE
1926                 string initpath = lyxrc.document_path;
1927                 string const trypath = buffer_.filePath();
1928                 // If directory is writeable, use this as default.
1929                 if (FileName(trypath).isDirWritable())
1930                         initpath = trypath;
1931
1932                 // FIXME UNICODE
1933                 FileDialog fileDlg(_("Select LyX document to insert"),
1934                         LFUN_FILE_INSERT,
1935                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1936                         make_pair(_("Examples|#E#e"),
1937                                     from_utf8(addPath(package().system_support().absFilename(),
1938                                     "examples"))));
1939
1940                 FileDialog::Result result =
1941                         fileDlg.open(from_utf8(initpath),
1942                                      FileFilterList(_("LyX Documents (*.lyx)")),
1943                                      docstring());
1944
1945                 if (result.first == FileDialog::Later)
1946                         return;
1947
1948                 // FIXME UNICODE
1949                 filename = to_utf8(result.second);
1950
1951                 // check selected filename
1952                 if (filename.empty()) {
1953                         // emit message signal.
1954                         message(_("Canceled."));
1955                         return;
1956                 }
1957         }
1958
1959         // Get absolute path of file and add ".lyx"
1960         // to the filename if necessary
1961         filename = fileSearch(string(), filename, "lyx").absFilename();
1962
1963         docstring const disp_fn = makeDisplayPath(filename);
1964         // emit message signal.
1965         message(bformat(_("Inserting document %1$s..."), disp_fn));
1966
1967         docstring res;
1968         Buffer buf("", false);
1969         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1970                 ErrorList & el = buffer_.errorList("Parse");
1971                 // Copy the inserted document error list into the current buffer one.
1972                 el = buf.errorList("Parse");
1973                 buffer_.undo().recordUndo(d->cursor_);
1974                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1975                                              buf.params().getTextClassPtr(), el);
1976                 res = _("Document %1$s inserted.");
1977         } else
1978                 res = _("Could not insert document %1$s");
1979
1980         // emit message signal.
1981         message(bformat(res, disp_fn));
1982         buffer_.errors("Parse");
1983         updateMetrics(false);
1984 }
1985
1986
1987 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1988 {
1989         int x = 0;
1990         int y = 0;
1991         int lastw = 0;
1992
1993         // Addup contribution of nested insets, from inside to outside,
1994         // keeping the outer paragraph for a special handling below
1995         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1996                 CursorSlice const & sl = dit[i];
1997                 int xx = 0;
1998                 int yy = 0;
1999                 
2000                 // get relative position inside sl.inset()
2001                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2002                 
2003                 // Make relative position inside of the edited inset relative to sl.inset()
2004                 x += xx;
2005                 y += yy;
2006                 
2007                 // In case of an RTL inset, the edited inset will be positioned to the left
2008                 // of xx:yy
2009                 if (sl.text()) {
2010                         bool boundary_i = boundary && i + 1 == dit.depth();
2011                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2012                         if (rtl)
2013                                 x -= lastw;
2014                 }
2015
2016                 // remember width for the case that sl.inset() is positioned in an RTL inset
2017                 if (i && dit[i - 1].text()) {
2018                         // If this Inset is inside a Text Inset, retrieve the Dimension
2019                         // from the containing text instead of using Inset::dimension() which
2020                         // might not be implemented.
2021                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2022                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2023                         // to be rewritten in light of the new design.
2024                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2025                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2026                         lastw = dim.wid;
2027                 } else {
2028                         Dimension const dim = sl.inset().dimension(*this);
2029                         lastw = dim.wid;
2030                 }
2031                 
2032                 //lyxerr << "Cursor::getPos, i: "
2033                 // << i << " x: " << xx << " y: " << y << endl;
2034         }
2035
2036         // Add contribution of initial rows of outermost paragraph
2037         CursorSlice const & sl = dit[0];
2038         TextMetrics const & tm = textMetrics(sl.text());
2039         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2040         BOOST_ASSERT(!pm.rows().empty());
2041         y -= pm.rows()[0].ascent();
2042 #if 1
2043         // FIXME: document this mess
2044         size_t rend;
2045         if (sl.pos() > 0 && dit.depth() == 1) {
2046                 int pos = sl.pos();
2047                 if (pos && boundary)
2048                         --pos;
2049 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
2050                 rend = pm.pos2row(pos);
2051         } else
2052                 rend = pm.pos2row(sl.pos());
2053 #else
2054         size_t rend = pm.pos2row(sl.pos());
2055 #endif
2056         for (size_t rit = 0; rit != rend; ++rit)
2057                 y += pm.rows()[rit].height();
2058         y += pm.rows()[rend].ascent();
2059         
2060         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2061         
2062         // Make relative position from the nested inset now bufferview absolute.
2063         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2064         x += xx;
2065         
2066         // In the RTL case place the nested inset at the left of the cursor in 
2067         // the outer paragraph
2068         bool boundary_1 = boundary && 1 == dit.depth();
2069         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2070         if (rtl)
2071                 x -= lastw;
2072         
2073         return Point(x, y);
2074 }
2075
2076
2077 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2078 {
2079         CursorSlice const & bot = dit.bottom();
2080         TextMetrics const & tm = textMetrics(bot.text());
2081         if (!tm.has(bot.pit()))
2082                 return Point(-1, -1);
2083
2084         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2085         p.y_ += tm.parMetrics(bot.pit()).position();
2086         return p;
2087 }
2088
2089
2090 void BufferView::draw(frontend::Painter & pain)
2091 {
2092         PainterInfo pi(this, pain);
2093         // Should the whole screen, including insets, be refreshed?
2094         // FIXME: We should also distinguish DecorationUpdate to avoid text
2095         // drawing if possible. This is not possible to do easily right now
2096         // because of the single backing pixmap.
2097         pi.full_repaint = d->metrics_info_.update_strategy != SingleParUpdate;
2098
2099         if (pi.full_repaint)
2100                 // Clear background (if not delegated to rows)
2101                 pain.fillRectangle(0, d->metrics_info_.y1, width_,
2102                         d->metrics_info_.y2 - d->metrics_info_.y1,
2103                         buffer_.inset().backgroundColor());
2104
2105         LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
2106         Text & text = buffer_.text();
2107         TextMetrics const & tm = d->text_metrics_[&text];
2108         int y = d->metrics_info_.y1 + tm.parMetrics(d->metrics_info_.p1).ascent();
2109         if (!pi.full_repaint)
2110                 tm.drawParagraph(pi, d->metrics_info_.p1, 0, y);
2111         else
2112                 tm.draw(pi, 0, y);
2113         LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING  ***" << endl;
2114
2115         // and grey out above (should not happen later)
2116 //      lyxerr << "par ascent: " << text.getPar(d->metrics_info_.p1).ascent() << endl;
2117         if (d->metrics_info_.y1 > 0
2118                 && d->metrics_info_.update_strategy == FullScreenUpdate)
2119                 pain.fillRectangle(0, 0, width_, d->metrics_info_.y1, Color::bottomarea);
2120
2121         // and possibly grey out below
2122 //      lyxerr << "par descent: " << text.getPar(d->metrics_info_.p1).ascent() << endl;
2123         if (d->metrics_info_.y2 < height_
2124                 && d->metrics_info_.update_strategy == FullScreenUpdate)
2125                 pain.fillRectangle(0, d->metrics_info_.y2, width_,
2126                         height_ - d->metrics_info_.y2, Color::bottomarea);
2127 }
2128
2129
2130 void BufferView::message(docstring const & msg)
2131 {
2132         if (d->gui_)
2133                 d->gui_->message(msg);
2134 }
2135
2136
2137 void BufferView::showDialog(std::string const & name)
2138 {
2139         if (d->gui_)
2140                 d->gui_->showDialog(name);
2141 }
2142
2143
2144 void BufferView::showDialogWithData(std::string const & name,
2145         std::string const & data)
2146 {
2147         if (d->gui_)
2148                 d->gui_->showDialogWithData(name, data);
2149 }
2150
2151
2152 void BufferView::showInsetDialog(std::string const & name,
2153         std::string const & data, Inset * inset)
2154 {
2155         if (d->gui_)
2156                 d->gui_->showInsetDialog(name, data, inset);
2157 }
2158
2159
2160 void BufferView::updateDialog(std::string const & name, std::string const & data)
2161 {
2162         if (d->gui_)
2163                 d->gui_->updateDialog(name, data);
2164 }
2165
2166
2167 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2168 {
2169         d->gui_ = gui;
2170 }
2171
2172
2173 // FIXME: Move this out of BufferView again
2174 docstring BufferView::contentsOfPlaintextFile(string const & f,
2175         bool asParagraph)
2176 {
2177         FileName fname(f);
2178
2179         if (fname.empty()) {
2180                 FileDialog fileDlg(_("Select file to insert"),
2181                                    ( asParagraph
2182                                      ? LFUN_FILE_INSERT_PLAINTEXT_PARA 
2183                                      : LFUN_FILE_INSERT_PLAINTEXT) );
2184
2185                 FileDialog::Result result =
2186                         fileDlg.open(from_utf8(buffer().filePath()),
2187                                      FileFilterList(), docstring());
2188
2189                 if (result.first == FileDialog::Later)
2190                         return docstring();
2191
2192                 fname = makeAbsPath(to_utf8(result.second));
2193
2194                 if (fname.empty())
2195                         return docstring();
2196         }
2197
2198         if (!fs::is_readable(fname.toFilesystemEncoding())) {
2199                 docstring const error = from_ascii(strerror(errno));
2200                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2201                 docstring const text =
2202                   bformat(_("Could not read the specified document\n"
2203                             "%1$s\ndue to the error: %2$s"), file, error);
2204                 Alert::error(_("Could not read file"), text);
2205                 return docstring();
2206         }
2207
2208         ifstream ifs(fname.toFilesystemEncoding().c_str());
2209         if (!ifs) {
2210                 docstring const error = from_ascii(strerror(errno));
2211                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2212                 docstring const text =
2213                   bformat(_("Could not open the specified document\n"
2214                             "%1$s\ndue to the error: %2$s"), file, error);
2215                 Alert::error(_("Could not open file"), text);
2216                 return docstring();
2217         }
2218
2219         ifs.unsetf(std::ios::skipws);
2220         istream_iterator<char> ii(ifs);
2221         istream_iterator<char> end;
2222 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2223         // We use this until the compilers get better...
2224         std::vector<char> tmp;
2225         copy(ii, end, back_inserter(tmp));
2226         string const tmpstr(tmp.begin(), tmp.end());
2227 #else
2228         // This is what we want to use and what we will use once the
2229         // compilers get good enough.
2230         //string tmpstr(ii, end); // yet a reason for using std::string
2231         // alternate approach to get the file into a string:
2232         string tmpstr;
2233         copy(ii, end, back_inserter(tmpstr));
2234 #endif
2235
2236         // FIXME UNICODE: We don't know the encoding of the file
2237         docstring file_content = from_utf8(tmpstr);
2238         if (file_content.empty()) {
2239                 Alert::error(_("Reading not UTF-8 encoded file"),
2240                              _("The file is not UTF-8 encoded.\n"
2241                                "It will be read as local 8Bit-encoded.\n"
2242                                "If this does not give the correct result\n"
2243                                "then please change the encoding of the file\n"
2244                                "to UTF-8 with a program other than LyX.\n"));
2245                 file_content = from_local8bit(tmpstr);
2246         }
2247
2248         return normalize_c(file_content);
2249 }
2250
2251
2252 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2253 {
2254         docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2255
2256         if (tmpstr.empty())
2257                 return;
2258
2259         Cursor & cur = cursor();
2260         cap::replaceSelection(cur);
2261         buffer_.undo().recordUndo(cur);
2262         if (asParagraph)
2263                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2264         else
2265                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2266 }
2267
2268 } // namespace lyx