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