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