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