]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
* implemention of the WordList with iterator caching for a std::set string list.
[features.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14 #include "InsetNewline.h"
15
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "Cursor.h"
23 #include "DispatchResult.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "InsetList.h"
27 #include "Intl.h"
28 #include "lyxfind.h"
29 #include "Lexer.h"
30 #include "LyXRC.h"
31 #include "Text.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "output_docbook.h"
35 #include "output_latex.h"
36 #include "output_plaintext.h"
37 #include "Paragraph.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
40 #include "ParIterator.h"
41 #include "Row.h"
42 #include "sgml.h"
43 #include "TextClass.h"
44 #include "TextMetrics.h"
45 #include "TexRow.h"
46 #include "WordList.h"
47
48 #include "frontends/alert.h"
49 #include "frontends/Painter.h"
50
51 #include "support/debug.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h"
54
55 #include <boost/bind.hpp>
56 #include <boost/assert.hpp>
57
58 using namespace std;
59 using namespace lyx::support;
60
61 using boost::bind;
62 using boost::ref;
63
64 namespace lyx {
65
66 using graphics::PreviewLoader;
67
68
69 class TextCompletionList : public Inset::CompletionList {
70 public:
71         ///
72         TextCompletionList(Cursor const & cur)
73         : buf_(cur.buffer()), pos_(0) {}
74         ///
75         virtual ~TextCompletionList() {}
76
77         ///
78         virtual bool sorted() const { return true; }
79         ///
80         virtual size_t size() const {
81                 return buf_.registeredWords().size();
82         }
83         ///
84         virtual docstring data(size_t idx) const {
85                 return buf_.registeredWords().word(idx);
86         }
87
88 private:
89         Buffer const & buf_;
90         size_t pos_;
91 };
92
93
94 /////////////////////////////////////////////////////////////////////
95
96 InsetText::InsetText(BufferParams const & bp)
97         : drawFrame_(false), frame_color_(Color_insetframe)
98 {
99         paragraphs().push_back(Paragraph());
100         Paragraph & ourpar = paragraphs().back();
101         ourpar.setEmptyOrDefaultLayout(bp.textClass());
102         ourpar.setInsetOwner(this);
103 }
104
105
106 InsetText::InsetText(InsetText const & in)
107         : Inset(in), text_()
108 {
109         text_.autoBreakRows_ = in.text_.autoBreakRows_;
110         drawFrame_ = in.drawFrame_;
111         frame_color_ = in.frame_color_;
112         text_.paragraphs() = in.text_.paragraphs();
113         setParagraphOwner();
114 }
115
116
117 InsetText::InsetText()
118 {}
119
120
121 void InsetText::setParagraphOwner()
122 {
123         for_each(paragraphs().begin(), paragraphs().end(),
124                  bind(&Paragraph::setInsetOwner, _1, this));
125 }
126
127
128 void InsetText::clear()
129 {
130         ParagraphList & pars = paragraphs();
131
132         // This is a gross hack...
133         LayoutPtr old_layout = pars.begin()->layout();
134
135         pars.clear();
136         pars.push_back(Paragraph());
137         pars.begin()->setInsetOwner(this);
138         pars.begin()->setLayout(old_layout);
139 }
140
141
142 Inset * InsetText::clone() const
143 {
144         return new InsetText(*this);
145 }
146
147
148 Dimension const InsetText::dimension(BufferView const & bv) const
149 {
150         TextMetrics const & tm = bv.textMetrics(&text_);
151         Dimension dim = tm.dimension();
152         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
153         dim.des += TEXT_TO_INSET_OFFSET;
154         dim.asc += TEXT_TO_INSET_OFFSET;
155         return dim;
156 }
157
158
159 void InsetText::write(Buffer const & buf, ostream & os) const
160 {
161         os << "Text\n";
162         text_.write(buf, os);
163 }
164
165
166 void InsetText::read(Buffer const & buf, Lexer & lex)
167 {
168         clear();
169
170         // delete the initial paragraph
171         Paragraph oldpar = *paragraphs().begin();
172         paragraphs().clear();
173         ErrorList errorList;
174         bool res = text_.read(buf, lex, errorList, this);
175
176         if (!res) {
177                 lex.printError("Missing \\end_inset at this point. "
178                                            "Read: `$$Token'");
179         }
180
181         // sanity check
182         // ensure we have at least one paragraph.
183         if (paragraphs().empty())
184                 paragraphs().push_back(oldpar);
185 }
186
187
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 {
190         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191
192         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193
194         // Hand font through to contained lyxtext:
195         tm.font_.fontInfo() = mi.base.font;
196         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
197         if (hasFixedWidth())
198                 tm.metrics(mi, dim, mi.base.textwidth);
199         else
200                 tm.metrics(mi, dim);
201         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
202         dim.asc += TEXT_TO_INSET_OFFSET;
203         dim.des += TEXT_TO_INSET_OFFSET;
204         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
205 }
206
207
208 void InsetText::draw(PainterInfo & pi, int x, int y) const
209 {
210         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
211
212         if (drawFrame_ || pi.full_repaint) {
213                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
214                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
215                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
216                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
217                 if (pi.full_repaint)
218                         pi.pain.fillRectangle(xframe, yframe, w, h, backgroundColor());
219                 if (drawFrame_)
220                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
221         }
222         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
223 }
224
225
226 docstring const InsetText::editMessage() const
227 {
228         return _("Opened Text Inset");
229 }
230
231
232 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
233 {
234         pit_type const pit = front ? 0 : paragraphs().size() - 1;
235         pos_type pos = front ? 0 : paragraphs().back().size();
236
237         // if visual information is not to be ignored, move to extreme right/left
238         if (entry_from != ENTRY_DIRECTION_IGNORE) {
239                 Cursor temp_cur = cur;
240                 temp_cur.pit() = pit;
241                 temp_cur.pos() = pos;
242                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
243                 pos = temp_cur.pos();
244         }
245
246         text_.setCursor(cur.top(), pit, pos);
247         cur.clearSelection();
248         cur.finishUndo();
249 }
250
251
252 Inset * InsetText::editXY(Cursor & cur, int x, int y)
253 {
254         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
255 }
256
257
258 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
259 {
260         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
261                 << " [ cmd.action = " << cmd.action << ']');
262         text_.dispatch(cur, cmd);
263 }
264
265
266 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
267         FuncStatus & status) const
268 {
269         return text_.getStatus(cur, cmd, status);
270 }
271
272
273 void InsetText::setChange(Change const & change)
274 {
275         ParagraphList::iterator pit = paragraphs().begin();
276         ParagraphList::iterator end = paragraphs().end();
277         for (; pit != end; ++pit) {
278                 pit->setChange(change);
279         }
280 }
281
282
283 void InsetText::acceptChanges(BufferParams const & bparams)
284 {
285         text_.acceptChanges(bparams);
286 }
287
288
289 void InsetText::rejectChanges(BufferParams const & bparams)
290 {
291         text_.rejectChanges(bparams);
292 }
293
294
295 int InsetText::latex(Buffer const & buf, odocstream & os,
296                      OutputParams const & runparams) const
297 {
298         TexRow texrow;
299         latexParagraphs(buf, text_, os, texrow, runparams);
300         return texrow.rows();
301 }
302
303
304 int InsetText::plaintext(Buffer const & buf, odocstream & os,
305                          OutputParams const & runparams) const
306 {
307         ParagraphList::const_iterator beg = paragraphs().begin();
308         ParagraphList::const_iterator end = paragraphs().end();
309         ParagraphList::const_iterator it = beg;
310         bool ref_printed = false;
311         int len = 0;
312         for (; it != end; ++it) {
313                 if (it != beg) {
314                         os << '\n';
315                         if (runparams.linelen > 0)
316                                 os << '\n';
317                 }
318                 odocstringstream oss;
319                 writePlaintextParagraph(buf, *it, oss, runparams, ref_printed);
320                 docstring const str = oss.str();
321                 os << str;
322                 // FIXME: len is not computed fully correctly; in principle,
323                 // we have to count the characters after the last '\n'
324                 len = str.size();
325         }
326
327         return len;
328 }
329
330
331 int InsetText::docbook(Buffer const & buf, odocstream & os,
332                        OutputParams const & runparams) const
333 {
334         docbookParagraphs(paragraphs(), buf, os, runparams);
335         return 0;
336 }
337
338
339 void InsetText::validate(LaTeXFeatures & features) const
340 {
341         for_each(paragraphs().begin(), paragraphs().end(),
342                  bind(&Paragraph::validate, _1, ref(features)));
343 }
344
345
346 void InsetText::cursorPos(BufferView const & bv,
347                 CursorSlice const & sl, bool boundary, int & x, int & y) const
348 {
349         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
350         y = bv.textMetrics(&text_).cursorY(sl, boundary);
351 }
352
353
354 bool InsetText::showInsetDialog(BufferView *) const
355 {
356         return false;
357 }
358
359
360 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
361 {
362         clear();
363         Paragraph & first = paragraphs().front();
364         for (unsigned int i = 0; i < data.length(); ++i)
365                 first.insertChar(i, data[i], font, trackChanges);
366 }
367
368
369 void InsetText::setAutoBreakRows(bool flag)
370 {
371         if (flag == text_.autoBreakRows_)
372                 return;
373
374         text_.autoBreakRows_ = flag;
375         if (flag)
376                 return;
377
378         // remove previously existing newlines
379         ParagraphList::iterator it = paragraphs().begin();
380         ParagraphList::iterator end = paragraphs().end();
381         for (; it != end; ++it)
382                 for (int i = 0; i < it->size(); ++i)
383                         if (it->isNewline(i))
384                                 // do not track the change, because the user
385                                 // is not allowed to revert/reject it
386                                 it->eraseChar(i, false);
387 }
388
389
390 void InsetText::setDrawFrame(bool flag)
391 {
392         drawFrame_ = flag;
393 }
394
395
396 ColorCode InsetText::frameColor() const
397 {
398         return frame_color_;
399 }
400
401
402 void InsetText::setFrameColor(ColorCode col)
403 {
404         frame_color_ = col;
405 }
406
407
408 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
409 {
410         // There is little we can do here to keep track of changes.
411         // As of 2006/10/20, appendParagraphs is used exclusively by
412         // LyXTabular::setMultiColumn. In this context, the paragraph break
413         // is lost irreversibly and the appended text doesn't really change
414
415         ParagraphList & pl = paragraphs();
416
417         ParagraphList::iterator pit = plist.begin();
418         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
419         ++pit;
420         mergeParagraph(buffer->params(), pl,
421                        distance(pl.begin(), ins) - 1);
422
423         for_each(pit, plist.end(),
424                  bind(&ParagraphList::push_back, ref(pl), _1));
425 }
426
427
428 void InsetText::addPreview(PreviewLoader & loader) const
429 {
430         ParagraphList::const_iterator pit = paragraphs().begin();
431         ParagraphList::const_iterator pend = paragraphs().end();
432
433         for (; pit != pend; ++pit) {
434                 InsetList::const_iterator it  = pit->insetList().begin();
435                 InsetList::const_iterator end = pit->insetList().end();
436                 for (; it != end; ++it)
437                         it->inset->addPreview(loader);
438         }
439 }
440
441
442 //FIXME: instead of this hack, which only works by chance,
443 // cells should have their own insetcell type, which returns CELL_CODE!
444 bool InsetText::neverIndent(Buffer const & buffer) const
445 {
446         // this is only true for tabular cells
447         return !text_.isMainText(buffer) && lyxCode() == TEXT_CODE;
448 }
449
450
451 ParagraphList const & InsetText::paragraphs() const
452 {
453         return text_.paragraphs();
454 }
455
456
457 ParagraphList & InsetText::paragraphs()
458 {
459         return text_.paragraphs();
460 }
461
462
463 void InsetText::updateLabels(Buffer const & buf, ParIterator const & it)
464 {
465         ParIterator it2 = it;
466         it2.forwardPos();
467         BOOST_ASSERT(&it2.inset() == this && it2.pit() == 0);
468         lyx::updateLabels(buf, it2);
469 }
470
471
472 bool InsetText::completionSupported(Cursor const & cur) const
473 {
474         Cursor const & bvCur = cur.bv().cursor();
475         if (&bvCur.inset() != this)
476                 return false;
477         Paragraph const & par = cur.paragraph();
478         return cur.pos() > 0
479                 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
480                 && par.isLetter(cur.pos() - 1);
481 }
482
483
484 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
485 {
486         return completionSupported(cur);
487 }
488
489
490 bool InsetText::automaticInlineCompletion() const
491 {
492         return lyxrc.completion_inline_text;
493 }
494
495
496 bool InsetText::automaticPopupCompletion() const
497 {
498         return lyxrc.completion_popup_text;
499 }
500
501
502 Inset::CompletionList const 
503 * InsetText::createCompletionList(Cursor const & cur) const
504 {
505         if (!completionSupported(cur))
506                 return 0;
507
508         return new TextCompletionList(cur);
509 }
510
511
512 docstring InsetText::previousWord(Buffer const & buffer, CursorSlice const & sl) const
513 {
514         CursorSlice from = sl;
515         CursorSlice to = sl;
516         text_.getWord(from, to, PREVIOUS_WORD);
517         if (sl == from || to == from)
518                 return docstring();
519         
520         Paragraph const & par = sl.paragraph();
521         return par.asString(buffer, from.pos(), to.pos(), false);
522 }
523
524
525 docstring InsetText::completionPrefix(Cursor const & cur) const
526 {
527         if (!completionSupported(cur))
528                 return docstring();
529         
530         return previousWord(cur.buffer(), cur.top());
531 }
532
533
534 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
535                                      bool /*finished*/)
536 {
537         if (!completionSupported(cur))
538                 return false;
539
540         BOOST_ASSERT(cur.bv().cursor() == cur);
541         cur.insert(s);
542         cur.bv().cursor() = cur;
543         return true;
544 }
545
546
547 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
548                                         Dimension & dim) const
549 {
550         Cursor const & bvcur = cur.bv().cursor();
551         
552         // get word in front of cursor
553         docstring word = previousWord(cur.buffer(), bvcur.top());
554         DocIterator wordStart = bvcur;
555         wordStart.pos() -= word.length();
556         
557         // get position on screen of the word start and end
558         Point lxy = cur.bv().getPos(wordStart, false);
559         Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
560         
561         // calculate dimensions of the word
562         TextMetrics const & tm = cur.bv().textMetrics(&text_);
563         dim = tm.rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
564         dim.wid = abs(rxy.x_ - lxy.x_);
565         
566         // calculate position of word
567         y = lxy.y_;
568         x = min(rxy.x_, lxy.x_);
569         
570         //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
571         //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
572 }
573
574
575 } // namespace lyx