]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
a01eb78b24f97e14ee379c1eb48daa1be9e7a169
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "debug.h"
20 #include "DocIterator.h"
21 #include "Counters.h"
22 #include "ErrorList.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "Layout.h"
31 #include "LayoutPtr.h"
32 #include "LyX.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "TexRow.h"
41 #include "Text.h"
42 #include "TocBackend.h"
43
44 #include "frontends/alert.h"
45
46 #include "insets/InsetBibitem.h"
47 #include "insets/InsetInclude.h"
48
49 #include "support/filetools.h"
50 #include "support/lyxlib.h"
51 #include "support/lstrings.h"
52
53
54 namespace lyx {
55
56 using namespace std;
57
58 using support::bformat;
59 using support::FileName;
60 using support::libFileSearch;
61 using support::makeAbsPath;
62 using support::makeDisplayPath;
63 using support::onlyFilename;
64 using support::onlyPath;
65
66 namespace Alert = frontend::Alert;
67
68
69 Buffer * checkAndLoadLyXFile(FileName const & filename)
70 {
71         // File already open?
72         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
73         if (checkBuffer) {
74                 if (checkBuffer->isClean())
75                         return checkBuffer;
76                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
77                 docstring text = bformat(_(
78                                 "The document %1$s is already loaded and has unsaved changes.\n"
79                                 "Do you want to abandon your changes and reload the version on disk?"), file);
80                 if (Alert::prompt(_("Reload saved document?"),
81                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
82                         return checkBuffer;
83
84                 // FIXME: should be LFUN_REVERT
85                 if (theBufferList().close(checkBuffer, false))
86                         // Load it again.
87                         return checkAndLoadLyXFile(filename);
88                 // The file could not be closed.
89                 return 0;
90         }
91
92         if (filename.isReadableFile()) {
93                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
94                 if (!b->loadLyXFile(filename)) {
95                         theBufferList().release(b);
96                         return 0;
97                 }
98                 return b;
99         }
100
101         docstring text = bformat(_("The document %1$s does not yet "
102                 "exist.\n\nDo you want to create a new document?"),
103                 from_utf8(filename.absFilename()));
104         if (!Alert::prompt(_("Create new document?"),
105                         text, 0, 1, _("&Create"), _("Cancel")))
106                 return newFile(filename.absFilename(), string(), true);
107
108         return 0;
109 }
110
111
112 // FIXME newFile() should probably be a member method of Application...
113 Buffer * newFile(string const & filename, string const & templatename,
114                  bool const isNamed)
115 {
116         // get a free buffer
117         Buffer * b = theBufferList().newBuffer(filename);
118         BOOST_ASSERT(b);
119
120         FileName tname;
121         // use defaults.lyx as a default template if it exists.
122         if (templatename.empty())
123                 tname = libFileSearch("templates", "defaults.lyx");
124         else
125                 tname = makeAbsPath(templatename);
126
127         if (!tname.empty()) {
128                 if (!b->readFile(tname)) {
129                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
130                         docstring const text  = bformat(
131                                 _("The specified document template\n%1$s\ncould not be read."),
132                                 file);
133                         Alert::error(_("Could not read template"), text);
134                         theBufferList().release(b);
135                         return 0;
136                 }
137         }
138
139         if (!isNamed) {
140                 b->setUnnamed();
141                 b->setFileName(filename);
142         }
143
144         b->setReadonly(false);
145         b->setFullyLoaded(true);
146
147         return b;
148 }
149
150
151 int countWords(DocIterator const & from, DocIterator const & to)
152 {
153         int count = 0;
154         bool inword = false;
155         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
156                 // Copied and adapted from isLetter() in ControlSpellChecker
157                 if (dit.inTexted()
158                     && dit.pos() != dit.lastpos()
159                     && dit.paragraph().isLetter(dit.pos())
160                     && !dit.paragraph().isDeleted(dit.pos())) {
161                         if (!inword) {
162                                 ++count;
163                                 inword = true;
164                         }
165                 } else if (inword)
166                         inword = false;
167         }
168
169         return count;
170 }
171
172
173 namespace {
174
175 depth_type getDepth(DocIterator const & it)
176 {
177         depth_type depth = 0;
178         for (size_t i = 0 ; i < it.depth() ; ++i)
179                 if (!it[i].inset().inMathed())
180                         depth += it[i].paragraph().getDepth() + 1;
181         // remove 1 since the outer inset does not count
182         return depth - 1;
183 }
184
185 depth_type getItemDepth(ParIterator const & it)
186 {
187         Paragraph const & par = *it;
188         LabelType const labeltype = par.layout()->labeltype;
189
190         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
191                 return 0;
192
193         // this will hold the lowest depth encountered up to now.
194         depth_type min_depth = getDepth(it);
195         ParIterator prev_it = it;
196         while (true) {
197                 if (prev_it.pit())
198                         --prev_it.top().pit();
199                 else {
200                         // start of nested inset: go to outer par
201                         prev_it.pop_back();
202                         if (prev_it.empty()) {
203                                 // start of document: nothing to do
204                                 return 0;
205                         }
206                 }
207
208                 // We search for the first paragraph with same label
209                 // that is not more deeply nested.
210                 Paragraph & prev_par = *prev_it;
211                 depth_type const prev_depth = getDepth(prev_it);
212                 if (labeltype == prev_par.layout()->labeltype) {
213                         if (prev_depth < min_depth)
214                                 return prev_par.itemdepth + 1;
215                         if (prev_depth == min_depth)
216                                 return prev_par.itemdepth;
217                 }
218                 min_depth = std::min(min_depth, prev_depth);
219                 // small optimization: if we are at depth 0, we won't
220                 // find anything else
221                 if (prev_depth == 0)
222                         return 0;
223         }
224 }
225
226
227 bool needEnumCounterReset(ParIterator const & it)
228 {
229         Paragraph const & par = *it;
230         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
231         depth_type const cur_depth = par.getDepth();
232         ParIterator prev_it = it;
233         while (prev_it.pit()) {
234                 --prev_it.top().pit();
235                 Paragraph const & prev_par = *prev_it;
236                 if (prev_par.getDepth() <= cur_depth)
237                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
238         }
239         // start of nested inset: reset
240         return true;
241 }
242
243
244 // set the label of a paragraph. This includes the counters.
245 void setLabel(Buffer const & buf, ParIterator & it)
246 {
247         TextClass const & textclass = buf.params().getTextClass();
248         Paragraph & par = it.paragraph();
249         LayoutPtr const & layout = par.layout();
250         Counters & counters = textclass.counters();
251
252         if (par.params().startOfAppendix()) {
253                 // FIXME: only the counter corresponding to toplevel
254                 // sectionning should be reset
255                 counters.reset();
256                 counters.appendix(true);
257         }
258         par.params().appendix(counters.appendix());
259
260         // Compute the item depth of the paragraph
261         par.itemdepth = getItemDepth(it);
262
263         if (layout->margintype == MARGIN_MANUAL) {
264                 if (par.params().labelWidthString().empty())
265                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
266         } else {
267                 par.params().labelWidthString(docstring());
268         }
269
270         switch(layout->labeltype) {
271         case LABEL_COUNTER:
272                 if (layout->toclevel <= buf.params().secnumdepth
273                     && (layout->latextype != LATEX_ENVIRONMENT
274                         || isFirstInSequence(it.pit(), it.plist()))) {
275                         counters.step(layout->counter);
276                         par.params().labelString(
277                                 par.expandLabel(layout, buf.params()));
278                 } else
279                         par.params().labelString(docstring());
280                 break;
281
282         case LABEL_ITEMIZE: {
283                 // At some point of time we should do something more
284                 // clever here, like:
285                 //   par.params().labelString(
286                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
287                 // for now, use a simple hardcoded label
288                 docstring itemlabel;
289                 switch (par.itemdepth) {
290                 case 0:
291                         itemlabel = char_type(0x2022);
292                         break;
293                 case 1:
294                         itemlabel = char_type(0x2013);
295                         break;
296                 case 2:
297                         itemlabel = char_type(0x2217);
298                         break;
299                 case 3:
300                         itemlabel = char_type(0x2219); // or 0x00b7
301                         break;
302                 }
303                 par.params().labelString(itemlabel);
304                 break;
305         }
306
307         case LABEL_ENUMERATE: {
308                 // FIXME: Yes I know this is a really, really! bad solution
309                 // (Lgb)
310                 docstring enumcounter = from_ascii("enum");
311
312                 switch (par.itemdepth) {
313                 case 2:
314                         enumcounter += 'i';
315                 case 1:
316                         enumcounter += 'i';
317                 case 0:
318                         enumcounter += 'i';
319                         break;
320                 case 3:
321                         enumcounter += "iv";
322                         break;
323                 default:
324                         // not a valid enumdepth...
325                         break;
326                 }
327
328                 // Maybe we have to reset the enumeration counter.
329                 if (needEnumCounterReset(it))
330                         counters.reset(enumcounter);
331
332                 counters.step(enumcounter);
333
334                 string format;
335
336                 switch (par.itemdepth) {
337                 case 0:
338                         format = N_("\\arabic{enumi}.");
339                         break;
340                 case 1:
341                         format = N_("(\\alph{enumii})");
342                         break;
343                 case 2:
344                         format = N_("\\roman{enumiii}.");
345                         break;
346                 case 3:
347                         format = N_("\\Alph{enumiv}.");
348                         break;
349                 default:
350                         // not a valid enumdepth...
351                         break;
352                 }
353
354                 par.params().labelString(counters.counterLabel(
355                         par.translateIfPossible(from_ascii(format), buf.params())));
356
357                 break;
358         }
359
360         case LABEL_SENSITIVE: {
361                 string const & type = counters.current_float();
362                 docstring full_label;
363                 if (type.empty())
364                         full_label = buf.B_("Senseless!!! ");
365                 else {
366                         docstring name = buf.B_(textclass.floats().getType(type).name());
367                         if (counters.hasCounter(from_utf8(type))) {
368                                 counters.step(from_utf8(type));
369                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
370                                                      name, 
371                                                      counters.theCounter(from_utf8(type)));
372                         } else
373                                 full_label = bformat(from_ascii("%1$s #:"), name);      
374                 }
375                 par.params().labelString(full_label);   
376                 break;
377         }
378
379         case LABEL_NO_LABEL:
380                 par.params().labelString(docstring());
381                 break;
382
383         case LABEL_MANUAL:
384         case LABEL_TOP_ENVIRONMENT:
385         case LABEL_CENTERED_TOP_ENVIRONMENT:
386         case LABEL_STATIC:      
387         case LABEL_BIBLIO:
388                 par.params().labelString(
389                         par.translateIfPossible(layout->labelstring(), 
390                                                 buf.params()));
391                 break;
392         }
393 }
394
395 } // anon namespace
396
397 void updateLabels(Buffer const & buf, ParIterator & parit)
398 {
399         BOOST_ASSERT(parit.pit() == 0);
400
401         depth_type maxdepth = 0;
402         pit_type const lastpit = parit.lastpit();
403         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
404                 // reduce depth if necessary
405                 parit->params().depth(min(parit->params().depth(), maxdepth));
406                 maxdepth = parit->getMaxDepthAfter();
407
408                 // set the counter for this paragraph
409                 setLabel(buf, parit);
410
411                 // Now the insets
412                 InsetList::const_iterator iit = parit->insetList().begin();
413                 InsetList::const_iterator end = parit->insetList().end();
414                 for (; iit != end; ++iit) {
415                         parit.pos() = iit->pos;
416                         iit->inset->updateLabels(buf, parit);
417                 }
418         }
419         
420 }
421
422
423 // FIXME: buf should should be const because updateLabels() modifies
424 // the contents of the paragraphs.
425 void updateLabels(Buffer const & buf, bool childonly)
426 {
427         Buffer const * const master = buf.masterBuffer();
428         // Use the master text class also for child documents
429         TextClass const & textclass = master->params().getTextClass();
430
431         if (!childonly) {
432                 // If this is a child document start with the master
433                 if (master != &buf) {
434                         updateLabels(*master);
435                         return;
436                 }
437
438                 // start over the counters
439                 textclass.counters().reset();
440         }
441
442         Buffer & cbuf = const_cast<Buffer &>(buf);
443
444         if (buf.text().empty()) {
445                 // FIXME: we don't call continue with updateLabels()
446                 // here because it crashes on newly created documents.
447                 // But the TocBackend needs to be initialised
448                 // nonetheless so we update the tocBackend manually.
449                 cbuf.tocBackend().update();
450                 return;
451         }
452
453         // do the real work
454         ParIterator parit = par_iterator_begin(buf.inset());
455         updateLabels(buf, parit);
456
457         cbuf.tocBackend().update();
458         if (!childonly)
459                 cbuf.structureChanged();
460 }
461
462
463 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
464 {
465         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
466                 Buffer * master = buffer.masterBuffer();
467                 master->tocBackend().updateItem(par_it);
468                 master->structureChanged();
469         }
470 }
471
472
473 } // namespace lyx