]> git.lyx.org Git - lyx.git/blob - src/buffer.C
more message work, should now be ready for real integration
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "bufferlist.h"
15 #include "LyXAction.h"
16 #include "lyxrc.h"
17 #include "lyxlex.h"
18 #include "tex-strings.h"
19 #include "layout.h"
20 #include "bufferview_funcs.h"
21 #include "lyxfont.h"
22 #include "version.h"
23 #include "LaTeX.h"
24 #include "Chktex.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "lyxtext.h"
28 #include "gettext.h"
29 #include "language.h"
30 #include "exporter.h"
31 #include "Lsstream.h"
32 #include "format.h"
33 #include "BufferView.h"
34 #include "ParagraphParameters.h"
35 #include "iterators.h"
36 #include "lyxtextclasslist.h"
37 #include "sgml.h"
38 #include "paragraph_funcs.h"
39 #include "messages.h"
40 #include "author.h"
41
42 #include "frontends/LyXView.h"
43
44 #include "mathed/formulamacro.h"
45 #include "mathed/formula.h"
46
47 #include "insets/inseterror.h"
48 #include "insets/insetbibitem.h"
49 #include "insets/insetbibtex.h"
50 #include "insets/insetinclude.h"
51 #include "insets/insettext.h"
52
53 #include "frontends/Dialogs.h"
54 #include "frontends/Alert.h"
55
56 #include "graphics/Previews.h"
57
58 #include "support/textutils.h"
59 #include "support/filetools.h"
60 #include "support/path.h"
61 #include "support/os.h"
62 #include "support/lyxlib.h"
63 #include "support/FileInfo.h"
64 #include "support/lyxmanip.h"
65 #include "support/lyxtime.h"
66
67 #include <boost/bind.hpp>
68 #include <boost/tuple/tuple.hpp>
69 #include "support/BoostFormat.h"
70
71 #include <fstream>
72 #include <iomanip>
73 #include <map>
74 #include <stack>
75 #include <list>
76 #include <algorithm>
77
78 #include <cstdlib>
79 #include <cmath>
80 #include <unistd.h>
81 #include <sys/types.h>
82 #include <utime.h>
83
84 #ifdef HAVE_LOCALE
85 #include <locale>
86 #endif
87
88 #ifndef CXX_GLOBAL_CSTD
89 using std::pow;
90 #endif
91
92 using std::ostream;
93 using std::ofstream;
94 using std::ifstream;
95 using std::fstream;
96 using std::ios;
97 using std::setw;
98 using std::endl;
99 using std::pair;
100 using std::make_pair;
101 using std::vector;
102 using std::map;
103 using std::stack;
104 using std::list;
105 using std::for_each;
106
107 using lyx::pos_type;
108 using lyx::textclass_type;
109
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
112
113 namespace {
114
115 const int LYX_FORMAT = 223;
116
117 } // namespace anon
118
119 Buffer::Buffer(string const & file, bool ronly)
120         : niceFile(true), lyx_clean(true), bak_clean(true),
121           unnamed(false), read_only(ronly),
122           filename_(file), users(0)
123 {
124         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
125         filepath_ = OnlyPath(file);
126         lyxvc.buffer(this);
127         if (read_only || lyxrc.use_tempdir) {
128                 tmppath = CreateBufferTmpDir();
129         } else {
130                 tmppath.erase();
131         }
132
133         // set initial author
134         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
135 }
136
137
138 Buffer::~Buffer()
139 {
140         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
141         // here the buffer should take care that it is
142         // saved properly, before it goes into the void.
143
144         // make sure that views using this buffer
145         // forgets it.
146         if (users)
147                 users->buffer(0);
148
149         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
150 #if USE_BOOST_FORMAT
151                 boost::format fmt = _("Could not remove the temporary directory %1$s");
152                 fmt % tmppath;
153                 string msg = fmt.str();
154 #else
155                 string msg = _("Could not remove the temporary directory ") + tmppath;
156 #endif
157                 Alert::warning(_("Could not remove temporary directory"), msg);
158         }
159
160         paragraphs.clear();
161
162         // Remove any previewed LaTeX snippets assocoated with this buffer.
163         grfx::Previews::get().removeLoader(this);
164 }
165
166
167 string const Buffer::getLatexName(bool no_path) const
168 {
169         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
170         if (no_path)
171                 return OnlyFilename(name);
172         else
173                 return name;
174 }
175
176
177 pair<Buffer::LogType, string> const Buffer::getLogName() const
178 {
179         string const filename = getLatexName(false);
180
181         if (filename.empty())
182                 return make_pair(Buffer::latexlog, string());
183
184         string path = OnlyPath(filename);
185
186         if (lyxrc.use_tempdir || !IsDirWriteable(path))
187                 path = tmppath;
188
189         string const fname = AddName(path,
190                                      OnlyFilename(ChangeExtension(filename,
191                                                                   ".log")));
192         string const bname =
193                 AddName(path, OnlyFilename(
194                         ChangeExtension(filename,
195                                         formats.extension("literate") + ".out")));
196
197         // If no Latex log or Build log is newer, show Build log
198
199         FileInfo const f_fi(fname);
200         FileInfo const b_fi(bname);
201
202         if (b_fi.exist() &&
203             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
204                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
205                 return make_pair(Buffer::buildlog, bname);
206         }
207         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
208         return make_pair(Buffer::latexlog, fname);
209 }
210
211
212 void Buffer::setReadonly(bool flag)
213 {
214         if (read_only != flag) {
215                 read_only = flag;
216                 updateTitles();
217                 users->owner()->getDialogs().updateBufferDependent(false);
218         }
219 }
220
221
222 AuthorList & Buffer::authors()
223 {
224         return params.authorlist;
225 }
226
227
228 /// Update window titles of all users
229 // Should work on a list
230 void Buffer::updateTitles() const
231 {
232         if (users)
233                 users->owner()->updateWindowTitle();
234 }
235
236
237 /// Reset autosave timer of all users
238 // Should work on a list
239 void Buffer::resetAutosaveTimers() const
240 {
241         if (users)
242                 users->owner()->resetAutosaveTimer();
243 }
244
245
246 void Buffer::setFileName(string const & newfile)
247 {
248         filename_ = MakeAbsPath(newfile);
249         filepath_ = OnlyPath(filename_);
250         setReadonly(IsFileWriteable(filename_) == 0);
251         updateTitles();
252 }
253
254
255 // We'll remove this later. (Lgb)
256 namespace {
257
258 void unknownClass(string const & unknown)
259 {
260         string msg =
261 #if USE_BOOST_FORMAT
262                 boost::io::str(boost::format(
263                         _("Using the default document class, because the "
264                         " class %1$s is unknown.")) % unknown);
265 #else
266                 _("Using the default document class, because the "
267                 " class ") + unknown + (" is unknown.");
268 #endif
269         Alert::warning(_("Unknown document class"), msg);
270 }
271
272 } // anon
273
274 int Buffer::readHeader(LyXLex & lex)
275 {
276         int unknown_tokens = 0;
277
278         while (lex.isOK()) {
279                 lex.nextToken();
280                 string const token = lex.getString();
281
282                 if (token.empty())
283                         continue;
284
285                 if (token == "\\end_header")
286                         break;
287
288                 lyxerr[Debug::PARSER] << "Handling header token: `"
289                                       << token << '\'' << endl;
290
291                 string unknown = params.readToken(lex, token);
292                 if (!unknown.empty()) {
293                         if (unknown[0] != '\\') {
294                                 unknownClass(unknown);
295                         } else {
296                                 ++unknown_tokens;
297                         }
298                 }
299         }
300         return unknown_tokens;
301 }
302
303
304 // candidate for move to BufferView
305 // (at least some parts in the beginning of the func)
306 //
307 // Uwe C. Schroeder
308 // changed to be public and have one parameter
309 // if par = 0 normal behavior
310 // else insert behavior
311 // Returns false if "\the_end" is not read (Asger)
312 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
313 {
314         int unknown_tokens = 0;
315
316         Paragraph::depth_type depth = 0;
317         bool the_end_read = false;
318
319         if (paragraphs.empty()) {
320                 unknown_tokens += readHeader(lex);
321
322                 if (!params.getLyXTextClass().load()) {
323                         string theclass = params.getLyXTextClass().name();
324                         string msg =
325 #if USE_BOOST_FORMAT
326                                 boost::io::str(boost::format(
327                                         _("Using the default document class, because the "
328                                         " class %1$s could not be loaded.")) % theclass);
329 #else
330                                 _("Using the default document class, because the "
331                                 " class ") + theclass + (" could not be loaded.");
332 #endif
333                         Alert::error(_("Can't load document class"), msg);
334                         params.textclass = 0;
335                 }
336         } else {
337                 // We are inserting into an existing document
338                 users->text->breakParagraph(paragraphs);
339
340                 // We don't want to adopt the parameters from the
341                 // document we insert, so read them into a temporary buffer
342                 // and then discard it
343
344                 Buffer tmpbuf("", false);
345                 tmpbuf.readHeader(lex);
346         }
347
348         while (lex.isOK()) {
349                 lex.nextToken();
350                 string const token = lex.getString();
351
352                 if (token.empty())
353                         continue;
354
355                 lyxerr[Debug::PARSER] << "Handling token: `"
356                                       << token << '\'' << endl;
357
358                 if (token == "\\the_end") {
359                         the_end_read = true;
360                         continue;
361                 }
362
363                 unknown_tokens += readParagraph(lex, token, paragraphs, pit, depth);
364         }
365
366
367         if (unknown_tokens > 0) {
368 #if USE_BOOST_FORMAT
369                 string s;
370                 if (unknown_tokens == 1) {
371                         boost::format fmt(_("Encountered one unknown token when reading the document %1$s."));
372                         fmt % fileName();
373                         s = fmt.str();
374                 } else {
375                         boost::format fmt(_("Encountered %1$s unknown tokens when reading the document %2$s."));
376                         fmt % tostr(unknown_tokens);
377                         fmt % fileName();
378                         s = fmt.str();
379                 }
380 #else
381                 string s = _("Encountered ");
382                 if (unknown_tokens == 1) {
383                         s += _("one unknown token");
384                 } else {
385                         s += tostr(unknown_tokens);
386                         s += _(" unknown tokens");
387                 }
388                 Alert::warning(_("Document format failure"), s);
389 #endif
390         }
391
392         return the_end_read;
393 }
394
395
396 int
397 Buffer::readParagraph(LyXLex & lex, string const & token,
398                       ParagraphList & pars, ParagraphList::iterator & pit,
399                       Paragraph::depth_type & depth)
400 {
401         static Change current_change;
402         int unknown = 0;
403
404         if (token == "\\layout") {
405                 lex.pushToken(token);
406
407                 Paragraph * par = new Paragraph();
408                 par->params().depth(depth);
409                 if (params.tracking_changes)
410                         par->trackChanges();
411                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
412                 par->setFont(0, f);
413
414                 // FIXME: goddamn InsetTabular makes us pass a Buffer
415                 // not BufferParams
416                 unknown += ::readParagraph(*this, *par, lex);
417
418                 // insert after
419                 if (pit != pars.end())
420                         ++pit;
421                 pit = pars.insert(pit, par);
422         } else if (token == "\\begin_deeper") {
423                 ++depth;
424         } else if (token == "\\end_deeper") {
425                 if (!depth) {
426                         lex.printError("\\end_deeper: " "depth is already null");
427                 } else {
428                         --depth;
429                 }
430         } else {
431                 ++unknown;
432         }
433         return unknown;
434 }
435
436
437 // needed to insert the selection
438 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
439                                  LyXFont const & fn,string const & str)
440 {
441         LyXLayout_ptr const & layout = par->layout();
442
443         LyXFont font = fn;
444
445         par->checkInsertChar(font);
446         // insert the string, don't insert doublespace
447         bool space_inserted = true;
448         bool autobreakrows = !par->inInset() ||
449                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
450         for(string::const_iterator cit = str.begin();
451             cit != str.end(); ++cit) {
452                 if (*cit == '\n') {
453                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
454                                 breakParagraph(params, paragraphs, par, pos,
455                                                layout->isEnvironment());
456                                 ++par;
457                                 pos = 0;
458                                 space_inserted = true;
459                         } else {
460                                 continue;
461                         }
462                         // do not insert consecutive spaces if !free_spacing
463                 } else if ((*cit == ' ' || *cit == '\t') &&
464                            space_inserted && !layout->free_spacing &&
465                                    !par->isFreeSpacing())
466                 {
467                         continue;
468                 } else if (*cit == '\t') {
469                         if (!layout->free_spacing && !par->isFreeSpacing()) {
470                                 // tabs are like spaces here
471                                 par->insertChar(pos, ' ', font);
472                                 ++pos;
473                                 space_inserted = true;
474                         } else {
475                                 const pos_type nb = 8 - pos % 8;
476                                 for (pos_type a = 0; a < nb ; ++a) {
477                                         par->insertChar(pos, ' ', font);
478                                         ++pos;
479                                 }
480                                 space_inserted = true;
481                         }
482                 } else if (!IsPrintable(*cit)) {
483                         // Ignore unprintables
484                         continue;
485                 } else {
486                         // just insert the character
487                         par->insertChar(pos, *cit, font);
488                         ++pos;
489                         space_inserted = (*cit == ' ');
490                 }
491
492         }
493 }
494
495
496 bool Buffer::readFile(LyXLex & lex, string const & filename)
497 {
498         bool ret = readFile(lex, filename, paragraphs.begin());
499
500         // After we have read a file, we must ensure that the buffer
501         // language is set and used in the gui.
502         // If you know of a better place to put this, please tell me. (Lgb)
503         messages_.reset(new Messages(params.language->code(),
504                                      "/usr/local/share/locale"));
505         
506         return ret;
507 }
508
509
510 // FIXME: all the below Alerts should give the filename..
511 bool Buffer::readFile(LyXLex & lex, string const & filename,
512                       ParagraphList::iterator pit)
513 {
514         if (!lex.isOK()) {
515                 Alert::error(_("Document could not be read"),
516                         _("The specified document could not be read."));
517                 return false;
518         }
519
520         lex.next();
521         string const token(lex.getString());
522
523         if (!lex.isOK()) {
524                 Alert::error(_("Document could not be read"),
525                         _("The specified document could not be read."));
526                 return false;
527         }
528
529         // the first token _must_ be...
530         if (token != "\\lyxformat") {
531                 Alert::error(_("Document format failure"),
532                         _("The specified document is not a LyX document."));
533                 return false;
534         }
535
536         lex.eatLine();
537         string tmp_format = lex.getString();
538         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
539         // if present remove ".," from string.
540         string::size_type dot = tmp_format.find_first_of(".,");
541         //lyxerr << "           dot found at " << dot << endl;
542         if (dot != string::npos)
543                         tmp_format.erase(dot, 1);
544         file_format = strToInt(tmp_format);
545         //lyxerr << "format: " << file_format << endl;
546         if (file_format == LYX_FORMAT) {
547                 // current format
548         } else if (file_format > LYX_FORMAT) {
549                 Alert::warning(_("Document format failure"),
550                         _("This document was created with a newer version of "
551                         "LyX. This is likely to cause problems."));
552         } else if (file_format < LYX_FORMAT) {
553                 // old formats
554                 if (file_format < 200) {
555                         Alert::error(_("Document format failure"),
556                                 _("This LyX document is too old to be read "
557                                 "by this version of LyX. Try LyX 0.10."));
558                         return false;
559                 } else if (!filename.empty()) {
560                         string command =
561                                 LibFileSearch("lyx2lyx", "lyx2lyx");
562                         if (command.empty()) {
563                                 Alert::error(_("Conversion script not found"),
564                                         _("The document is from an earlier version "
565                                           "of LyX, but the conversion script lyx2lyx "
566                                           "could not be found."));
567                                 return false;
568                         }
569                         command += " -t"
570                                 +tostr(LYX_FORMAT) + ' '
571                                 + QuoteName(filename);
572                         lyxerr[Debug::INFO] << "Running '"
573                                             << command << '\''
574                                             << endl;
575                         cmd_ret const ret = RunCommand(command);
576                         if (ret.first) {
577                                 Alert::error(_("Conversion script failed"),
578                                         _("The document is from an earlier version "
579                                           "of LyX, but the lyx2lyx script failed "
580                                           "to convert it."));
581                                 return false;
582                         }
583                         istringstream is(STRCONV(ret.second));
584                         LyXLex tmplex(0, 0);
585                         tmplex.setStream(is);
586                         return readFile(tmplex, string(), pit);
587                 } else {
588                         // This code is reached if lyx2lyx failed (for
589                         // some reason) to change the file format of
590                         // the file.
591                         lyx::Assert(false);
592                         return false;
593                 }
594         }
595         bool the_end = readBody(lex, pit);
596         params.setPaperStuff();
597
598         if (!the_end) {
599                 Alert::error(_("Document format failure"),
600                         _("The document ended unexpectedly, which means "
601                           "that it is probably corrupted."));
602         }
603         return true;
604 }
605
606
607 // Should probably be moved to somewhere else: BufferView? LyXView?
608 bool Buffer::save() const
609 {
610         // We don't need autosaves in the immediate future. (Asger)
611         resetAutosaveTimers();
612
613         // make a backup
614         string s;
615         if (lyxrc.make_backup) {
616                 s = fileName() + '~';
617                 if (!lyxrc.backupdir_path.empty())
618                         s = AddName(lyxrc.backupdir_path,
619                                     subst(os::slashify_path(s),'/','!'));
620
621                 // Rename is the wrong way of making a backup,
622                 // this is the correct way.
623                 /* truss cp fil fil2:
624                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
625                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
626                    open("LyXVC.lyx", O_RDONLY)                     = 3
627                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
628                    fstat(4, 0xEFFFF508)                            = 0
629                    fstat(3, 0xEFFFF508)                            = 0
630                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
631                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
632                    read(3, 0xEFFFD4A0, 8192)                       = 0
633                    close(4)                                        = 0
634                    close(3)                                        = 0
635                    chmod("LyXVC3.lyx", 0100644)                    = 0
636                    lseek(0, 0, SEEK_CUR)                           = 46440
637                    _exit(0)
638                 */
639
640                 // Should probably have some more error checking here.
641                 // Doing it this way, also makes the inodes stay the same.
642                 // This is still not a very good solution, in particular we
643                 // might loose the owner of the backup.
644                 FileInfo finfo(fileName());
645                 if (finfo.exist()) {
646                         mode_t fmode = finfo.getMode();
647                         struct utimbuf times = {
648                                 finfo.getAccessTime(),
649                                 finfo.getModificationTime() };
650
651                         ifstream ifs(fileName().c_str());
652                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
653                         if (ifs && ofs) {
654                                 ofs << ifs.rdbuf();
655                                 ifs.close();
656                                 ofs.close();
657                                 ::chmod(s.c_str(), fmode);
658
659                                 if (::utime(s.c_str(), &times)) {
660                                         lyxerr << "utime error." << endl;
661                                 }
662                         } else {
663                                 lyxerr << "LyX was not able to make "
664                                         "backup copy. Beware." << endl;
665                         }
666                 }
667         }
668
669         if (writeFile(fileName())) {
670                 markClean();
671                 removeAutosaveFile(fileName());
672         } else {
673                 // Saving failed, so backup is not backup
674                 if (lyxrc.make_backup) {
675                         lyx::rename(s, fileName());
676                 }
677                 return false;
678         }
679         return true;
680 }
681
682
683 bool Buffer::writeFile(string const & fname) const
684 {
685         if (read_only && (fname == fileName())) {
686                 return false;
687         }
688
689         FileInfo finfo(fname);
690         if (finfo.exist() && !finfo.writable()) {
691                 return false;
692         }
693
694         ofstream ofs(fname.c_str());
695         if (!ofs) {
696                 return false;
697         }
698
699 #ifdef HAVE_LOCALE
700         // Use the standard "C" locale for file output.
701         ofs.imbue(std::locale::classic());
702 #endif
703
704         // The top of the file should not be written by params.
705
706         // write out a comment in the top of the file
707         ofs << '#' << lyx_docversion
708             << " created this file. For more info see http://www.lyx.org/\n"
709             << "\\lyxformat " << LYX_FORMAT << "\n";
710
711         // now write out the buffer paramters.
712         params.writeFile(ofs);
713
714         ofs << "\\end_header\n";
715
716         Paragraph::depth_type depth = 0;
717
718         // this will write out all the paragraphs
719         // using recursive descent.
720         ParagraphList::iterator pit = paragraphs.begin();
721         ParagraphList::iterator pend = paragraphs.end();
722         for (; pit != pend; ++pit)
723                 pit->write(this, ofs, params, depth);
724
725         // Write marker that shows file is complete
726         ofs << "\n\\the_end" << endl;
727
728         ofs.close();
729
730         // how to check if close went ok?
731         // Following is an attempt... (BE 20001011)
732
733         // good() returns false if any error occured, including some
734         //        formatting error.
735         // bad()  returns true if something bad happened in the buffer,
736         //        which should include file system full errors.
737
738         bool status = true;
739         if (!ofs.good()) {
740                 status = false;
741 #if 0
742                 if (ofs.bad()) {
743                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
744                 } else {
745                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
746                                << endl;
747                 }
748 #endif
749         }
750
751         return status;
752 }
753
754
755 namespace {
756
757 pair<int, string> const addDepth(int depth, int ldepth)
758 {
759         int d = depth * 2;
760         if (ldepth > depth)
761                 d += (ldepth - depth) * 2;
762         return make_pair(d, string(d, ' '));
763 }
764
765 }
766
767
768 string const Buffer::asciiParagraph(Paragraph const & par,
769                                     unsigned int linelen,
770                                     bool noparbreak) const
771 {
772         ostringstream buffer;
773         Paragraph::depth_type depth = 0;
774         int ltype = 0;
775         Paragraph::depth_type ltype_depth = 0;
776         bool ref_printed = false;
777 //      if (!par->previous()) {
778 #if 0
779         // begins or ends a deeper area ?
780         if (depth != par->params().depth()) {
781                 if (par->params().depth() > depth) {
782                         while (par->params().depth() > depth) {
783                                 ++depth;
784                         }
785                 } else {
786                         while (par->params().depth() < depth) {
787                                 --depth;
788                         }
789                 }
790         }
791 #else
792         depth = par.params().depth();
793 #endif
794
795         // First write the layout
796         string const & tmp = par.layout()->name();
797         if (compare_no_case(tmp, "itemize") == 0) {
798                 ltype = 1;
799                 ltype_depth = depth + 1;
800         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
801                 ltype = 2;
802                 ltype_depth = depth + 1;
803         } else if (contains(ascii_lowercase(tmp), "ection")) {
804                 ltype = 3;
805                 ltype_depth = depth + 1;
806         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
807                 ltype = 4;
808                 ltype_depth = depth + 1;
809         } else if (compare_ascii_no_case(tmp, "description") == 0) {
810                 ltype = 5;
811                 ltype_depth = depth + 1;
812         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
813                 ltype = 6;
814                 ltype_depth = 0;
815         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
816                 ltype = 7;
817                 ltype_depth = 0;
818         } else {
819                 ltype = 0;
820                 ltype_depth = 0;
821         }
822
823         /* maybe some vertical spaces */
824
825         /* the labelwidthstring used in lists */
826
827         /* some lines? */
828
829         /* some pagebreaks? */
830
831         /* noindent ? */
832
833         /* what about the alignment */
834
835         // linelen <= 0 is special and means we don't have paragraph breaks
836
837         string::size_type currlinelen = 0;
838
839         if (!noparbreak) {
840                 if (linelen > 0)
841                         buffer << "\n\n";
842
843                 buffer << string(depth * 2, ' ');
844                 currlinelen += depth * 2;
845
846                 //--
847                 // we should probably change to the paragraph language in the
848                 // gettext here (if possible) so that strings are outputted in
849                 // the correct language! (20012712 Jug)
850                 //--
851                 switch (ltype) {
852                 case 0: // Standard
853                 case 4: // (Sub)Paragraph
854                 case 5: // Description
855                         break;
856                 case 6: // Abstract
857                         if (linelen > 0) {
858                                 buffer << _("Abstract") << "\n\n";
859                                 currlinelen = 0;
860                         } else {
861                                 string const abst = _("Abstract: ");
862                                 buffer << abst;
863                                 currlinelen += abst.length();
864                         }
865                         break;
866                 case 7: // Bibliography
867                         if (!ref_printed) {
868                                 if (linelen > 0) {
869                                         buffer << _("References") << "\n\n";
870                                         currlinelen = 0;
871                                 } else {
872                                         string const refs = _("References: ");
873                                         buffer << refs;
874                                         currlinelen += refs.length();
875                                 }
876
877                                 ref_printed = true;
878                         }
879                         break;
880                 default:
881                 {
882                         string const parlab = par.params().labelString();
883                         buffer << parlab << ' ';
884                         currlinelen += parlab.length() + 1;
885                 }
886                 break;
887
888                 }
889         }
890
891         if (!currlinelen) {
892                 pair<int, string> p = addDepth(depth, ltype_depth);
893                 buffer << p.second;
894                 currlinelen += p.first;
895         }
896
897         // this is to change the linebreak to do it by word a bit more
898         // intelligent hopefully! (only in the case where we have a
899         // max linelength!) (Jug)
900
901         string word;
902
903         for (pos_type i = 0; i < par.size(); ++i) {
904                 char c = par.getUChar(params, i);
905                 switch (c) {
906                 case Paragraph::META_INSET:
907                 {
908                         Inset const * inset = par.getInset(i);
909                         if (inset) {
910                                 if (linelen > 0) {
911                                         buffer << word;
912                                         currlinelen += word.length();
913                                         word.erase();
914                                 }
915                                 if (inset->ascii(this, buffer, linelen)) {
916                                         // to be sure it breaks paragraph
917                                         currlinelen += linelen;
918                                 }
919                         }
920                 }
921                 break;
922
923                 default:
924                         if (c == ' ') {
925                                 if (linelen > 0 &&
926                                     currlinelen + word.length() > linelen - 10) {
927                                         buffer << "\n";
928                                         pair<int, string> p = addDepth(depth, ltype_depth);
929                                         buffer << p.second;
930                                         currlinelen = p.first;
931                                 }
932
933                                 buffer << word << ' ';
934                                 currlinelen += word.length() + 1;
935                                 word.erase();
936
937                         } else {
938                                 if (c != '\0') {
939                                         word += c;
940                                 } else {
941                                         lyxerr[Debug::INFO] <<
942                                                 "writeAsciiFile: NULL char in structure." << endl;
943                                 }
944                                 if ((linelen > 0) &&
945                                         (currlinelen + word.length()) > linelen)
946                                 {
947                                         buffer << "\n";
948
949                                         pair<int, string> p =
950                                                 addDepth(depth, ltype_depth);
951                                         buffer << p.second;
952                                         currlinelen = p.first;
953                                 }
954                         }
955                         break;
956                 }
957         }
958         buffer << word;
959         return STRCONV(buffer.str());
960 }
961
962
963 void Buffer::writeFileAscii(string const & fname, int linelen)
964 {
965         ofstream ofs(fname.c_str());
966         if (!ofs) {
967                 string const file = MakeDisplayPath(fname, 50);
968 #if USE_BOOST_FORMAT
969                 boost::format fmt(_("Could not save the document\n%1$s."));
970                 fmt % file;
971                 string text = fmt.str();
972 #else
973                 string text = _("Could not save the document\n");
974                 text += file + ".";
975 #endif
976                 Alert::error(_("Could not save document"), text);
977                 return;
978         }
979         writeFileAscii(ofs, linelen);
980 }
981
982
983 void Buffer::writeFileAscii(ostream & os, int linelen)
984 {
985         ParagraphList::iterator beg = paragraphs.begin();
986         ParagraphList::iterator end = paragraphs.end();
987         ParagraphList::iterator it = beg;
988         for (; it != end; ++it) {
989                 os << asciiParagraph(*it, linelen, it == beg);
990         }
991         os << "\n";
992 }
993
994
995
996 void Buffer::makeLaTeXFile(string const & fname,
997                            string const & original_path,
998                            bool nice, bool only_body, bool only_preamble)
999 {
1000         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1001
1002         ofstream ofs(fname.c_str());
1003         if (!ofs) {
1004                 string const file = MakeDisplayPath(fname, 50);
1005 #if USE_BOOST_FORMAT
1006                 boost::format fmt(_("Could not open the specified document\n%1$s."));
1007                 fmt % file;
1008                 string text = fmt.str();
1009 #else
1010                 string text = _("Could not open the specified document\n");
1011                 text += file + ".";
1012 #endif
1013                 Alert::error(_("Could not open file"), text);
1014                 return;
1015         }
1016
1017         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1018
1019         ofs.close();
1020         if (ofs.fail()) {
1021                 lyxerr << "File was not closed properly." << endl;
1022         }
1023 }
1024
1025
1026 void Buffer::makeLaTeXFile(ostream & os,
1027                            string const & original_path,
1028                            bool nice, bool only_body, bool only_preamble)
1029 {
1030         niceFile = nice; // this will be used by Insetincludes.
1031
1032         // validate the buffer.
1033         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1034         LaTeXFeatures features(params);
1035         validate(features);
1036         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1037
1038         texrow.reset();
1039         // The starting paragraph of the coming rows is the
1040         // first paragraph of the document. (Asger)
1041         texrow.start(&*(paragraphs.begin()), 0);
1042
1043         if (!only_body && nice) {
1044                 os << "%% " << lyx_docversion << " created this file.  "
1045                         "For more info, see http://www.lyx.org/.\n"
1046                         "%% Do not edit unless you really know what "
1047                         "you are doing.\n";
1048                 texrow.newline();
1049                 texrow.newline();
1050         }
1051         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1052         // There are a few differences between nice LaTeX and usual files:
1053         // usual is \batchmode and has a
1054         // special input@path to allow the including of figures
1055         // with either \input or \includegraphics (what figinsets do).
1056         // input@path is set when the actual parameter
1057         // original_path is set. This is done for usual tex-file, but not
1058         // for nice-latex-file. (Matthias 250696)
1059         if (!only_body) {
1060                 if (!nice) {
1061                         // code for usual, NOT nice-latex-file
1062                         os << "\\batchmode\n"; // changed
1063                         // from \nonstopmode
1064                         texrow.newline();
1065                 }
1066                 if (!original_path.empty()) {
1067                         string inputpath = os::external_path(original_path);
1068                         subst(inputpath, "~", "\\string~");
1069                         os << "\\makeatletter\n"
1070                             << "\\def\\input@path{{"
1071                             << inputpath << "/}}\n"
1072                             << "\\makeatother\n";
1073                         texrow.newline();
1074                         texrow.newline();
1075                         texrow.newline();
1076                 }
1077
1078                 // Write the preamble
1079                 params.writeLaTeX(os, features, texrow);
1080
1081                 if (only_preamble)
1082                         return;
1083
1084                 // make the body.
1085                 os << "\\begin{document}\n";
1086                 texrow.newline();
1087         } // only_body
1088         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1089
1090         if (!lyxrc.language_auto_begin) {
1091                 os << subst(lyxrc.language_command_begin, "$$lang",
1092                              params.language->babel())
1093                     << endl;
1094                 texrow.newline();
1095         }
1096
1097         latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1098
1099         // add this just in case after all the paragraphs
1100         os << endl;
1101         texrow.newline();
1102
1103         if (!lyxrc.language_auto_end) {
1104                 os << subst(lyxrc.language_command_end, "$$lang",
1105                              params.language->babel())
1106                     << endl;
1107                 texrow.newline();
1108         }
1109
1110         if (!only_body) {
1111                 os << "\\end{document}\n";
1112                 texrow.newline();
1113
1114                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1115         } else {
1116                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1117                                      << endl;
1118         }
1119
1120         // Just to be sure. (Asger)
1121         texrow.newline();
1122
1123         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1124         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1125                             << '.' << endl;
1126
1127         // we want this to be true outside previews (for insetexternal)
1128         niceFile = true;
1129 }
1130
1131
1132 bool Buffer::isLatex() const
1133 {
1134         return params.getLyXTextClass().outputType() == LATEX;
1135 }
1136
1137
1138 bool Buffer::isLinuxDoc() const
1139 {
1140         return params.getLyXTextClass().outputType() == LINUXDOC;
1141 }
1142
1143
1144 bool Buffer::isLiterate() const
1145 {
1146         return params.getLyXTextClass().outputType() == LITERATE;
1147 }
1148
1149
1150 bool Buffer::isDocBook() const
1151 {
1152         return params.getLyXTextClass().outputType() == DOCBOOK;
1153 }
1154
1155
1156 bool Buffer::isSGML() const
1157 {
1158         LyXTextClass const & tclass = params.getLyXTextClass();
1159
1160         return tclass.outputType() == LINUXDOC ||
1161                tclass.outputType() == DOCBOOK;
1162 }
1163
1164
1165 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1166 {
1167         ofstream ofs(fname.c_str());
1168
1169         if (!ofs) {
1170                 string const file = MakeDisplayPath(fname, 50);
1171 #if USE_BOOST_FORMAT
1172                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1173                 fmt % file;
1174                 string text = fmt.str();
1175 #else
1176                 string text = _("Could not save the specified document\n");
1177                 text += file + _(".\n");
1178 #endif
1179                 Alert::error(_("Could not save document"), text);
1180                 return;
1181         }
1182
1183         niceFile = nice; // this will be used by included files.
1184
1185         LaTeXFeatures features(params);
1186
1187         validate(features);
1188
1189         texrow.reset();
1190
1191         LyXTextClass const & tclass = params.getLyXTextClass();
1192
1193         string top_element = tclass.latexname();
1194
1195         if (!body_only) {
1196                 ofs << "<!doctype linuxdoc system";
1197
1198                 string preamble = params.preamble;
1199                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1200                          : fname;
1201                 preamble += features.getIncludedFiles(name);
1202                 preamble += features.getLyXSGMLEntities();
1203
1204                 if (!preamble.empty()) {
1205                         ofs << " [ " << preamble << " ]";
1206                 }
1207                 ofs << ">\n\n";
1208
1209                 if (params.options.empty())
1210                         sgml::openTag(ofs, 0, false, top_element);
1211                 else {
1212                         string top = top_element;
1213                         top += ' ';
1214                         top += params.options;
1215                         sgml::openTag(ofs, 0, false, top);
1216                 }
1217         }
1218
1219         ofs << "<!-- "  << lyx_docversion
1220             << " created this file. For more info see http://www.lyx.org/"
1221             << " -->\n";
1222
1223         Paragraph::depth_type depth = 0; // paragraph depth
1224         string item_name;
1225         vector<string> environment_stack(5);
1226
1227         ParagraphList::iterator pit = paragraphs.begin();
1228         ParagraphList::iterator pend = paragraphs.end();
1229         for (; pit != pend; ++pit) {
1230                 LyXLayout_ptr const & style = pit->layout();
1231                 // treat <toc> as a special case for compatibility with old code
1232                 if (pit->isInset(0)) {
1233                         Inset * inset = pit->getInset(0);
1234                         Inset::Code lyx_code = inset->lyxCode();
1235                         if (lyx_code == Inset::TOC_CODE) {
1236                                 string const temp = "toc";
1237                                 sgml::openTag(ofs, depth, false, temp);
1238                                 continue;
1239                         }
1240                 }
1241
1242                 // environment tag closing
1243                 for (; depth > pit->params().depth(); --depth) {
1244                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1245                         environment_stack[depth].erase();
1246                 }
1247
1248                 // write opening SGML tags
1249                 switch (style->latextype) {
1250                 case LATEX_PARAGRAPH:
1251                         if (depth == pit->params().depth()
1252                            && !environment_stack[depth].empty()) {
1253                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1254                                 environment_stack[depth].erase();
1255                                 if (depth)
1256                                         --depth;
1257                                 else
1258                                         ofs << "</p>";
1259                         }
1260                         sgml::openTag(ofs, depth, false, style->latexname());
1261                         break;
1262
1263                 case LATEX_COMMAND:
1264                         if (depth != 0)
1265                                 sgmlError(&*pit, 0,
1266                                           _("Error: Wrong depth for LatexType Command.\n"));
1267
1268                         if (!environment_stack[depth].empty()) {
1269                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1270                                 ofs << "</p>";
1271                         }
1272
1273                         environment_stack[depth].erase();
1274                         sgml::openTag(ofs, depth, false, style->latexname());
1275                         break;
1276
1277                 case LATEX_ENVIRONMENT:
1278                 case LATEX_ITEM_ENVIRONMENT:
1279                 case LATEX_BIB_ENVIRONMENT:
1280                 {
1281                         string const & latexname = style->latexname();
1282
1283                         if (depth == pit->params().depth()
1284                             && environment_stack[depth] != latexname) {
1285                                 sgml::closeTag(ofs, depth, false,
1286                                              environment_stack[depth]);
1287                                 environment_stack[depth].erase();
1288                         }
1289                         if (depth < pit->params().depth()) {
1290                                depth = pit->params().depth();
1291                                environment_stack[depth].erase();
1292                         }
1293                         if (environment_stack[depth] != latexname) {
1294                                 if (depth == 0) {
1295                                         sgml::openTag(ofs, depth, false, "p");
1296                                 }
1297                                 sgml::openTag(ofs, depth, false, latexname);
1298
1299                                 if (environment_stack.size() == depth + 1)
1300                                         environment_stack.push_back("!-- --");
1301                                 environment_stack[depth] = latexname;
1302                         }
1303
1304                         if (style->latexparam() == "CDATA")
1305                                 ofs << "<![CDATA[";
1306
1307                         if (style->latextype == LATEX_ENVIRONMENT) break;
1308
1309                         if (style->labeltype == LABEL_MANUAL)
1310                                 item_name = "tag";
1311                         else
1312                                 item_name = "item";
1313
1314                         sgml::openTag(ofs, depth + 1, false, item_name);
1315                 }
1316                 break;
1317
1318                 default:
1319                         sgml::openTag(ofs, depth, false, style->latexname());
1320                         break;
1321                 }
1322
1323                 simpleLinuxDocOnePar(ofs, &*pit, depth);
1324
1325                 ofs << "\n";
1326                 // write closing SGML tags
1327                 switch (style->latextype) {
1328                 case LATEX_COMMAND:
1329                         break;
1330                 case LATEX_ENVIRONMENT:
1331                 case LATEX_ITEM_ENVIRONMENT:
1332                 case LATEX_BIB_ENVIRONMENT:
1333                         if (style->latexparam() == "CDATA")
1334                                 ofs << "]]>";
1335                         break;
1336                 default:
1337                         sgml::closeTag(ofs, depth, false, style->latexname());
1338                         break;
1339                 }
1340         }
1341
1342         // Close open tags
1343         for (int i = depth; i >= 0; --i)
1344                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1345
1346         if (!body_only) {
1347                 ofs << "\n\n";
1348                 sgml::closeTag(ofs, 0, false, top_element);
1349         }
1350
1351         ofs.close();
1352         // How to check for successful close
1353
1354         // we want this to be true outside previews (for insetexternal)
1355         niceFile = true;
1356 }
1357
1358
1359 // checks, if newcol chars should be put into this line
1360 // writes newline, if necessary.
1361 namespace {
1362
1363 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1364                           string::size_type newcol)
1365 {
1366         colcount += newcol;
1367         if (colcount > lyxrc.ascii_linelen) {
1368                 os << "\n";
1369                 colcount = newcol; // assume write after this call
1370         }
1371 }
1372
1373 enum PAR_TAG {
1374         NONE=0,
1375         TT = 1,
1376         SF = 2,
1377         BF = 4,
1378         IT = 8,
1379         SL = 16,
1380         EM = 32
1381 };
1382
1383
1384 string tag_name(PAR_TAG const & pt) {
1385         switch (pt) {
1386         case NONE: return "!-- --";
1387         case TT: return "tt";
1388         case SF: return "sf";
1389         case BF: return "bf";
1390         case IT: return "it";
1391         case SL: return "sl";
1392         case EM: return "em";
1393         }
1394         return "";
1395 }
1396
1397
1398 inline
1399 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1400 {
1401         p1 = static_cast<PAR_TAG>(p1 | p2);
1402 }
1403
1404
1405 inline
1406 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1407 {
1408         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1409 }
1410
1411 } // anon
1412
1413
1414 // Handle internal paragraph parsing -- layout already processed.
1415 void Buffer::simpleLinuxDocOnePar(ostream & os,
1416         Paragraph * par,
1417         Paragraph::depth_type /*depth*/)
1418 {
1419         LyXLayout_ptr const & style = par->layout();
1420
1421         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1422
1423         // gets paragraph main font
1424         LyXFont font_old;
1425         bool desc_on;
1426         if (style->labeltype == LABEL_MANUAL) {
1427                 font_old = style->labelfont;
1428                 desc_on = true;
1429         } else {
1430                 font_old = style->font;
1431                 desc_on = false;
1432         }
1433
1434         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1435         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1436         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1437         bool is_em = false;
1438
1439         stack<PAR_TAG> tag_state;
1440         // parsing main loop
1441         for (pos_type i = 0; i < par->size(); ++i) {
1442
1443                 PAR_TAG tag_close = NONE;
1444                 list < PAR_TAG > tag_open;
1445
1446                 LyXFont const font = par->getFont(params, i, outerFont(par, paragraphs));
1447
1448                 if (font_old.family() != font.family()) {
1449                         switch (family_type) {
1450                         case LyXFont::SANS_FAMILY:
1451                                 tag_close |= SF;
1452                                 break;
1453                         case LyXFont::TYPEWRITER_FAMILY:
1454                                 tag_close |= TT;
1455                                 break;
1456                         default:
1457                                 break;
1458                         }
1459
1460                         family_type = font.family();
1461
1462                         switch (family_type) {
1463                         case LyXFont::SANS_FAMILY:
1464                                 tag_open.push_back(SF);
1465                                 break;
1466                         case LyXFont::TYPEWRITER_FAMILY:
1467                                 tag_open.push_back(TT);
1468                                 break;
1469                         default:
1470                                 break;
1471                         }
1472                 }
1473
1474                 if (font_old.series() != font.series()) {
1475                         switch (series_type) {
1476                         case LyXFont::BOLD_SERIES:
1477                                 tag_close |= BF;
1478                                 break;
1479                         default:
1480                                 break;
1481                         }
1482
1483                         series_type = font.series();
1484
1485                         switch (series_type) {
1486                         case LyXFont::BOLD_SERIES:
1487                                 tag_open.push_back(BF);
1488                                 break;
1489                         default:
1490                                 break;
1491                         }
1492
1493                 }
1494
1495                 if (font_old.shape() != font.shape()) {
1496                         switch (shape_type) {
1497                         case LyXFont::ITALIC_SHAPE:
1498                                 tag_close |= IT;
1499                                 break;
1500                         case LyXFont::SLANTED_SHAPE:
1501                                 tag_close |= SL;
1502                                 break;
1503                         default:
1504                                 break;
1505                         }
1506
1507                         shape_type = font.shape();
1508
1509                         switch (shape_type) {
1510                         case LyXFont::ITALIC_SHAPE:
1511                                 tag_open.push_back(IT);
1512                                 break;
1513                         case LyXFont::SLANTED_SHAPE:
1514                                 tag_open.push_back(SL);
1515                                 break;
1516                         default:
1517                                 break;
1518                         }
1519                 }
1520                 // handle <em> tag
1521                 if (font_old.emph() != font.emph()) {
1522                         if (font.emph() == LyXFont::ON) {
1523                                 tag_open.push_back(EM);
1524                                 is_em = true;
1525                         }
1526                         else if (is_em) {
1527                                 tag_close |= EM;
1528                                 is_em = false;
1529                         }
1530                 }
1531
1532                 list < PAR_TAG > temp;
1533                 while (!tag_state.empty() && tag_close) {
1534                         PAR_TAG k =  tag_state.top();
1535                         tag_state.pop();
1536                         os << "</" << tag_name(k) << '>';
1537                         if (tag_close & k)
1538                                 reset(tag_close,k);
1539                         else
1540                                 temp.push_back(k);
1541                 }
1542
1543                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1544                     j != temp.end(); ++j) {
1545                         tag_state.push(*j);
1546                         os << '<' << tag_name(*j) << '>';
1547                 }
1548
1549                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1550                     j != tag_open.end(); ++j) {
1551                         tag_state.push(*j);
1552                         os << '<' << tag_name(*j) << '>';
1553                 }
1554
1555                 char c = par->getChar(i);
1556
1557                 if (c == Paragraph::META_INSET) {
1558                         Inset * inset = par->getInset(i);
1559                         inset->linuxdoc(this, os);
1560                         font_old = font;
1561                         continue;
1562                 }
1563
1564                 if (style->latexparam() == "CDATA") {
1565                         // "TeX"-Mode on == > SGML-Mode on.
1566                         if (c != '\0')
1567                                 os << c;
1568                         ++char_line_count;
1569                 } else {
1570                         bool ws;
1571                         string str;
1572                         boost::tie(ws, str) = sgml::escapeChar(c);
1573                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
1574                                 // in freespacing mode, spaces are
1575                                 // non-breaking characters
1576                                 if (desc_on) {// if char is ' ' then...
1577
1578                                         ++char_line_count;
1579                                         sgmlLineBreak(os, char_line_count, 6);
1580                                         os << "</tag>";
1581                                         desc_on = false;
1582                                 } else  {
1583                                         sgmlLineBreak(os, char_line_count, 1);
1584                                         os << c;
1585                                 }
1586                         } else {
1587                                 os << str;
1588                                 char_line_count += str.length();
1589                         }
1590                 }
1591                 font_old = font;
1592         }
1593
1594         while (!tag_state.empty()) {
1595                 os << "</" << tag_name(tag_state.top()) << '>';
1596                 tag_state.pop();
1597         }
1598
1599         // resets description flag correctly
1600         if (desc_on) {
1601                 // <tag> not closed...
1602                 sgmlLineBreak(os, char_line_count, 6);
1603                 os << "</tag>";
1604         }
1605 }
1606
1607
1608 // Print an error message.
1609 void Buffer::sgmlError(ParagraphList::iterator /*par*/, int /*pos*/,
1610         string const & /*message*/) const
1611 {
1612 #ifdef WITH_WARNINGS
1613 #warning This is wrong we cannot insert an inset like this!!!
1614         // I guess this was Jose' so I explain you more or less why this
1615         // is wrong. This way you insert something in the paragraph and
1616         // don't tell it to LyXText (row rebreaking and undo handling!!!)
1617         // I deactivate this code, have a look at BufferView::insertErrors
1618         // how you should do this correctly! (Jug 20020315)
1619 #endif
1620 #if 0
1621         // insert an error marker in text
1622         InsetError * new_inset = new InsetError(message);
1623         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1624                          params.language));
1625 #endif
1626 }
1627
1628
1629 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1630 {
1631         ofstream ofs(fname.c_str());
1632         if (!ofs) {
1633                 string const file = MakeDisplayPath(fname, 50);
1634 #if USE_BOOST_FORMAT
1635                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1636                 fmt % file;
1637                 string text = fmt.str();
1638 #else
1639                 string text = _("Could not save the specified document\n");
1640                 text += file + _(".\n");
1641 #endif
1642                 Alert::error(_("Could not save document"), text);
1643                 return;
1644         }
1645
1646         niceFile = nice; // this will be used by Insetincludes.
1647
1648         LaTeXFeatures features(params);
1649         validate(features);
1650
1651         texrow.reset();
1652
1653         LyXTextClass const & tclass = params.getLyXTextClass();
1654         string top_element = tclass.latexname();
1655
1656         if (!only_body) {
1657                 ofs << "<!DOCTYPE " << top_element
1658                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1659
1660                 string preamble = params.preamble;
1661                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1662                          : fname;
1663                 preamble += features.getIncludedFiles(name);
1664                 preamble += features.getLyXSGMLEntities();
1665
1666                 if (!preamble.empty()) {
1667                         ofs << "\n [ " << preamble << " ]";
1668                 }
1669                 ofs << ">\n\n";
1670         }
1671
1672         string top = top_element;
1673         top += " lang=\"";
1674         top += params.language->code();
1675         top += '"';
1676
1677         if (!params.options.empty()) {
1678                 top += ' ';
1679                 top += params.options;
1680         }
1681         sgml::openTag(ofs, 0, false, top);
1682
1683         ofs << "<!-- DocBook file was created by " << lyx_docversion
1684             << "\n  See http://www.lyx.org/ for more information -->\n";
1685
1686         vector<string> environment_stack(10);
1687         vector<string> environment_inner(10);
1688         vector<string> command_stack(10);
1689
1690         bool command_flag = false;
1691         Paragraph::depth_type command_depth = 0;
1692         Paragraph::depth_type command_base = 0;
1693         Paragraph::depth_type cmd_depth = 0;
1694         Paragraph::depth_type depth = 0; // paragraph depth
1695
1696         string item_name;
1697         string command_name;
1698
1699         ParagraphList::iterator par = paragraphs.begin();
1700         ParagraphList::iterator pend = paragraphs.end();
1701
1702         for (; par != pend; ++par) {
1703                 string sgmlparam;
1704                 string c_depth;
1705                 string c_params;
1706                 int desc_on = 0; // description mode
1707
1708                 LyXLayout_ptr const & style = par->layout();
1709
1710                 // environment tag closing
1711                 for (; depth > par->params().depth(); --depth) {
1712                         if (environment_inner[depth] != "!-- --") {
1713                                 item_name = "listitem";
1714                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1715                                 if (environment_inner[depth] == "varlistentry")
1716                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1717                         }
1718                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1719                         environment_stack[depth].erase();
1720                         environment_inner[depth].erase();
1721                 }
1722
1723                 if (depth == par->params().depth()
1724                    && environment_stack[depth] != style->latexname()
1725                    && !environment_stack[depth].empty()) {
1726                         if (environment_inner[depth] != "!-- --") {
1727                                 item_name= "listitem";
1728                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1729                                 if (environment_inner[depth] == "varlistentry")
1730                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1731                         }
1732
1733                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1734
1735                         environment_stack[depth].erase();
1736                         environment_inner[depth].erase();
1737                 }
1738
1739                 // Write opening SGML tags.
1740                 switch (style->latextype) {
1741                 case LATEX_PARAGRAPH:
1742                         sgml::openTag(ofs, depth + command_depth,
1743                                     false, style->latexname());
1744                         break;
1745
1746                 case LATEX_COMMAND:
1747                         if (depth != 0)
1748                                 sgmlError(par, 0,
1749                                           _("Error: Wrong depth for LatexType Command.\n"));
1750
1751                         command_name = style->latexname();
1752
1753                         sgmlparam = style->latexparam();
1754                         c_params = split(sgmlparam, c_depth,'|');
1755
1756                         cmd_depth = lyx::atoi(c_depth);
1757
1758                         if (command_flag) {
1759                                 if (cmd_depth < command_base) {
1760                                         for (Paragraph::depth_type j = command_depth;
1761                                              j >= command_base; --j) {
1762                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1763                                                 ofs << endl;
1764                                         }
1765                                         command_depth = command_base = cmd_depth;
1766                                 } else if (cmd_depth <= command_depth) {
1767                                         for (int j = command_depth;
1768                                              j >= int(cmd_depth); --j) {
1769                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1770                                                 ofs << endl;
1771                                         }
1772                                         command_depth = cmd_depth;
1773                                 } else
1774                                         command_depth = cmd_depth;
1775                         } else {
1776                                 command_depth = command_base = cmd_depth;
1777                                 command_flag = true;
1778                         }
1779                         if (command_stack.size() == command_depth + 1)
1780                                 command_stack.push_back(string());
1781                         command_stack[command_depth] = command_name;
1782
1783                         // treat label as a special case for
1784                         // more WYSIWYM handling.
1785                         // This is a hack while paragraphs can't have
1786                         // attributes, like id in this case.
1787                         if (par->isInset(0)) {
1788                                 Inset * inset = par->getInset(0);
1789                                 Inset::Code lyx_code = inset->lyxCode();
1790                                 if (lyx_code == Inset::LABEL_CODE) {
1791                                         command_name += " id=\"";
1792                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1793                                         command_name += '"';
1794                                         desc_on = 3;
1795                                 }
1796                         }
1797
1798                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1799
1800                         item_name = c_params.empty() ? "title" : c_params;
1801                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1802                         break;
1803
1804                 case LATEX_ENVIRONMENT:
1805                 case LATEX_ITEM_ENVIRONMENT:
1806                         if (depth < par->params().depth()) {
1807                                 depth = par->params().depth();
1808                                 environment_stack[depth].erase();
1809                         }
1810
1811                         if (environment_stack[depth] != style->latexname()) {
1812                                 if (environment_stack.size() == depth + 1) {
1813                                         environment_stack.push_back("!-- --");
1814                                         environment_inner.push_back("!-- --");
1815                                 }
1816                                 environment_stack[depth] = style->latexname();
1817                                 environment_inner[depth] = "!-- --";
1818                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1819                         } else {
1820                                 if (environment_inner[depth] != "!-- --") {
1821                                         item_name= "listitem";
1822                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1823                                         if (environment_inner[depth] == "varlistentry")
1824                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1825                                 }
1826                         }
1827
1828                         if (style->latextype == LATEX_ENVIRONMENT) {
1829                                 if (!style->latexparam().empty()) {
1830                                         if (style->latexparam() == "CDATA")
1831                                                 ofs << "<![CDATA[";
1832                                         else
1833                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1834                                 }
1835                                 break;
1836                         }
1837
1838                         desc_on = (style->labeltype == LABEL_MANUAL);
1839
1840                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1841                         sgml::openTag(ofs, depth + 1 + command_depth,
1842                                     false, environment_inner[depth]);
1843
1844                         item_name = desc_on ? "term" : "para";
1845                         sgml::openTag(ofs, depth + 1 + command_depth,
1846                                     false, item_name);
1847                         break;
1848                 default:
1849                         sgml::openTag(ofs, depth + command_depth,
1850                                     false, style->latexname());
1851                         break;
1852                 }
1853
1854                 simpleDocBookOnePar(ofs, par, desc_on,
1855                                     depth + 1 + command_depth);
1856
1857                 string end_tag;
1858                 // write closing SGML tags
1859                 switch (style->latextype) {
1860                 case LATEX_COMMAND:
1861                         end_tag = c_params.empty() ? "title" : c_params;
1862                         sgml::closeTag(ofs, depth + command_depth,
1863                                      false, end_tag);
1864                         break;
1865                 case LATEX_ENVIRONMENT:
1866                         if (!style->latexparam().empty()) {
1867                                 if (style->latexparam() == "CDATA")
1868                                         ofs << "]]>";
1869                                 else
1870                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1871                         }
1872                         break;
1873                 case LATEX_ITEM_ENVIRONMENT:
1874                         if (desc_on == 1) break;
1875                         end_tag = "para";
1876                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1877                         break;
1878                 case LATEX_PARAGRAPH:
1879                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1880                         break;
1881                 default:
1882                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1883                         break;
1884                 }
1885         }
1886
1887         // Close open tags
1888         for (int d = depth; d >= 0; --d) {
1889                 if (!environment_stack[depth].empty()) {
1890                         if (environment_inner[depth] != "!-- --") {
1891                                 item_name = "listitem";
1892                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1893                                if (environment_inner[depth] == "varlistentry")
1894                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1895                         }
1896
1897                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1898                 }
1899         }
1900
1901         for (int j = command_depth; j >= 0 ; --j)
1902                 if (!command_stack[j].empty()) {
1903                         sgml::closeTag(ofs, j, false, command_stack[j]);
1904                         ofs << endl;
1905                 }
1906
1907         ofs << "\n\n";
1908         sgml::closeTag(ofs, 0, false, top_element);
1909
1910         ofs.close();
1911         // How to check for successful close
1912
1913         // we want this to be true outside previews (for insetexternal)
1914         niceFile = true;
1915 }
1916
1917
1918 void Buffer::simpleDocBookOnePar(ostream & os,
1919                                  ParagraphList::iterator par, int & desc_on,
1920                                  Paragraph::depth_type depth) const
1921 {
1922         bool emph_flag = false;
1923
1924         LyXLayout_ptr const & style = par->layout();
1925
1926         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1927
1928         int char_line_count = depth;
1929         //if (!style.free_spacing)
1930         //      os << string(depth,' ');
1931
1932         // parsing main loop
1933         for (pos_type i = 0; i < par->size(); ++i) {
1934                 LyXFont font = par->getFont(params, i, outerFont(par, paragraphs));
1935
1936                 // handle <emphasis> tag
1937                 if (font_old.emph() != font.emph()) {
1938                         if (font.emph() == LyXFont::ON) {
1939                                 if (style->latexparam() == "CDATA")
1940                                         os << "]]>";
1941                                 os << "<emphasis>";
1942                                 if (style->latexparam() == "CDATA")
1943                                         os << "<![CDATA[";
1944                                 emph_flag = true;
1945                         } else if (i) {
1946                                 if (style->latexparam() == "CDATA")
1947                                         os << "]]>";
1948                                 os << "</emphasis>";
1949                                 if (style->latexparam() == "CDATA")
1950                                         os << "<![CDATA[";
1951                                 emph_flag = false;
1952                         }
1953                 }
1954
1955
1956                 if (par->isInset(i)) {
1957                         Inset * inset = par->getInset(i);
1958                         // don't print the inset in position 0 if desc_on == 3 (label)
1959                         if (i || desc_on != 3) {
1960                                 if (style->latexparam() == "CDATA")
1961                                         os << "]]>";
1962                                 inset->docbook(this, os, false);
1963                                 if (style->latexparam() == "CDATA")
1964                                         os << "<![CDATA[";
1965                         }
1966                 } else {
1967                         char c = par->getChar(i);
1968                         bool ws;
1969                         string str;
1970                         boost::tie(ws, str) = sgml::escapeChar(c);
1971
1972                         if (style->pass_thru) {
1973                                 os << c;
1974                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
1975                                         os << str;
1976                         } else if (desc_on ==1) {
1977                                 ++char_line_count;
1978                                 os << "\n</term><listitem><para>";
1979                                 desc_on = 2;
1980                         } else {
1981                                 os << ' ';
1982                         }
1983                 }
1984                 font_old = font;
1985         }
1986
1987         if (emph_flag) {
1988                 if (style->latexparam() == "CDATA")
1989                         os << "]]>";
1990                 os << "</emphasis>";
1991                 if (style->latexparam() == "CDATA")
1992                         os << "<![CDATA[";
1993         }
1994
1995         // resets description flag correctly
1996         if (desc_on == 1) {
1997                 // <term> not closed...
1998                 os << "</term>\n<listitem><para>&nbsp;</para>";
1999         }
2000         if (style->free_spacing)
2001                 os << '\n';
2002 }
2003
2004
2005 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2006 // Other flags: -wall -v0 -x
2007 int Buffer::runChktex()
2008 {
2009         if (!users->text) return 0;
2010
2011         users->owner()->busy(true);
2012
2013         // get LaTeX-Filename
2014         string const name = getLatexName();
2015         string path = filePath();
2016
2017         string const org_path = path;
2018         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2019                 path = tmppath;
2020         }
2021
2022         Path p(path); // path to LaTeX file
2023         users->owner()->message(_("Running chktex..."));
2024
2025         // Remove all error insets
2026         bool const removedErrorInsets = users->removeAutoInsets();
2027
2028         // Generate the LaTeX file if neccessary
2029         makeLaTeXFile(name, org_path, false);
2030
2031         TeXErrors terr;
2032         Chktex chktex(lyxrc.chktex_command, name, filePath());
2033         int res = chktex.run(terr); // run chktex
2034
2035         if (res == -1) {
2036                 Alert::error(_("chktex failure"),
2037                         _("Could not run chktex successfully."));
2038         } else if (res > 0) {
2039                 // Insert all errors as errors boxes
2040                 users->insertErrors(terr);
2041         }
2042
2043         // if we removed error insets before we ran chktex or if we inserted
2044         // error insets after we ran chktex, this must be run:
2045         if (removedErrorInsets || res) {
2046 #warning repaint needed here, or do you mean update() ?
2047                 users->repaint();
2048                 users->fitCursor();
2049         }
2050         users->owner()->busy(false);
2051
2052         return res;
2053 }
2054
2055
2056 void Buffer::validate(LaTeXFeatures & features) const
2057 {
2058         LyXTextClass const & tclass = params.getLyXTextClass();
2059
2060         if (params.tracking_changes) {
2061                 features.require("dvipost");
2062                 features.require("color");
2063         }
2064
2065         // AMS Style is at document level
2066         if (params.use_amsmath == BufferParams::AMS_ON
2067             || tclass.provides(LyXTextClass::amsmath))
2068                 features.require("amsmath");
2069
2070         for_each(paragraphs.begin(), paragraphs.end(),
2071                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2072
2073         // the bullet shapes are buffer level not paragraph level
2074         // so they are tested here
2075         for (int i = 0; i < 4; ++i) {
2076                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2077                         int const font = params.user_defined_bullets[i].getFont();
2078                         if (font == 0) {
2079                                 int const c = params
2080                                         .user_defined_bullets[i]
2081                                         .getCharacter();
2082                                 if (c == 16
2083                                    || c == 17
2084                                    || c == 25
2085                                    || c == 26
2086                                    || c == 31) {
2087                                         features.require("latexsym");
2088                                 }
2089                         } else if (font == 1) {
2090                                 features.require("amssymb");
2091                         } else if ((font >= 2 && font <= 5)) {
2092                                 features.require("pifont");
2093                         }
2094                 }
2095         }
2096
2097         if (lyxerr.debugging(Debug::LATEX)) {
2098                 features.showStruct();
2099         }
2100 }
2101
2102
2103 vector<string> const Buffer::getLabelList() const
2104 {
2105         /// if this is a child document and the parent is already loaded
2106         /// Use the parent's list instead  [ale990407]
2107         if (!params.parentname.empty()
2108             && bufferlist.exists(params.parentname)) {
2109                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2110                 if (tmp)
2111                         return tmp->getLabelList();
2112         }
2113
2114         vector<string> label_list;
2115         for (inset_iterator it = inset_const_iterator_begin();
2116              it != inset_const_iterator_end(); ++it) {
2117                 vector<string> const l = it->getLabelList();
2118                 label_list.insert(label_list.end(), l.begin(), l.end());
2119         }
2120         return label_list;
2121 }
2122
2123
2124 // This is also a buffer property (ale)
2125 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2126 {
2127         /// if this is a child document and the parent is already loaded
2128         /// use the parent's list instead  [ale990412]
2129         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2130                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2131                 if (tmp) {
2132                         tmp->fillWithBibKeys(keys);
2133                         return;
2134                 }
2135         }
2136
2137         for (inset_iterator it = inset_const_iterator_begin();
2138                 it != inset_const_iterator_end(); ++it) {
2139                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2140                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2141                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2142                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2143                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2144                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2145                         string const key = bib.getContents();
2146                         string const opt = bib.getOptions();
2147                         string const ref; // = pit->asString(this, false);
2148                         string const info = opt + "TheBibliographyRef" + ref;
2149                         keys.push_back(pair<string, string>(key, info));
2150                 }
2151         }
2152 }
2153
2154
2155 bool Buffer::isDepClean(string const & name) const
2156 {
2157         DepClean::const_iterator it = dep_clean_.find(name);
2158         if (it == dep_clean_.end())
2159                 return true;
2160         return it->second;
2161 }
2162
2163
2164 void Buffer::markDepClean(string const & name)
2165 {
2166         dep_clean_[name] = true;
2167 }
2168
2169
2170 bool Buffer::dispatch(string const & command, bool * result)
2171 {
2172         // Split command string into command and argument
2173         string cmd;
2174         string line = ltrim(command);
2175         string const arg = trim(split(line, cmd, ' '));
2176
2177         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2178 }
2179
2180
2181 bool Buffer::dispatch(int action, string const & argument, bool * result)
2182 {
2183         bool dispatched = true;
2184
2185         switch (action) {
2186                 case LFUN_EXPORT: {
2187                         bool const tmp = Exporter::Export(this, argument, false);
2188                         if (result)
2189                                 *result = tmp;
2190                         break;
2191                 }
2192
2193                 default:
2194                         dispatched = false;
2195         }
2196         return dispatched;
2197 }
2198
2199
2200 void Buffer::resizeInsets(BufferView * bv)
2201 {
2202         /// then remove all LyXText in text-insets
2203         for_each(paragraphs.begin(), paragraphs.end(),
2204                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2205 }
2206
2207
2208 void Buffer::redraw()
2209 {
2210 #warning repaint needed here, or do you mean update() ?
2211         users->repaint();
2212         users->fitCursor();
2213 }
2214
2215
2216 void Buffer::changeLanguage(Language const * from, Language const * to)
2217 {
2218         // Take care of l10n/i18n
2219         messages_.reset(new Messages(to->code(), "/usr/local/share/locale"));
2220
2221         ParIterator end = par_iterator_end();
2222         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2223                 (*it)->changeLanguage(params, from, to);
2224 }
2225
2226
2227 bool Buffer::isMultiLingual()
2228 {
2229         ParIterator end = par_iterator_end();
2230         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2231                 if ((*it)->isMultiLingual(params))
2232                         return true;
2233
2234         return false;
2235 }
2236
2237
2238 void Buffer::inset_iterator::setParagraph()
2239 {
2240         while (pit != pend) {
2241                 it = pit->insetlist.begin();
2242                 if (it != pit->insetlist.end())
2243                         return;
2244                 ++pit;
2245         }
2246 }
2247
2248
2249 Inset * Buffer::getInsetFromID(int id_arg) const
2250 {
2251         for (inset_iterator it = inset_const_iterator_begin();
2252                  it != inset_const_iterator_end(); ++it)
2253         {
2254                 if (it->id() == id_arg)
2255                         return &(*it);
2256                 Inset * in = it->getInsetFromID(id_arg);
2257                 if (in)
2258                         return in;
2259         }
2260         return 0;
2261 }
2262
2263
2264 Paragraph * Buffer::getParFromID(int id) const
2265 {
2266         if (id < 0)
2267                 return 0;
2268
2269         // why should we allow < 0 ??
2270         //lyx::Assert(id >= 0);
2271
2272         ParConstIterator it(par_iterator_begin());
2273         ParConstIterator end(par_iterator_end());
2274
2275         for (; it != end; ++it) {
2276                 // go on then, show me how to remove
2277                 // the cast
2278                 if ((*it)->id() == id) {
2279                         return const_cast<Paragraph*>(*it);
2280                 }
2281         }
2282
2283         return 0;
2284 }
2285
2286
2287 ParIterator Buffer::par_iterator_begin()
2288 {
2289         return ParIterator(&*(paragraphs.begin()));
2290 }
2291
2292
2293 ParIterator Buffer::par_iterator_end()
2294 {
2295         return ParIterator();
2296 }
2297
2298 ParConstIterator Buffer::par_iterator_begin() const
2299 {
2300         return ParConstIterator(&*(paragraphs.begin()));
2301 }
2302
2303
2304 ParConstIterator Buffer::par_iterator_end() const
2305 {
2306         return ParConstIterator();
2307 }
2308
2309
2310
2311 void Buffer::addUser(BufferView * u)
2312 {
2313         users = u;
2314 }
2315
2316
2317 void Buffer::delUser(BufferView *)
2318 {
2319         users = 0;
2320 }
2321
2322
2323 Language const * Buffer::getLanguage() const
2324 {
2325         return params.language;
2326 }
2327
2328
2329 string const Buffer::B_(string const & l10n) const
2330 {
2331         if (messages_.get()) {
2332                 return messages_->get(l10n);
2333         }
2334         
2335         return _(l10n);
2336 }
2337
2338
2339 bool Buffer::isClean() const
2340 {
2341         return lyx_clean;
2342 }
2343
2344
2345 bool Buffer::isBakClean() const
2346 {
2347         return bak_clean;
2348 }
2349
2350
2351 void Buffer::markClean() const
2352 {
2353         if (!lyx_clean) {
2354                 lyx_clean = true;
2355                 updateTitles();
2356         }
2357         // if the .lyx file has been saved, we don't need an
2358         // autosave
2359         bak_clean = true;
2360 }
2361
2362
2363 void Buffer::markBakClean()
2364 {
2365         bak_clean = true;
2366 }
2367
2368
2369 void Buffer::setUnnamed(bool flag)
2370 {
2371         unnamed = flag;
2372 }
2373
2374
2375 bool Buffer::isUnnamed()
2376 {
2377         return unnamed;
2378 }
2379
2380
2381 void Buffer::markDirty()
2382 {
2383         if (lyx_clean) {
2384                 lyx_clean = false;
2385                 updateTitles();
2386         }
2387         bak_clean = false;
2388
2389         DepClean::iterator it = dep_clean_.begin();
2390         DepClean::const_iterator const end = dep_clean_.end();
2391
2392         for (; it != end; ++it) {
2393                 it->second = false;
2394         }
2395 }
2396
2397
2398 string const & Buffer::fileName() const
2399 {
2400         return filename_;
2401 }
2402
2403
2404 string const & Buffer::filePath() const
2405 {
2406         return filepath_;
2407 }
2408
2409
2410 bool Buffer::isReadonly() const
2411 {
2412         return read_only;
2413 }
2414
2415
2416 BufferView * Buffer::getUser() const
2417 {
2418         return users;
2419 }
2420
2421
2422 void Buffer::setParentName(string const & name)
2423 {
2424         params.parentname = name;
2425 }
2426
2427
2428 Buffer::inset_iterator::inset_iterator()
2429         : pit(0), pend(0)
2430 {}
2431
2432
2433 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2434         : pit(p), pend(e)
2435 {
2436         setParagraph();
2437 }
2438
2439
2440 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2441 {
2442         if (pit != pend) {
2443                 ++it;
2444                 if (it == pit->insetlist.end()) {
2445                         ++pit;
2446                         setParagraph();
2447                 }
2448         }
2449         return *this;
2450 }
2451
2452
2453 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2454 {
2455         inset_iterator tmp = *this;
2456         ++*this;
2457         return tmp;
2458 }
2459
2460
2461 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2462 {
2463         return *it.getInset();
2464 }
2465
2466
2467 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2468 {
2469         return it.getInset();
2470 }
2471
2472
2473 Paragraph * Buffer::inset_iterator::getPar()
2474 {
2475         return &(*pit);
2476 }
2477
2478
2479 lyx::pos_type Buffer::inset_iterator::getPos() const
2480 {
2481         return it.getPos();
2482 }
2483
2484
2485 bool operator==(Buffer::inset_iterator const & iter1,
2486                 Buffer::inset_iterator const & iter2)
2487 {
2488         return iter1.pit == iter2.pit
2489                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2490 }
2491
2492
2493 bool operator!=(Buffer::inset_iterator const & iter1,
2494                 Buffer::inset_iterator const & iter2)
2495 {
2496         return !(iter1 == iter2);
2497 }