3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "callback.h" // added for Dispatch functions
25 #include "CoordCache.h"
26 #include "CutAndPaste.h"
28 #include "DispatchResult.h"
29 #include "ErrorList.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
36 #include "InsetIterator.h"
38 #include "LaTeXFeatures.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "rowpainter.h"
53 #include "TextClass.h"
57 #include "WordLangTuple.h"
59 #include "insets/InsetBibtex.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetRef.h"
62 #include "insets/InsetText.h"
64 #include "frontends/alert.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/FontMetrics.h"
67 #include "frontends/Painter.h"
68 #include "frontends/Selection.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/FileFilterList.h"
74 #include "support/filetools.h"
75 #include "support/Package.h"
76 #include "support/types.h"
78 #include <boost/bind.hpp>
79 #include <boost/current_function.hpp>
86 using std::istringstream;
90 using std::mem_fun_ref;
97 using support::addPath;
98 using support::bformat;
99 using support::FileFilterList;
100 using support::FileName;
101 using support::fileSearch;
102 using support::isDirWriteable;
103 using support::isFileReadable;
104 using support::makeDisplayPath;
105 using support::package;
107 namespace Alert = frontend::Alert;
111 /// Return an inset of this class if it exists at the current cursor position
113 T * getInsetByCode(Cursor & cur, Inset::Code code)
116 DocIterator it = cur;
117 if (it.nextInset() &&
118 it.nextInset()->lyxCode() == code) {
119 inset = static_cast<T*>(it.nextInset());
127 BufferView::BufferView(Buffer & buf)
128 : width_(0), height_(0), buffer_(buf), wh_(0),
130 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
131 need_centering_(false), intl_(new Intl), last_inset_(0)
133 xsel_cache_.set = false;
134 intl_->initKeyMapper(lyxrc.use_kbmap);
136 cursor_.push(buffer_.inset());
137 cursor_.resetAnchor();
138 buffer_.text().setCurrentFont(cursor_);
140 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
141 graphics::Previews::get().generateBufferPreviews(buffer_);
145 BufferView::~BufferView()
147 // current buffer is going to be switched-off, save cursor pos
148 // Ideally, the whole cursor stack should be saved, but session
149 // currently can only handle bottom (whole document) level pit and pos.
150 // That is to say, if a cursor is in a nested inset, it will be
151 // restore to the left of the top level inset.
152 LyX::ref().session().lastFilePos().save(
153 support::FileName(buffer_.fileName()),
154 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
158 Buffer & BufferView::buffer()
164 Buffer const & BufferView::buffer() const
170 bool BufferView::fitCursor()
172 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
173 frontend::FontMetrics const & fm =
174 theFontMetrics(cursor_.getFont());
175 int const asc = fm.maxAscent();
176 int const des = fm.maxDescent();
177 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
178 if (p.y_ - asc >= 0 && p.y_ + des < height_)
186 bool BufferView::multiParSel()
188 if (!cursor_.selection())
190 bool ret = multiparsel_cache_;
191 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
192 // Either this, or previous selection spans paragraphs
193 return ret || multiparsel_cache_;
197 bool BufferView::update(Update::flags flags)
199 // last_inset_ points to the last visited inset. This pointer may become
200 // invalid because of keyboard editing. Since all such operations
201 // causes screen update(), I reset last_inset_ to avoid such a problem.
203 // This is close to a hot-path.
205 << BOOST_CURRENT_FUNCTION
206 << "[fitcursor = " << (flags & Update::FitCursor)
207 << ", forceupdate = " << (flags & Update::Force)
208 << ", singlepar = " << (flags & Update::SinglePar)
209 << "] buffer: " << &buffer_ << endl;
211 // Update macro store
212 if (!(cursor().inMathed() && cursor().inMacroMode()))
213 buffer_.buildMacros();
215 // Now do the first drawing step if needed. This consists on updating
216 // the CoordCache in updateMetrics().
217 // The second drawing step is done in WorkArea::redraw() if needed.
219 // Case when no explicit update is requested.
221 // no need to redraw anything.
222 metrics_info_.update_strategy = NoScreenUpdate;
226 if (flags == Update::Decoration) {
227 metrics_info_.update_strategy = DecorationUpdate;
231 if (flags == Update::FitCursor
232 || flags == (Update::Decoration | Update::FitCursor)) {
233 bool const fit_cursor = fitCursor();
234 // tell the frontend to update the screen if needed.
236 updateMetrics(false);
239 if (flags & Update::Decoration) {
240 metrics_info_.update_strategy = DecorationUpdate;
243 // no screen update is needed.
244 metrics_info_.update_strategy = NoScreenUpdate;
248 bool full_metrics = flags & Update::Force;
249 if (flags & Update::MultiParSel)
250 full_metrics |= multiParSel();
252 bool const single_par = !full_metrics;
253 updateMetrics(single_par);
255 if (flags & Update::FitCursor && fitCursor())
256 updateMetrics(false);
258 // tell the frontend to update the screen.
263 void BufferView::updateScrollbar()
265 Text & t = buffer_.text();
266 TextMetrics & tm = text_metrics_[&t];
268 int const parsize = int(t.paragraphs().size() - 1);
269 if (anchor_ref_ > parsize) {
270 anchor_ref_ = parsize;
275 << BOOST_CURRENT_FUNCTION
276 << " Updating scrollbar: height: " << t.paragraphs().size()
277 << " curr par: " << cursor_.bottom().pit()
278 << " default height " << defaultRowHeight() << endl;
280 // It would be better to fix the scrollbar to understand
281 // values in [0..1] and divide everything by wh
283 // estimated average paragraph height:
287 int h = tm.parMetrics(anchor_ref_).height();
289 // Normalize anchor/offset (MV):
290 while (offset_ref_ > h && anchor_ref_ < parsize) {
293 h = tm.parMetrics(anchor_ref_).height();
295 // Look at paragraph heights on-screen
298 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
301 int const h2 = tm.parMetrics(pit).height();
307 int const hav = sumh / nh;
308 // More realistic average paragraph height
313 scrollbarParameters_.height = (parsize + 1) * wh_;
314 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
315 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
319 ScrollbarParameters const & BufferView::scrollbarParameters() const
321 return scrollbarParameters_;
325 void BufferView::scrollDocView(int value)
327 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
328 << "[ value = " << value << "]" << endl;
330 Text & t = buffer_.text();
331 TextMetrics & tm = text_metrics_[&t];
333 float const bar = value / float(wh_ * t.paragraphs().size());
335 anchor_ref_ = int(bar * t.paragraphs().size());
336 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
337 anchor_ref_ = int(t.paragraphs().size()) - 1;
339 tm.redoParagraph(anchor_ref_);
340 int const h = tm.parMetrics(anchor_ref_).height();
341 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
342 updateMetrics(false);
346 void BufferView::setCursorFromScrollbar()
348 Text & t = buffer_.text();
350 int const height = 2 * defaultRowHeight();
351 int const first = height;
352 int const last = height_ - height;
353 Cursor & cur = cursor_;
355 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
358 case bv_funcs::CUR_ABOVE:
359 // We reset the cursor because bv_funcs::status() does not
360 // work when the cursor is within mathed.
361 cur.reset(buffer_.inset());
362 t.setCursorFromCoordinates(cur, 0, first);
363 cur.clearSelection();
365 case bv_funcs::CUR_BELOW:
366 // We reset the cursor because bv_funcs::status() does not
367 // work when the cursor is within mathed.
368 cur.reset(buffer_.inset());
369 t.setCursorFromCoordinates(cur, 0, last);
370 cur.clearSelection();
372 case bv_funcs::CUR_INSIDE:
373 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
374 int const newy = min(last, max(y, first));
376 cur.reset(buffer_.inset());
377 t.setCursorFromCoordinates(cur, 0, newy);
383 Change const BufferView::getCurrentChange() const
385 if (!cursor_.selection())
386 return Change(Change::UNCHANGED);
388 DocIterator dit = cursor_.selectionBegin();
389 return dit.paragraph().lookupChange(dit.pos());
393 void BufferView::saveBookmark(unsigned int idx)
395 // tenatively save bookmark, id and pos will be used to
396 // acturately locate a bookmark in a 'live' lyx session.
397 // pit and pos will be updated with bottom level pit/pos
399 LyX::ref().session().bookmarks().save(
400 FileName(buffer_.fileName()),
401 cursor_.bottom().pit(),
402 cursor_.bottom().pos(),
403 cursor_.paragraph().id(),
408 // emit message signal.
409 message(_("Save bookmark"));
413 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
414 int top_id, pos_type top_pos)
416 bool success = false;
419 cursor_.clearSelection();
421 // if a valid par_id is given, try it first
422 // This is the case for a 'live' bookmark when unique paragraph ID
423 // is used to track bookmarks.
425 ParIterator par = buffer_.getParFromID(top_id);
426 if (par != buffer_.par_iterator_end()) {
427 doc_it = makeDocIterator(par, min(par->size(), top_pos));
428 // Some slices of the iterator may not be
429 // reachable (e.g. closed collapsable inset)
430 // so the dociterator may need to be
431 // shortened. Otherwise, setCursor may crash
432 // lyx when the cursor can not be set to these
434 size_t const n = doc_it.depth();
435 for (size_t i = 0; i < n; ++i)
436 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
444 // if top_id == 0, or searching through top_id failed
445 // This is the case for a 'restored' bookmark when only bottom
446 // (document level) pit was saved. Because of this, bookmark
447 // restoration is inaccurate. If a bookmark was within an inset,
448 // it will be restored to the left of the outmost inset that contains
450 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
451 doc_it = doc_iterator_begin(buffer_.inset());
452 doc_it.pit() = bottom_pit;
453 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
458 // Note: only bottom (document) level pit is set.
460 // set the current font.
461 buffer_.text().setCurrentFont(cursor_);
462 // center the screen on this new position.
470 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
472 if (lyxrc.rtl_support) {
473 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
474 if (intl_->keymap == Intl::PRIMARY)
477 if (intl_->keymap == Intl::SECONDARY)
482 intl_->getTransManager().translateAndInsert(c, t, cur);
486 int BufferView::workWidth() const
492 void BufferView::updateOffsetRef()
494 // No need to update offset_ref_ in this case.
495 if (!need_centering_)
498 // We are not properly started yet, delay until resizing is
503 CursorSlice & bot = cursor_.bottom();
504 TextMetrics & tm = text_metrics_[bot.text()];
505 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
506 Point p = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary());
507 offset_ref_ = p.y_ + pm.ascent() - height_ / 2;
509 need_centering_ = false;
513 void BufferView::center()
515 anchor_ref_ = cursor_.bottom().pit();
516 need_centering_ = true;
520 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
524 Cursor & cur = cursor_;
526 switch (cmd.action) {
529 flag.enabled(!buffer_.undostack().empty());
532 flag.enabled(!buffer_.redostack().empty());
534 case LFUN_FILE_INSERT:
535 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
536 case LFUN_FILE_INSERT_PLAINTEXT:
537 case LFUN_BOOKMARK_SAVE:
538 // FIXME: Actually, these LFUNS should be moved to Text
539 flag.enabled(cur.inTexted());
541 case LFUN_FONT_STATE:
542 case LFUN_LABEL_INSERT:
543 case LFUN_PARAGRAPH_GOTO:
544 // FIXME handle non-trivially
545 case LFUN_OUTLINE_UP:
546 case LFUN_OUTLINE_DOWN:
547 case LFUN_OUTLINE_IN:
548 case LFUN_OUTLINE_OUT:
550 case LFUN_REFERENCE_NEXT:
552 case LFUN_WORD_REPLACE:
555 case LFUN_MARK_TOGGLE:
556 case LFUN_SCREEN_RECENTER:
557 case LFUN_BIBTEX_DATABASE_ADD:
558 case LFUN_BIBTEX_DATABASE_DEL:
559 case LFUN_WORDS_COUNT:
560 case LFUN_NEXT_INSET_TOGGLE:
564 case LFUN_LABEL_GOTO: {
565 flag.enabled(!cmd.argument().empty()
566 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
570 case LFUN_CHANGES_TRACK:
572 flag.setOnOff(buffer_.params().trackChanges);
575 case LFUN_CHANGES_OUTPUT:
577 flag.setOnOff(buffer_.params().outputChanges);
580 case LFUN_CHANGES_MERGE:
581 case LFUN_CHANGE_NEXT:
582 case LFUN_ALL_CHANGES_ACCEPT:
583 case LFUN_ALL_CHANGES_REJECT:
584 // TODO: context-sensitive enabling of LFUNs
585 // In principle, these command should only be enabled if there
586 // is a change in the document. However, without proper
587 // optimizations, this will inevitably result in poor performance.
591 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
592 flag.setOnOff(buffer_.params().compressed);
604 Update::flags BufferView::dispatch(FuncRequest const & cmd)
606 //lyxerr << BOOST_CURRENT_FUNCTION
607 // << [ cmd = " << cmd << "]" << endl;
609 // Make sure that the cached BufferView is correct.
610 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
611 << " action[" << cmd.action << ']'
612 << " arg[" << to_utf8(cmd.argument()) << ']'
613 << " x[" << cmd.x << ']'
614 << " y[" << cmd.y << ']'
615 << " button[" << cmd.button() << ']'
618 Cursor & cur = cursor_;
619 // Default Update flags.
620 Update::flags updateFlags = Update::Force | Update::FitCursor;
622 switch (cmd.action) {
625 cur.message(_("Undo"));
626 cur.clearSelection();
627 if (!textUndo(*this)) {
628 cur.message(_("No further undo information"));
629 updateFlags = Update::None;
634 cur.message(_("Redo"));
635 cur.clearSelection();
636 if (!textRedo(*this)) {
637 cur.message(_("No further redo information"));
638 updateFlags = Update::None;
642 case LFUN_FILE_INSERT:
644 menuInsertLyXFile(to_utf8(cmd.argument()));
647 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
649 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
652 case LFUN_FILE_INSERT_PLAINTEXT:
654 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
657 case LFUN_FONT_STATE:
658 cur.message(cur.currentState());
661 case LFUN_BOOKMARK_SAVE:
662 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
665 case LFUN_LABEL_GOTO: {
666 docstring label = cmd.argument();
669 getInsetByCode<InsetRef>(cursor_,
672 label = inset->getParam("reference");
673 // persistent=false: use temp_bookmark
683 case LFUN_PARAGRAPH_GOTO: {
684 int const id = convert<int>(to_utf8(cmd.argument()));
686 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
687 b = theBufferList().next(b)) {
689 ParIterator par = b->getParFromID(id);
690 if (par == b->par_iterator_end()) {
692 << "No matching paragraph found! ["
693 << id << "]." << endl;
696 << "Paragraph " << par->id()
697 << " found in buffer `"
698 << b->fileName() << "'." << endl;
702 setCursor(makeDocIterator(par, 0));
704 // Switch to other buffer view and resend cmd
705 theLyXFunc().dispatch(FuncRequest(
706 LFUN_BUFFER_SWITCH, b->fileName()));
707 theLyXFunc().dispatch(cmd);
708 updateFlags = Update::None;
717 case LFUN_OUTLINE_UP:
718 toc::outline(toc::Up, cursor_);
719 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
720 updateLabels(buffer_);
722 case LFUN_OUTLINE_DOWN:
723 toc::outline(toc::Down, cursor_);
724 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
725 updateLabels(buffer_);
727 case LFUN_OUTLINE_IN:
728 toc::outline(toc::In, cursor_);
729 updateLabels(buffer_);
731 case LFUN_OUTLINE_OUT:
732 toc::outline(toc::Out, cursor_);
733 updateLabels(buffer_);
737 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
740 case LFUN_REFERENCE_NEXT: {
741 vector<Inset_code> tmp;
742 tmp.push_back(Inset::LABEL_CODE);
743 tmp.push_back(Inset::REF_CODE);
744 bv_funcs::gotoInset(this, tmp, true);
748 case LFUN_CHANGES_TRACK:
749 buffer_.params().trackChanges = !buffer_.params().trackChanges;
752 case LFUN_CHANGES_OUTPUT:
753 buffer_.params().outputChanges = !buffer_.params().outputChanges;
754 if (buffer_.params().outputChanges) {
755 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
756 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
757 LaTeXFeatures::isAvailable("xcolor");
759 if (!dvipost && !xcolorsoul) {
760 Alert::warning(_("Changes not shown in LaTeX output"),
761 _("Changes will not be highlighted in LaTeX output, "
762 "because neither dvipost nor xcolor/soul are installed.\n"
763 "Please install these packages or redefine "
764 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
765 } else if (!xcolorsoul) {
766 Alert::warning(_("Changes not shown in LaTeX output"),
767 _("Changes will not be highlighted in LaTeX output "
768 "when using pdflatex, because xcolor and soul are not installed.\n"
769 "Please install both packages or redefine "
770 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
775 case LFUN_CHANGE_NEXT:
776 findNextChange(this);
779 case LFUN_CHANGES_MERGE:
780 if (findNextChange(this))
781 showDialog("changes");
784 case LFUN_ALL_CHANGES_ACCEPT:
785 // select complete document
786 cursor_.reset(buffer_.inset());
787 cursor_.selHandle(true);
788 buffer_.text().cursorBottom(cursor_);
789 // accept everything in a single step to support atomic undo
790 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
793 case LFUN_ALL_CHANGES_REJECT:
794 // select complete document
795 cursor_.reset(buffer_.inset());
796 cursor_.selHandle(true);
797 buffer_.text().cursorBottom(cursor_);
798 // reject everything in a single step to support atomic undo
799 // Note: reject does not work recursively; the user may have to repeat the operation
800 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
807 case LFUN_WORD_REPLACE: {
808 bool has_deleted = false;
809 if (cur.selection()) {
810 DocIterator beg = cur.selectionBegin();
811 DocIterator end = cur.selectionEnd();
812 if (beg.pit() == end.pit()) {
813 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
814 if (cur.paragraph().isDeleted(p))
819 replace(this, cmd, has_deleted);
824 cur.clearSelection();
826 cur.message(from_utf8(N_("Mark off")));
830 cur.clearSelection();
833 cur.message(from_utf8(N_("Mark on")));
836 case LFUN_MARK_TOGGLE:
837 cur.clearSelection();
840 cur.message(from_utf8(N_("Mark removed")));
843 cur.message(from_utf8(N_("Mark set")));
848 case LFUN_SCREEN_RECENTER:
852 case LFUN_BIBTEX_DATABASE_ADD: {
853 Cursor tmpcur = cursor_;
854 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
855 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
858 if (inset->addDatabase(to_utf8(cmd.argument())))
859 buffer_.updateBibfilesCache();
864 case LFUN_BIBTEX_DATABASE_DEL: {
865 Cursor tmpcur = cursor_;
866 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
867 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
870 if (inset->delDatabase(to_utf8(cmd.argument())))
871 buffer_.updateBibfilesCache();
876 case LFUN_WORDS_COUNT: {
877 DocIterator from, to;
878 if (cur.selection()) {
879 from = cur.selectionBegin();
880 to = cur.selectionEnd();
882 from = doc_iterator_begin(buffer_.inset());
883 to = doc_iterator_end(buffer_.inset());
885 int const count = countWords(from, to);
889 message = bformat(_("%1$d words in selection."),
892 message = bformat(_("%1$d words in document."),
897 message = _("One word in selection.");
899 message = _("One word in document.");
902 Alert::information(_("Count words"), message);
906 case LFUN_BUFFER_TOGGLE_COMPRESSION:
907 // turn compression on/off
908 buffer_.params().compressed = !buffer_.params().compressed;
911 case LFUN_NEXT_INSET_TOGGLE: {
912 // this is the real function we want to invoke
913 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
914 // if there is an inset at cursor, see whether it
916 Inset * inset = cur.nextInset();
917 if (inset && inset->isActive()) {
919 tmpcur.pushLeft(*inset);
920 inset->dispatch(tmpcur, tmpcmd);
921 if (tmpcur.result().dispatched()) {
925 // if it did not work, try the underlying inset.
926 if (!cur.result().dispatched())
927 cur.dispatch(tmpcmd);
929 if (cur.result().dispatched())
930 cur.clearSelection();
936 updateFlags = Update::None;
943 docstring const BufferView::requestSelection()
945 Cursor & cur = cursor_;
947 if (!cur.selection()) {
948 xsel_cache_.set = false;
952 if (!xsel_cache_.set ||
953 cur.top() != xsel_cache_.cursor ||
954 cur.anchor_.top() != xsel_cache_.anchor)
956 xsel_cache_.cursor = cur.top();
957 xsel_cache_.anchor = cur.anchor_.top();
958 xsel_cache_.set = cur.selection();
959 return cur.selectionAsString(false);
965 void BufferView::clearSelection()
967 cursor_.clearSelection();
968 // Clear the selection buffer. Otherwise a subsequent
969 // middle-mouse-button paste would use the selection buffer,
970 // not the more current external selection.
971 cap::clearSelection();
972 xsel_cache_.set = false;
973 // The buffer did not really change, but this causes the
974 // redraw we need because we cleared the selection above.
979 void BufferView::resize(int width, int height)
981 // Update from work area
985 // The complete text metrics will be redone.
986 text_metrics_.clear();
987 updateMetrics(false);
991 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
993 pit_type pit = text.getPitNearY(*this, y);
994 BOOST_ASSERT(pit != -1);
995 Paragraph const & par = text.getPar(pit);
998 << BOOST_CURRENT_FUNCTION
1003 InsetList::const_iterator iit = par.insetlist.begin();
1004 InsetList::const_iterator iend = par.insetlist.end();
1005 for (; iit != iend; ++iit) {
1006 Inset * const inset = iit->inset;
1007 if (inset->covers(*this, x, y)) {
1008 if (!inset->descendable())
1009 // No need to go further down if the inset is not
1013 size_t cell_number = inset->nargs();
1014 // Check all the inner cell.
1015 for (size_t i = 0; i != cell_number; ++i) {
1016 Text const * inner_text = inset->getText(i);
1019 Inset const * inset_deeper =
1020 getCoveringInset(*inner_text, x, y);
1022 return inset_deeper;
1026 LYXERR(Debug::DEBUG)
1027 << BOOST_CURRENT_FUNCTION
1028 << ": Hit inset: " << inset << endl;
1032 LYXERR(Debug::DEBUG)
1033 << BOOST_CURRENT_FUNCTION
1034 << ": No inset hit. " << endl;
1039 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1041 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1043 // This is only called for mouse related events including
1044 // LFUN_FILE_OPEN generated by drag-and-drop.
1045 FuncRequest cmd = cmd0;
1048 cur.push(buffer_.inset());
1049 cur.selection() = cursor_.selection();
1051 // Either the inset under the cursor or the
1052 // surrounding Text will handle this event.
1054 // make sure we stay within the screen...
1055 cmd.y = min(max(cmd.y, -1), height_);
1057 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1059 // Get inset under mouse, if there is one.
1060 Inset const * covering_inset =
1061 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1062 if (covering_inset == last_inset_)
1063 // Same inset, no need to do anything...
1066 bool need_redraw = false;
1067 // const_cast because of setMouseHover().
1068 Inset * inset = const_cast<Inset *>(covering_inset);
1070 // Remove the hint on the last hovered inset (if any).
1071 need_redraw |= last_inset_->setMouseHover(false);
1073 // Highlighted the newly hovered inset (if any).
1074 need_redraw |= inset->setMouseHover(true);
1075 last_inset_ = inset;
1077 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1078 // not expose the button for redraw. We adjust here the metrics dimension
1079 // to enable a full redraw.
1080 // FIXME: It is possible to redraw only the area around the button!
1082 && metrics_info_.update_strategy == SingleParUpdate) {
1083 // FIXME: It should be possible to redraw only the area around
1084 // the button by doing this:
1086 //metrics_info_.singlepar = false;
1087 //metrics_info_.y1 = ymin of button;
1088 //metrics_info_.y2 = ymax of button;
1090 // Unfortunately, BufferView::draw() does not distinguish
1091 // between background updates and text updates. So we use the hammer
1092 // solution for now. We could also avoid the updateMetrics() below
1093 // by using the first and last pit of the CoordCache. Have a look
1094 // at Text::getPitNearY() to see what I mean.
1096 //metrics_info_.pit1 = first pit of CoordCache;
1097 //metrics_info_.pit2 = last pit of CoordCache;
1098 //metrics_info_.singlepar = false;
1099 //metrics_info_.y1 = 0;
1100 //metrics_info_.y2 = height_;
1102 updateMetrics(false);
1105 // This event (moving without mouse click) is not passed further.
1106 // This should be changed if it is further utilized.
1110 // Build temporary cursor.
1111 Inset * inset = buffer_.text().editXY(cur, cmd.x, cmd.y);
1113 // Put anchor at the same position.
1116 // Try to dispatch to an non-editable inset near this position
1117 // via the temp cursor. If the inset wishes to change the real
1118 // cursor it has to do so explicitly by using
1119 // cur.bv().cursor() = cur; (or similar)
1121 inset->dispatch(cur, cmd);
1124 // Now dispatch to the temporary cursor. If the real cursor should
1125 // be modified, the inset's dispatch has to do so explicitly.
1126 if (!cur.result().dispatched())
1129 //Do we have a selection?
1130 theSelection().haveSelection(cursor().selection());
1132 // Redraw if requested and necessary.
1133 if (cur.result().dispatched() && cur.result().update())
1134 return update(cur.result().update());
1140 void BufferView::scroll(int /*lines*/)
1142 // Text const * t = buffer_.text();
1143 // int const line_height = defaultRowHeight();
1145 // // The new absolute coordinate
1146 // int new_top_y = top_y() + lines * line_height;
1148 // // Restrict to a valid value
1149 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1150 // new_top_y = std::max(0, new_top_y);
1152 // scrollDocView(new_top_y);
1157 void BufferView::setCursorFromRow(int row)
1162 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1164 cursor_.reset(buffer_.inset());
1166 buffer_.text().setCursor(cursor_, 0, 0);
1168 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1172 void BufferView::gotoLabel(docstring const & label)
1174 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1175 vector<docstring> labels;
1176 it->getLabelList(buffer_, labels);
1177 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1186 TextMetrics const & BufferView::textMetrics(Text const * t) const
1188 return const_cast<BufferView *>(this)->textMetrics(t);
1192 TextMetrics & BufferView::textMetrics(Text const * t)
1194 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1195 if (tmc_it == text_metrics_.end()) {
1196 tmc_it = text_metrics_.insert(
1197 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1199 return tmc_it->second;
1203 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1206 return textMetrics(t).parMetrics(pit);
1210 int BufferView::workHeight() const
1216 void BufferView::setCursor(DocIterator const & dit)
1218 size_t const n = dit.depth();
1219 for (size_t i = 0; i < n; ++i)
1220 dit[i].inset().edit(cursor_, true);
1222 cursor_.setCursor(dit);
1223 cursor_.selection() = false;
1227 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1229 // Would be wrong to delete anything if we have a selection.
1230 if (cur.selection())
1233 bool need_anchor_change = false;
1234 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1235 need_anchor_change);
1237 if (need_anchor_change)
1243 updateLabels(buffer_);
1245 updateMetrics(false);
1251 bool BufferView::mouseSetCursor(Cursor & cur)
1253 BOOST_ASSERT(&cur.bv() == this);
1255 // this event will clear selection so we save selection for
1256 // persistent selection
1257 cap::saveSelection(cursor());
1259 // Has the cursor just left the inset?
1260 bool badcursor = false;
1261 bool leftinset = (&cursor_.inset() != &cur.inset());
1263 badcursor = notifyCursorLeaves(cursor_, cur);
1265 // do the dEPM magic if needed
1266 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1267 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1268 // the leftinset bool would not be necessary (badcursor instead).
1269 bool update = leftinset;
1270 if (!badcursor && cursor_.inTexted())
1271 update |= checkDepm(cur, cursor_);
1273 // if the cursor was in an empty script inset and the new
1274 // position is in the nucleus of the inset, notifyCursorLeaves
1275 // will kill the script inset itself. So we check all the
1276 // elements of the cursor to make sure that they are correct.
1277 // For an example, see bug 2933:
1278 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1279 // The code below could maybe be moved to a DocIterator method.
1280 //lyxerr << "cur before " << cur <<std::endl;
1281 DocIterator dit(cur.inset());
1282 dit.push_back(cur.bottom());
1284 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1285 dit.push_back(cur[i]);
1288 //lyxerr << "5 cur after" << dit <<std::endl;
1290 cursor_.setCursor(dit);
1291 cursor_.boundary(cur.boundary());
1292 cursor_.clearSelection();
1298 void BufferView::putSelectionAt(DocIterator const & cur,
1299 int length, bool backwards)
1301 cursor_.clearSelection();
1307 cursor_.pos() += length;
1308 cursor_.setSelection(cursor_, -length);
1310 cursor_.setSelection(cursor_, length);
1315 Cursor & BufferView::cursor()
1321 Cursor const & BufferView::cursor() const
1327 pit_type BufferView::anchor_ref() const
1333 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1335 return metrics_info_;
1339 // FIXME: We should split-up updateMetrics() for the singlepar case.
1340 void BufferView::updateMetrics(bool singlepar)
1342 Text & buftext = buffer_.text();
1343 TextMetrics & tm = textMetrics(&buftext);
1344 pit_type size = int(buftext.paragraphs().size());
1346 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1347 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1352 // Clear out the position cache in case of full screen redraw,
1353 coord_cache_.clear();
1355 // Clear out paragraph metrics to avoid having invalid metrics
1356 // in the cache from paragraphs not relayouted below
1360 // If the paragraph metrics has changed, we can not
1361 // use the singlepar optimisation.
1363 // In Single Paragraph mode, rebreak only
1364 // the (main text, not inset!) paragraph containing the cursor.
1365 // (if this paragraph contains insets etc., rebreaking will
1366 // recursively descend)
1367 && tm.redoParagraph(cursor_.bottom().pit()))
1370 pit_type const pit = anchor_ref_;
1373 size_t const npit = buftext.paragraphs().size();
1375 // Rebreak anchor paragraph.
1377 tm.redoParagraph(pit);
1381 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1383 // Redo paragraphs above anchor if necessary.
1385 while (y1 > 0 && pit1 > 0) {
1386 y1 -= tm.parMetrics(pit1).ascent();
1389 tm.redoParagraph(pit1);
1390 y1 -= tm.parMetrics(pit1).descent();
1394 // Take care of ascent of first line
1395 y1 -= tm.parMetrics(pit1).ascent();
1397 // Normalize anchor for next time
1401 // Grey at the beginning is ugly
1402 if (pit1 == 0 && y1 > 0) {
1408 // Redo paragraphs below the anchor if necessary.
1410 while (y2 < height_ && pit2 < int(npit) - 1) {
1411 y2 += tm.parMetrics(pit2).descent();
1414 tm.redoParagraph(pit2);
1415 y2 += tm.parMetrics(pit2).ascent();
1418 // Take care of descent of last line
1419 y2 += tm.parMetrics(pit2).descent();
1421 // The coordinates of all these paragraphs are correct, cache them
1423 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1424 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1425 ParagraphMetrics const & pm = tm.parMetrics(pit);
1427 parPos[pit] = Point(0, y);
1428 if (singlepar && pit == cursor_.bottom().pit()) {
1429 // In Single Paragraph mode, collect here the
1430 // y1 and y2 of the (one) paragraph the cursor is in
1431 y1 = y - pm.ascent();
1432 y2 = y + pm.descent();
1438 // collect cursor paragraph iter bounds
1439 pit1 = cursor_.bottom().pit();
1440 pit2 = cursor_.bottom().pit();
1443 LYXERR(Debug::DEBUG)
1444 << BOOST_CURRENT_FUNCTION
1447 << " pit1: " << pit1
1448 << " pit2: " << pit2
1449 << " npit: " << npit
1450 << " singlepar: " << singlepar
1454 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1455 singlepar? SingleParUpdate: FullScreenUpdate, size);
1457 if (lyxerr.debugging(Debug::WORKAREA)) {
1458 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1459 coord_cache_.dump();
1464 void BufferView::menuInsertLyXFile(string const & filenm)
1466 BOOST_ASSERT(cursor_.inTexted());
1467 string filename = filenm;
1469 if (filename.empty()) {
1470 // Launch a file browser
1472 string initpath = lyxrc.document_path;
1473 string const trypath = buffer_.filePath();
1474 // If directory is writeable, use this as default.
1475 if (isDirWriteable(FileName(trypath)))
1479 FileDialog fileDlg(_("Select LyX document to insert"),
1481 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1482 make_pair(_("Examples|#E#e"),
1483 from_utf8(addPath(package().system_support().absFilename(),
1486 FileDialog::Result result =
1487 fileDlg.open(from_utf8(initpath),
1488 FileFilterList(_("LyX Documents (*.lyx)")),
1491 if (result.first == FileDialog::Later)
1495 filename = to_utf8(result.second);
1497 // check selected filename
1498 if (filename.empty()) {
1499 // emit message signal.
1500 message(_("Canceled."));
1505 // Get absolute path of file and add ".lyx"
1506 // to the filename if necessary
1507 filename = fileSearch(string(), filename, "lyx").absFilename();
1509 docstring const disp_fn = makeDisplayPath(filename);
1510 // emit message signal.
1511 message(bformat(_("Inserting document %1$s..."), disp_fn));
1514 Buffer buf("", false);
1515 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1516 ErrorList & el = buffer_.errorList("Parse");
1517 // Copy the inserted document error list into the current buffer one.
1518 el = buf.errorList("Parse");
1519 recordUndo(cursor_);
1520 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1521 buf.params().getTextClass_ptr(), el);
1522 res = _("Document %1$s inserted.");
1524 res = _("Could not insert document %1$s");
1526 // emit message signal.
1527 message(bformat(res, disp_fn));
1528 buffer_.errors("Parse");
1529 updateMetrics(false);
1533 void BufferView::draw(frontend::Painter & pain)
1535 Text & text = buffer_.text();
1536 bool const select = cursor_.selection();
1538 PainterInfo pi(this, pain);
1539 // Should the whole screen, including insets, be refreshed?
1540 // FIXME: We should also distinguish DecorationUpdate to avoid text
1541 // drawing if possible. This is not possible to do easily right now
1542 // because of the single backing pixmap.
1543 bool repaintAll = select
1544 || metrics_info_.update_strategy != SingleParUpdate;
1547 // Clear background (if not delegated to rows)
1548 pain.fillRectangle(0, metrics_info_.y1, width_,
1549 metrics_info_.y2 - metrics_info_.y1, text.backgroundColor());
1552 text.drawSelection(pi, 0, 0);
1554 int yy = metrics_info_.y1;
1556 for (pit_type pit = metrics_info_.p1; pit <= metrics_info_.p2; ++pit) {
1557 ParagraphMetrics const & pm = parMetrics(&text, pit);
1559 paintPar(pi, text, pit, 0, yy, repaintAll);
1563 // and grey out above (should not happen later)
1564 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1565 if (metrics_info_.y1 > 0
1566 && metrics_info_.update_strategy == FullScreenUpdate)
1567 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1569 // and possibly grey out below
1570 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1571 if (metrics_info_.y2 < height_
1572 && metrics_info_.update_strategy == FullScreenUpdate)
1573 pain.fillRectangle(0, metrics_info_.y2, width_,
1574 height_ - metrics_info_.y2, Color::bottomarea);