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