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 "CoordCache.h"
25 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // update bookmark pit of the current buffer before switch
158 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160 if (buffer()->fileName() != bm.filename.absFilename())
162 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
167 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
171 // current buffer is going to be switched-off, save cursor pos
172 // Ideally, the whole cursor stack should be saved, but session
173 // currently can only handle bottom (whole document) level pit and pos.
174 // That is to say, if a cursor is in a nested inset, it will be
175 // restore to the left of the top level inset.
176 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180 // If we're quitting lyx, don't bother updating stuff
186 //FIXME Fix for bug 3440 is here.
187 // If we are closing current buffer, switch to the first in
190 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191 << " No Buffer!" << endl;
192 // We are closing the buffer, use the first buffer as current
194 // if (last_buffer_) buffer_ = last_buffer_;
195 // also check that this is in theBufferList()?
196 buffer_ = theBufferList().first();
199 // last_buffer = buffer_;
200 // Set current buffer
205 cursor_ = Cursor(*this);
212 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().setCurrentFont(cursor_);
217 if (buffer_->getCursor().size() > 0 &&
218 buffer_->getAnchor().size() > 0)
220 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221 cursor_.resetAnchor();
222 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223 cursor_.setSelection();
224 // do not set selection to the new buffer because we
225 // only paste recent selection.
227 // Make sure that the restored cursor is not broken. This can happen for
228 // example if this Buffer has been modified by another view.
229 cursor_.fixIfBroken();
231 updateMetrics(false);
232 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233 graphics::Previews::get().generateBufferPreviews(*buffer_);
236 void BufferView::resize()
241 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
243 updateMetrics(false);
247 bool BufferView::fitCursor()
249 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
250 frontend::FontMetrics const & fm =
251 theFontMetrics(cursor_.getFont());
252 int const asc = fm.maxAscent();
253 int const des = fm.maxDescent();
254 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
255 if (p.y_ - asc >= 0 && p.y_ + des < height_)
263 bool BufferView::multiParSel()
265 if (!cursor_.selection())
267 bool ret = multiparsel_cache_;
268 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
269 // Either this, or previous selection spans paragraphs
270 return ret || multiparsel_cache_;
274 bool BufferView::update(Update::flags flags)
276 // last_inset_ points to the last visited inset. This pointer may become
277 // invalid because of keyboard editing. Since all such operations
278 // causes screen update(), I reset last_inset_ to avoid such a problem.
280 // This is close to a hot-path.
282 << BOOST_CURRENT_FUNCTION
283 << "[fitcursor = " << (flags & Update::FitCursor)
284 << ", forceupdate = " << (flags & Update::Force)
285 << ", singlepar = " << (flags & Update::SinglePar)
286 << "] buffer: " << buffer_ << endl;
288 // Check needed to survive LyX startup
292 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
294 // Update macro store
295 if (!(cursor().inMathed() && cursor().inMacroMode()))
296 buffer_->buildMacros();
298 // Now do the first drawing step if needed. This consists on updating
299 // the CoordCache in updateMetrics().
300 // The second drawing step is done in WorkArea::redraw() if needed.
302 // Case when no explicit update is requested.
304 // no need to redraw anything.
305 metrics_info_.update_strategy = NoScreenUpdate;
309 if (flags == Update::Decoration) {
310 metrics_info_.update_strategy = DecorationUpdate;
314 if (flags == Update::FitCursor
315 || flags == (Update::Decoration | Update::FitCursor)) {
316 bool const fit_cursor = fitCursor();
317 // tell the frontend to update the screen if needed.
319 updateMetrics(false);
322 if (flags & Update::Decoration) {
323 metrics_info_.update_strategy = DecorationUpdate;
326 // no screen update is needed.
327 metrics_info_.update_strategy = NoScreenUpdate;
331 bool full_metrics = flags & Update::Force;
332 if (flags & Update::MultiParSel)
333 full_metrics |= multiParSel();
335 bool const single_par = !full_metrics;
336 updateMetrics(single_par);
338 if (flags & Update::FitCursor && fitCursor())
339 updateMetrics(false);
341 // tell the frontend to update the screen.
346 void BufferView::updateScrollbar()
349 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
350 << " no text in updateScrollbar" << endl;
351 scrollbarParameters_.reset();
355 Text & t = buffer_->text();
356 TextMetrics & tm = text_metrics_[&t];
358 int const parsize = int(t.paragraphs().size() - 1);
359 if (anchor_ref_ > parsize) {
360 anchor_ref_ = parsize;
365 << BOOST_CURRENT_FUNCTION
366 << " Updating scrollbar: height: " << t.paragraphs().size()
367 << " curr par: " << cursor_.bottom().pit()
368 << " default height " << defaultRowHeight() << endl;
370 // It would be better to fix the scrollbar to understand
371 // values in [0..1] and divide everything by wh
373 // estimated average paragraph height:
377 int h = tm.parMetrics(anchor_ref_).height();
379 // Normalize anchor/offset (MV):
380 while (offset_ref_ > h && anchor_ref_ < parsize) {
383 h = tm.parMetrics(anchor_ref_).height();
385 // Look at paragraph heights on-screen
388 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
391 int const h2 = tm.parMetrics(pit).height();
397 int const hav = sumh / nh;
398 // More realistic average paragraph height
403 scrollbarParameters_.height = (parsize + 1) * wh_;
404 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
405 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
409 ScrollbarParameters const & BufferView::scrollbarParameters() const
411 return scrollbarParameters_;
415 void BufferView::scrollDocView(int value)
417 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
418 << "[ value = " << value << "]" << endl;
423 Text & t = buffer_->text();
424 TextMetrics & tm = text_metrics_[&t];
426 float const bar = value / float(wh_ * t.paragraphs().size());
428 anchor_ref_ = int(bar * t.paragraphs().size());
429 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
430 anchor_ref_ = int(t.paragraphs().size()) - 1;
432 tm.redoParagraph(anchor_ref_);
433 int const h = tm.parMetrics(anchor_ref_).height();
434 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
435 updateMetrics(false);
439 void BufferView::setCursorFromScrollbar()
444 Text & t = buffer_->text();
446 int const height = 2 * defaultRowHeight();
447 int const first = height;
448 int const last = height_ - height;
449 Cursor & cur = cursor_;
451 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
454 case bv_funcs::CUR_ABOVE:
455 // We reset the cursor because bv_funcs::status() does not
456 // work when the cursor is within mathed.
457 cur.reset(buffer_->inset());
458 t.setCursorFromCoordinates(cur, 0, first);
459 cur.clearSelection();
461 case bv_funcs::CUR_BELOW:
462 // We reset the cursor because bv_funcs::status() does not
463 // work when the cursor is within mathed.
464 cur.reset(buffer_->inset());
465 t.setCursorFromCoordinates(cur, 0, last);
466 cur.clearSelection();
468 case bv_funcs::CUR_INSIDE:
469 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
470 int const newy = min(last, max(y, first));
472 cur.reset(buffer_->inset());
473 t.setCursorFromCoordinates(cur, 0, newy);
479 Change const BufferView::getCurrentChange() const
481 if (!cursor_.selection())
482 return Change(Change::UNCHANGED);
484 DocIterator dit = cursor_.selectionBegin();
485 return dit.paragraph().lookupChange(dit.pos());
489 void BufferView::saveBookmark(unsigned int idx)
491 // tenatively save bookmark, id and pos will be used to
492 // acturately locate a bookmark in a 'live' lyx session.
493 // pit and pos will be updated with bottom level pit/pos
495 LyX::ref().session().bookmarks().save(
496 FileName(buffer_->fileName()),
497 cursor_.bottom().pit(),
498 cursor_.bottom().pos(),
499 cursor_.paragraph().id(),
504 // emit message signal.
505 message(_("Save bookmark"));
509 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
510 int top_id, pos_type top_pos)
512 cursor_.clearSelection();
514 // if a valid par_id is given, try it first
515 // This is the case for a 'live' bookmark when unique paragraph ID
516 // is used to track bookmarks.
518 ParIterator par = buffer_->getParFromID(top_id);
519 if (par != buffer_->par_iterator_end()) {
520 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
521 // Some slices of the iterator may not be
522 // reachable (e.g. closed collapsable inset)
523 // so the dociterator may need to be
524 // shortened. Otherwise, setCursor may crash
525 // lyx when the cursor can not be set to these
527 size_t const n = dit.depth();
528 for (size_t i = 0; i < n; ++i)
529 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
534 // Note: return bottom (document) level pit.
535 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
538 // if top_id == 0, or searching through top_id failed
539 // This is the case for a 'restored' bookmark when only bottom
540 // (document level) pit was saved. Because of this, bookmark
541 // restoration is inaccurate. If a bookmark was within an inset,
542 // it will be restored to the left of the outmost inset that contains
544 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
545 DocIterator it = doc_iterator_begin(buffer_->inset());
546 it.pit() = bottom_pit;
547 it.pos() = min(bottom_pos, it.paragraph().size());
549 return boost::make_tuple(it.pit(), it.pos(),
550 it.paragraph().id());
553 return boost::make_tuple(pit_type(0), pos_type(0), 0);
557 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
559 if (lyxrc.rtl_support) {
560 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
561 if (intl_->keymap == Intl::PRIMARY)
564 if (intl_->keymap == Intl::SECONDARY)
569 intl_->getTransManager().translateAndInsert(c, t, cur);
573 int BufferView::workWidth() const
579 void BufferView::center()
581 CursorSlice & bot = cursor_.bottom();
582 TextMetrics & tm = text_metrics_[bot.text()];
583 pit_type const pit = bot.pit();
584 tm.redoParagraph(pit);
585 ParagraphMetrics const & pm = tm.parMetrics(pit);
587 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
588 + pm.ascent() - height_ / 2;
592 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
596 Cursor & cur = cursor_;
598 switch (cmd.action) {
601 flag.enabled(!buffer_->undostack().empty());
604 flag.enabled(!buffer_->redostack().empty());
606 case LFUN_FILE_INSERT:
607 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
608 case LFUN_FILE_INSERT_PLAINTEXT:
609 case LFUN_BOOKMARK_SAVE:
610 // FIXME: Actually, these LFUNS should be moved to Text
611 flag.enabled(cur.inTexted());
613 case LFUN_FONT_STATE:
614 case LFUN_LABEL_INSERT:
615 case LFUN_PARAGRAPH_GOTO:
616 // FIXME handle non-trivially
617 case LFUN_OUTLINE_UP:
618 case LFUN_OUTLINE_DOWN:
619 case LFUN_OUTLINE_IN:
620 case LFUN_OUTLINE_OUT:
622 case LFUN_REFERENCE_NEXT:
626 case LFUN_MARK_TOGGLE:
627 case LFUN_SCREEN_RECENTER:
628 case LFUN_BIBTEX_DATABASE_ADD:
629 case LFUN_BIBTEX_DATABASE_DEL:
630 case LFUN_WORDS_COUNT:
631 case LFUN_NEXT_INSET_TOGGLE:
635 case LFUN_WORD_REPLACE:
636 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
639 case LFUN_LABEL_GOTO: {
640 flag.enabled(!cmd.argument().empty()
641 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
645 case LFUN_CHANGES_TRACK:
647 flag.setOnOff(buffer_->params().trackChanges);
650 case LFUN_CHANGES_OUTPUT:
651 flag.enabled(buffer_);
652 flag.setOnOff(buffer_->params().outputChanges);
655 case LFUN_CHANGES_MERGE:
656 case LFUN_CHANGE_NEXT:
657 case LFUN_ALL_CHANGES_ACCEPT:
658 case LFUN_ALL_CHANGES_REJECT:
659 // TODO: context-sensitive enabling of LFUNs
660 // In principle, these command should only be enabled if there
661 // is a change in the document. However, without proper
662 // optimizations, this will inevitably result in poor performance.
663 flag.enabled(buffer_);
666 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
667 flag.setOnOff(buffer_->params().compressed);
679 Update::flags BufferView::dispatch(FuncRequest const & cmd)
681 //lyxerr << BOOST_CURRENT_FUNCTION
682 // << [ cmd = " << cmd << "]" << endl;
684 // Make sure that the cached BufferView is correct.
685 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
686 << " action[" << cmd.action << ']'
687 << " arg[" << to_utf8(cmd.argument()) << ']'
688 << " x[" << cmd.x << ']'
689 << " y[" << cmd.y << ']'
690 << " button[" << cmd.button() << ']'
693 // FIXME: this should not be possible.
697 Cursor & cur = cursor_;
698 // Default Update flags.
699 Update::flags updateFlags = Update::Force | Update::FitCursor;
701 switch (cmd.action) {
704 cur.message(_("Undo"));
705 cur.clearSelection();
706 if (!textUndo(*this)) {
707 cur.message(_("No further undo information"));
708 updateFlags = Update::None;
713 cur.message(_("Redo"));
714 cur.clearSelection();
715 if (!textRedo(*this)) {
716 cur.message(_("No further redo information"));
717 updateFlags = Update::None;
721 case LFUN_FILE_INSERT:
723 menuInsertLyXFile(to_utf8(cmd.argument()));
726 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
728 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
731 case LFUN_FILE_INSERT_PLAINTEXT:
733 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
736 case LFUN_FONT_STATE:
737 cur.message(cur.currentState());
740 case LFUN_BOOKMARK_SAVE:
741 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
744 case LFUN_LABEL_GOTO: {
745 docstring label = cmd.argument();
748 getInsetByCode<InsetRef>(cursor_,
751 label = inset->getParam("reference");
752 // persistent=false: use temp_bookmark
762 case LFUN_PARAGRAPH_GOTO: {
763 int const id = convert<int>(to_utf8(cmd.argument()));
765 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
766 ParIterator par = b->getParFromID(id);
767 if (par == b->par_iterator_end()) {
769 << "No matching paragraph found! ["
770 << id << "]." << endl;
773 << "Paragraph " << par->id()
774 << " found in buffer `"
775 << b->fileName() << "'." << endl;
779 setCursor(makeDocIterator(par, 0));
781 // Switch to other buffer view and resend cmd
782 theLyXFunc().dispatch(FuncRequest(
783 LFUN_BUFFER_SWITCH, b->fileName()));
784 theLyXFunc().dispatch(cmd);
785 updateFlags = Update::None;
794 case LFUN_OUTLINE_UP:
795 toc::outline(toc::Up, cursor_);
796 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
797 updateLabels(*buffer_);
799 case LFUN_OUTLINE_DOWN:
800 toc::outline(toc::Down, cursor_);
801 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
802 updateLabels(*buffer_);
804 case LFUN_OUTLINE_IN:
805 toc::outline(toc::In, cursor_);
806 updateLabels(*buffer_);
808 case LFUN_OUTLINE_OUT:
809 toc::outline(toc::Out, cursor_);
810 updateLabels(*buffer_);
814 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
817 case LFUN_REFERENCE_NEXT: {
818 vector<Inset_code> tmp;
819 tmp.push_back(Inset::LABEL_CODE);
820 tmp.push_back(Inset::REF_CODE);
821 bv_funcs::gotoInset(this, tmp, true);
825 case LFUN_CHANGES_TRACK:
826 buffer_->params().trackChanges = !buffer_->params().trackChanges;
829 case LFUN_CHANGES_OUTPUT:
830 buffer_->params().outputChanges = !buffer_->params().outputChanges;
831 if (buffer_->params().outputChanges) {
832 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
833 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
834 LaTeXFeatures::isAvailable("xcolor");
836 if (!dvipost && !xcolorsoul) {
837 Alert::warning(_("Changes not shown in LaTeX output"),
838 _("Changes will not be highlighted in LaTeX output, "
839 "because neither dvipost nor xcolor/soul are installed.\n"
840 "Please install these packages or redefine "
841 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
842 } else if (!xcolorsoul) {
843 Alert::warning(_("Changes not shown in LaTeX output"),
844 _("Changes will not be highlighted in LaTeX output "
845 "when using pdflatex, because xcolor and soul are not installed.\n"
846 "Please install both packages or redefine "
847 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
852 case LFUN_CHANGE_NEXT:
853 findNextChange(this);
856 case LFUN_CHANGES_MERGE:
857 if (findNextChange(this))
858 showDialog("changes");
861 case LFUN_ALL_CHANGES_ACCEPT:
862 // select complete document
863 cursor_.reset(buffer_->inset());
864 cursor_.selHandle(true);
865 buffer_->text().cursorBottom(cursor_);
866 // accept everything in a single step to support atomic undo
867 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
870 case LFUN_ALL_CHANGES_REJECT:
871 // select complete document
872 cursor_.reset(buffer_->inset());
873 cursor_.selHandle(true);
874 buffer_->text().cursorBottom(cursor_);
875 // reject everything in a single step to support atomic undo
876 // Note: reject does not work recursively; the user may have to repeat the operation
877 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
884 case LFUN_WORD_REPLACE:
889 cur.clearSelection();
891 cur.message(from_utf8(N_("Mark off")));
895 cur.clearSelection();
898 cur.message(from_utf8(N_("Mark on")));
901 case LFUN_MARK_TOGGLE:
902 cur.clearSelection();
905 cur.message(from_utf8(N_("Mark removed")));
908 cur.message(from_utf8(N_("Mark set")));
913 case LFUN_SCREEN_RECENTER:
917 case LFUN_BIBTEX_DATABASE_ADD: {
918 Cursor tmpcur = cursor_;
919 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
920 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
923 if (inset->addDatabase(to_utf8(cmd.argument())))
924 buffer_->updateBibfilesCache();
929 case LFUN_BIBTEX_DATABASE_DEL: {
930 Cursor tmpcur = cursor_;
931 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
932 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
935 if (inset->delDatabase(to_utf8(cmd.argument())))
936 buffer_->updateBibfilesCache();
941 case LFUN_WORDS_COUNT: {
942 DocIterator from, to;
943 if (cur.selection()) {
944 from = cur.selectionBegin();
945 to = cur.selectionEnd();
947 from = doc_iterator_begin(buffer_->inset());
948 to = doc_iterator_end(buffer_->inset());
950 int const count = countWords(from, to);
954 message = bformat(_("%1$d words in selection."),
957 message = bformat(_("%1$d words in document."),
962 message = _("One word in selection.");
964 message = _("One word in document.");
967 Alert::information(_("Count words"), message);
971 case LFUN_BUFFER_TOGGLE_COMPRESSION:
972 // turn compression on/off
973 buffer_->params().compressed = !buffer_->params().compressed;
976 case LFUN_NEXT_INSET_TOGGLE: {
977 // this is the real function we want to invoke
978 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
979 // if there is an inset at cursor, see whether it
981 Inset * inset = cur.nextInset();
982 if (inset && inset->isActive()) {
984 tmpcur.pushLeft(*inset);
985 inset->dispatch(tmpcur, tmpcmd);
986 if (tmpcur.result().dispatched()) {
990 // if it did not work, try the underlying inset.
991 if (!cur.result().dispatched())
992 cur.dispatch(tmpcmd);
994 if (cur.result().dispatched())
995 cur.clearSelection();
1001 updateFlags = Update::None;
1008 docstring const BufferView::requestSelection()
1013 Cursor & cur = cursor_;
1015 if (!cur.selection()) {
1016 xsel_cache_.set = false;
1020 if (!xsel_cache_.set ||
1021 cur.top() != xsel_cache_.cursor ||
1022 cur.anchor_.top() != xsel_cache_.anchor)
1024 xsel_cache_.cursor = cur.top();
1025 xsel_cache_.anchor = cur.anchor_.top();
1026 xsel_cache_.set = cur.selection();
1027 return cur.selectionAsString(false);
1033 void BufferView::clearSelection()
1036 cursor_.clearSelection();
1037 // Clear the selection buffer. Otherwise a subsequent
1038 // middle-mouse-button paste would use the selection buffer,
1039 // not the more current external selection.
1040 cap::clearSelection();
1041 xsel_cache_.set = false;
1042 // The buffer did not really change, but this causes the
1043 // redraw we need because we cleared the selection above.
1049 void BufferView::workAreaResize(int width, int height)
1051 // Update from work area
1055 // The complete text metrics will be redone.
1056 text_metrics_.clear();
1063 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1065 pit_type pit = text.getPitNearY(*this, y);
1066 BOOST_ASSERT(pit != -1);
1067 Paragraph const & par = text.getPar(pit);
1069 LYXERR(Debug::DEBUG)
1070 << BOOST_CURRENT_FUNCTION
1075 InsetList::const_iterator iit = par.insetlist.begin();
1076 InsetList::const_iterator iend = par.insetlist.end();
1077 for (; iit != iend; ++iit) {
1078 Inset * const inset = iit->inset;
1079 if (inset->covers(*this, x, y)) {
1080 if (!inset->descendable())
1081 // No need to go further down if the inset is not
1085 size_t cell_number = inset->nargs();
1086 // Check all the inner cell.
1087 for (size_t i = 0; i != cell_number; ++i) {
1088 Text const * inner_text = inset->getText(i);
1091 Inset const * inset_deeper =
1092 getCoveringInset(*inner_text, x, y);
1094 return inset_deeper;
1098 LYXERR(Debug::DEBUG)
1099 << BOOST_CURRENT_FUNCTION
1100 << ": Hit inset: " << inset << endl;
1104 LYXERR(Debug::DEBUG)
1105 << BOOST_CURRENT_FUNCTION
1106 << ": No inset hit. " << endl;
1111 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1113 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1115 // This is only called for mouse related events including
1116 // LFUN_FILE_OPEN generated by drag-and-drop.
1117 FuncRequest cmd = cmd0;
1119 // E.g. Qt mouse press when no buffer
1124 cur.push(buffer_->inset());
1125 cur.selection() = cursor_.selection();
1127 // Either the inset under the cursor or the
1128 // surrounding Text will handle this event.
1130 // make sure we stay within the screen...
1131 cmd.y = min(max(cmd.y, -1), height_);
1133 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1135 // Get inset under mouse, if there is one.
1136 Inset const * covering_inset =
1137 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1138 if (covering_inset == last_inset_)
1139 // Same inset, no need to do anything...
1142 bool need_redraw = false;
1143 // const_cast because of setMouseHover().
1144 Inset * inset = const_cast<Inset *>(covering_inset);
1146 // Remove the hint on the last hovered inset (if any).
1147 need_redraw |= last_inset_->setMouseHover(false);
1149 // Highlighted the newly hovered inset (if any).
1150 need_redraw |= inset->setMouseHover(true);
1151 last_inset_ = inset;
1153 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1154 // not expose the button for redraw. We adjust here the metrics dimension
1155 // to enable a full redraw.
1156 // FIXME: It is possible to redraw only the area around the button!
1158 && metrics_info_.update_strategy == SingleParUpdate) {
1159 // FIXME: It should be possible to redraw only the area around
1160 // the button by doing this:
1162 //metrics_info_.singlepar = false;
1163 //metrics_info_.y1 = ymin of button;
1164 //metrics_info_.y2 = ymax of button;
1166 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1167 // between background updates and text updates. So we use the hammer
1168 // solution for now. We could also avoid the updateMetrics() below
1169 // by using the first and last pit of the CoordCache. Have a look
1170 // at Text::getPitNearY() to see what I mean.
1172 //metrics_info_.pit1 = first pit of CoordCache;
1173 //metrics_info_.pit2 = last pit of CoordCache;
1174 //metrics_info_.singlepar = false;
1175 //metrics_info_.y1 = 0;
1176 //metrics_info_.y2 = height_;
1178 updateMetrics(false);
1181 // This event (moving without mouse click) is not passed further.
1182 // This should be changed if it is further utilized.
1186 // Build temporary cursor.
1187 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1189 // Put anchor at the same position.
1192 // Try to dispatch to an non-editable inset near this position
1193 // via the temp cursor. If the inset wishes to change the real
1194 // cursor it has to do so explicitly by using
1195 // cur.bv().cursor() = cur; (or similar)
1197 inset->dispatch(cur, cmd);
1200 // Now dispatch to the temporary cursor. If the real cursor should
1201 // be modified, the inset's dispatch has to do so explicitly.
1202 if (!cur.result().dispatched())
1205 // Redraw if requested and necessary.
1206 if (cur.result().dispatched() && cur.result().update())
1207 return update(cur.result().update());
1213 void BufferView::scroll(int /*lines*/)
1218 // Text const * t = &buffer_->text();
1219 // int const line_height = defaultRowHeight();
1221 // // The new absolute coordinate
1222 // int new_top_y = top_y() + lines * line_height;
1224 // // Restrict to a valid value
1225 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1226 // new_top_y = std::max(0, new_top_y);
1228 // scrollDocView(new_top_y);
1233 void BufferView::setCursorFromRow(int row)
1238 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1241 buffer_->text().setCursor(cursor_, 0, 0);
1243 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1247 void BufferView::gotoLabel(docstring const & label)
1249 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1250 vector<docstring> labels;
1251 it->getLabelList(*buffer_, labels);
1252 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1261 TextMetrics const & BufferView::textMetrics(Text const * t) const
1263 return const_cast<BufferView *>(this)->textMetrics(t);
1267 TextMetrics & BufferView::textMetrics(Text const * t)
1269 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1270 if (tmc_it == text_metrics_.end()) {
1271 tmc_it = text_metrics_.insert(
1272 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1274 return tmc_it->second;
1278 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1281 return textMetrics(t).parMetrics(pit);
1285 int BufferView::workHeight() const
1291 void BufferView::setCursor(DocIterator const & dit)
1293 size_t const n = dit.depth();
1294 for (size_t i = 0; i < n; ++i)
1295 dit[i].inset().edit(cursor_, true);
1297 cursor_.setCursor(dit);
1298 cursor_.selection() = false;
1302 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1304 // Would be wrong to delete anything if we have a selection.
1305 if (cur.selection())
1308 bool need_anchor_change = false;
1309 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1310 need_anchor_change);
1312 if (need_anchor_change)
1318 updateLabels(*buffer_);
1320 updateMetrics(false);
1326 bool BufferView::mouseSetCursor(Cursor & cur)
1328 BOOST_ASSERT(&cur.bv() == this);
1330 // Has the cursor just left the inset?
1331 bool badcursor = false;
1332 bool leftinset = (&cursor_.inset() != &cur.inset());
1334 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1336 // do the dEPM magic if needed
1337 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1338 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1339 // the leftinset bool would not be necessary (badcursor instead).
1340 bool update = leftinset;
1341 if (!badcursor && cursor_.inTexted())
1342 update |= checkDepm(cur, cursor_);
1344 // if the cursor was in an empty script inset and the new
1345 // position is in the nucleus of the inset, notifyCursorLeaves
1346 // will kill the script inset itself. So we check all the
1347 // elements of the cursor to make sure that they are correct.
1348 // For an example, see bug 2933:
1349 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1350 // The code below could maybe be moved to a DocIterator method.
1351 //lyxerr << "cur before " << cur <<std::endl;
1352 DocIterator dit(cur.inset());
1353 dit.push_back(cur.bottom());
1355 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1356 dit.push_back(cur[i]);
1359 //lyxerr << "5 cur after" << dit <<std::endl;
1361 cursor_.setCursor(dit);
1362 cursor_.boundary(cur.boundary());
1363 cursor_.clearSelection();
1369 void BufferView::putSelectionAt(DocIterator const & cur,
1370 int length, bool backwards)
1372 cursor_.clearSelection();
1378 cursor_.pos() += length;
1379 cursor_.setSelection(cursor_, -length);
1381 cursor_.setSelection(cursor_, length);
1382 cap::saveSelection(cursor_);
1387 Cursor & BufferView::cursor()
1393 Cursor const & BufferView::cursor() const
1399 pit_type BufferView::anchor_ref() const
1405 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1407 return metrics_info_;
1411 // FIXME: We should split-up updateMetrics() for the singlepar case.
1412 void BufferView::updateMetrics(bool singlepar)
1414 Text & buftext = buffer_->text();
1415 TextMetrics & tm = textMetrics(&buftext);
1416 pit_type size = int(buftext.paragraphs().size());
1418 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1419 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1423 // If the paragraph metrics has changed, we can not
1424 // use the singlepar optimisation.
1426 // In Single Paragraph mode, rebreak only
1427 // the (main text, not inset!) paragraph containing the cursor.
1428 // (if this paragraph contains insets etc., rebreaking will
1429 // recursively descend)
1430 && tm.redoParagraph(cursor_.bottom().pit()))
1433 pit_type const pit = anchor_ref_;
1436 size_t const npit = buftext.paragraphs().size();
1438 // Rebreak anchor paragraph.
1440 tm.redoParagraph(pit);
1442 // Clear out the position cache in case of full screen redraw.
1444 coord_cache_.clear();
1446 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1448 // Redo paragraphs above anchor if necessary.
1450 while (y1 > 0 && pit1 > 0) {
1451 y1 -= tm.parMetrics(pit1).ascent();
1454 tm.redoParagraph(pit1);
1455 y1 -= tm.parMetrics(pit1).descent();
1459 // Take care of ascent of first line
1460 y1 -= tm.parMetrics(pit1).ascent();
1462 // Normalize anchor for next time
1466 // Grey at the beginning is ugly
1467 if (pit1 == 0 && y1 > 0) {
1473 // Redo paragraphs below the anchor if necessary.
1475 while (y2 < height_ && pit2 < int(npit) - 1) {
1476 y2 += tm.parMetrics(pit2).descent();
1479 tm.redoParagraph(pit2);
1480 y2 += tm.parMetrics(pit2).ascent();
1483 // Take care of descent of last line
1484 y2 += tm.parMetrics(pit2).descent();
1486 // The coordinates of all these paragraphs are correct, cache them
1488 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1489 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1490 ParagraphMetrics const & pm = tm.parMetrics(pit);
1492 parPos[pit] = Point(0, y);
1493 if (singlepar && pit == cursor_.bottom().pit()) {
1494 // In Single Paragraph mode, collect here the
1495 // y1 and y2 of the (one) paragraph the cursor is in
1496 y1 = y - pm.ascent();
1497 y2 = y + pm.descent();
1503 // collect cursor paragraph iter bounds
1504 pit1 = cursor_.bottom().pit();
1505 pit2 = cursor_.bottom().pit();
1508 LYXERR(Debug::DEBUG)
1509 << BOOST_CURRENT_FUNCTION
1512 << " pit1: " << pit1
1513 << " pit2: " << pit2
1514 << " npit: " << npit
1515 << " singlepar: " << singlepar
1519 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1520 singlepar? SingleParUpdate: FullScreenUpdate, size);
1522 if (lyxerr.debugging(Debug::WORKAREA)) {
1523 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1524 coord_cache_.dump();
1529 void BufferView::menuInsertLyXFile(string const & filenm)
1531 BOOST_ASSERT(cursor_.inTexted());
1532 string filename = filenm;
1534 if (filename.empty()) {
1535 // Launch a file browser
1537 string initpath = lyxrc.document_path;
1540 string const trypath = buffer_->filePath();
1541 // If directory is writeable, use this as default.
1542 if (isDirWriteable(FileName(trypath)))
1547 FileDialog fileDlg(_("Select LyX document to insert"),
1549 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1550 make_pair(_("Examples|#E#e"),
1551 from_utf8(addPath(package().system_support().absFilename(),
1554 FileDialog::Result result =
1555 fileDlg.open(from_utf8(initpath),
1556 FileFilterList(_("LyX Documents (*.lyx)")),
1559 if (result.first == FileDialog::Later)
1563 filename = to_utf8(result.second);
1565 // check selected filename
1566 if (filename.empty()) {
1567 // emit message signal.
1568 message(_("Canceled."));
1573 // Get absolute path of file and add ".lyx"
1574 // to the filename if necessary
1575 filename = fileSearch(string(), filename, "lyx").absFilename();
1577 docstring const disp_fn = makeDisplayPath(filename);
1578 // emit message signal.
1579 message(bformat(_("Inserting document %1$s..."), disp_fn));
1582 Buffer buf("", false);
1583 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1584 ErrorList & el = buffer_->errorList("Parse");
1585 // Copy the inserted document error list into the current buffer one.
1586 el = buf.errorList("Parse");
1587 recordUndo(cursor_);
1588 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1589 buf.params().textclass, el);
1590 res = _("Document %1$s inserted.");
1592 res = _("Could not insert document %1$s");
1594 // emit message signal.
1595 message(bformat(res, disp_fn));
1596 buffer_->errors("Parse");