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