]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
5e61cb1116b572b46ea952422e7d46a312ad8ba7
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19
20 #include <string>
21 #include <vector>
22
23
24 namespace lyx {
25
26 class BufferParams;
27 class EmbeddedFiles;
28 class ErrorItem;
29 class ErrorList;
30 class FuncRequest;
31 class Inset;
32 class Font;
33 class Format;
34 class Lexer;
35 class LyXRC;
36 class Text;
37 class LyXVC;
38 class LaTeXFeatures;
39 class Language;
40 class MacroData;
41 class OutputParams;
42 class Paragraph;
43 class ParConstIterator;
44 class ParIterator;
45 class ParagraphList;
46 class TeXErrors;
47 class TexRow;
48 class TocBackend;
49 class Undo;
50
51 namespace frontend {
52 class GuiBufferDelegate;
53 class WorkAreaManager;
54 }
55
56 namespace support {
57 class FileName;
58 class FileNameList;
59 }
60
61 /** The buffer object.
62  * This is the buffer object. It contains all the informations about
63  * a document loaded into LyX.
64  * The buffer object owns the Text (wrapped in an InsetText), which
65  * contains the individual paragraphs of the document.
66  *
67  *
68  * I am not sure if the class is complete or
69  * minimal, probably not.
70  * \author Lars Gullik Bjønnes
71  */
72 class Buffer {
73 public:
74         /// What type of log will \c getLogName() return?
75         enum LogType {
76                 latexlog, ///< LaTeX log
77                 buildlog  ///< Literate build log
78         };
79
80         /// Result of \c readFile()
81         enum ReadStatus {
82                 failure, ///< The file could not be read
83                 success, ///< The file could not be read
84                 wrongversion ///< The version of the file does not match ours
85         };
86
87
88         /// Method to check if a file is externally modified, used by 
89         /// isExternallyModified()
90         /**
91          * timestamp is fast but inaccurate. For example, the granularity
92          * of timestamp on a FAT filesystem is 2 second. Also, various operations
93          * may touch the timestamp of a file even when its content is unchanged.
94          *
95          * checksum is accurate but slow, which can be a problem when it is 
96          * frequently used, or used for a large file on a slow (network) file
97          * system.
98          *
99          * FIXME: replace this method with support/FileMonitor.
100          */
101         enum CheckMethod {
102                 checksum_method,  ///< Use file checksum
103                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
104         };
105         
106         /** Constructor
107             \param file
108             \param b  optional \c false by default
109         */
110         explicit Buffer(std::string const & file, bool b = false);
111
112         /// Destructor
113         ~Buffer();
114
115         /** High-level interface to buffer functionality.
116             This function parses a command string and executes it
117         */
118         bool dispatch(std::string const & command, bool * result = 0);
119
120         /// Maybe we know the function already by number...
121         bool dispatch(FuncRequest const & func, bool * result = 0);
122
123         /// Load the autosaved file.
124         void loadAutoSaveFile();
125
126         /// read a new document from a string
127         bool readString(std::string const &);
128         /// load a new file
129         bool readFile(support::FileName const & filename);
130
131         /// read the header, returns number of unknown tokens
132         int readHeader(Lexer & lex);
133
134         /** Reads a file without header.
135             \param par if != 0 insert the file.
136             \return \c false if file is not completely read.
137         */
138         bool readDocument(Lexer &);
139
140         ///
141         void insertStringAsLines(ParagraphList & plist,
142                 pit_type &, pos_type &,
143                 Font const &, docstring const &, bool);
144         ///
145         ParIterator getParFromID(int id) const;
146         /// do we have a paragraph with this id?
147         bool hasParWithID(int id) const;
148
149         ///
150         frontend::WorkAreaManager & workAreaManager() const;
151
152         /** Save file.
153             Takes care of auto-save files and backup file if requested.
154             Returns \c true if the save is successful, \c false otherwise.
155         */
156         bool save() const;
157
158         /// Write document to stream. Returns \c false if unsuccesful.
159         bool write(std::ostream &) const;
160         /// Write file. Returns \c false if unsuccesful.
161         bool writeFile(support::FileName const &) const;
162
163   /// Loads LyX file \c filename into buffer, *  and \return success 
164         bool loadLyXFile(support::FileName const & s);
165
166         /// Fill in the ErrorList with the TeXErrors
167         void bufferErrors(TeXErrors const &, ErrorList &) const;
168
169         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
170         bool makeLaTeXFile(support::FileName const & filename,
171                            std::string const & original_path,
172                            OutputParams const &,
173                            bool output_preamble = true,
174                            bool output_body = true) const;
175         /** Export the buffer to LaTeX.
176             If \p os is a file stream, and params().inputenc is "auto" or
177             "default", and the buffer contains text in different languages
178             with more than one encoding, then this method will change the
179             encoding associated to \p os. Therefore you must not call this
180             method with a string stream if the output is supposed to go to a
181             file. \code
182             odocfstream ofs;
183             ofs.open("test.tex");
184             writeLaTeXSource(ofs, ...);
185             ofs.close();
186             \endcode is NOT equivalent to \code
187             odocstringstream oss;
188             writeLaTeXSource(oss, ...);
189             odocfstream ofs;
190             ofs.open("test.tex");
191             ofs << oss.str();
192             ofs.close();
193             \endcode
194          */
195         void writeLaTeXSource(odocstream & os,
196                            std::string const & original_path,
197                            OutputParams const &,
198                            bool output_preamble = true,
199                            bool output_body = true) const;
200         ///
201         void makeDocBookFile(support::FileName const & filename,
202                              OutputParams const & runparams_in,
203                              bool only_body = false) const;
204         ///
205         void writeDocBookSource(odocstream & os, std::string const & filename,
206                              OutputParams const & runparams_in,
207                              bool only_body = false) const;
208         /// returns the main language for the buffer (document)
209         Language const * language() const;
210         /// get l10n translated to the buffers language
211         docstring const B_(std::string const & l10n) const;
212
213         ///
214         int runChktex();
215         /// return true if the main lyx file does not need saving
216         bool isClean() const;
217         ///
218         bool isBakClean() const;
219         ///
220         bool isDepClean(std::string const & name) const;
221
222         /// whether or not disk file has been externally modified
223         bool isExternallyModified(CheckMethod method) const;
224
225         /// save timestamp and checksum of the given file.
226         void saveCheckSum(support::FileName const & file) const;
227
228         /// mark the main lyx file as not needing saving
229         void markClean() const;
230
231         ///
232         void markBakClean() const;
233
234         ///
235         void markDepClean(std::string const & name);
236
237         ///
238         void setUnnamed(bool flag = true);
239
240         ///
241         bool isUnnamed() const;
242
243         /// Mark this buffer as dirty.
244         void markDirty();
245
246         /// Returns the buffer's filename. It is always an absolute path.
247         support::FileName fileName() const;
248
249         /// Returns the buffer's filename. It is always an absolute path.
250         std::string absFileName() const;
251
252         /// Returns the the path where the buffer lives.
253         /// It is always an absolute path.
254         std::string filePath() const;
255
256         /** A transformed version of the file name, adequate for LaTeX.
257             \param no_path optional if \c true then the path is stripped.
258         */
259         std::string latexName(bool no_path = true) const;
260
261         /// Get thee name and type of the log.
262         std::string logName(LogType * type = 0) const;
263
264         /// Change name of buffer. Updates "read-only" flag.
265         void setFileName(std::string const & newfile);
266
267         /// Set document's parent Buffer.
268         void setParent(Buffer const *);
269         Buffer const * parent();
270
271         /** Get the document's master (or \c this if this is not a
272             child document)
273          */
274         Buffer const * masterBuffer() const;
275
276         /// Is buffer read-only?
277         bool isReadonly() const;
278
279         /// Set buffer read-only flag
280         void setReadonly(bool flag = true);
281
282         /// returns \c true if the buffer contains a LaTeX document
283         bool isLatex() const;
284         /// returns \c true if the buffer contains a DocBook document
285         bool isDocBook() const;
286         /// returns \c true if the buffer contains a Wed document
287         bool isLiterate() const;
288
289         /** Validate a buffer for LaTeX.
290             This validates the buffer, and returns a struct for use by
291             #makeLaTeX# and others. Its main use is to figure out what
292             commands and packages need to be included in the LaTeX file.
293             It (should) also check that the needed constructs are there
294             (i.e. that the \refs points to coresponding \labels). It
295             should perhaps inset "error" insets to help the user correct
296             obvious mistakes.
297         */
298         void validate(LaTeXFeatures &) const;
299
300         /// Update the cache with all bibfiles in use (including bibfiles
301         /// of loaded child documents).
302         void updateBibfilesCache() const;
303         /// Return the cache with all bibfiles in use (including bibfiles
304         /// of loaded child documents).
305         support::FileNameList const & getBibfilesCache() const;
306         ///
307         void getLabelList(std::vector<docstring> &) const;
308
309         ///
310         void changeLanguage(Language const * from, Language const * to);
311
312         ///
313         bool isMultiLingual() const;
314
315         ///
316         BufferParams & params();
317         BufferParams const & params() const;
318
319         /** The list of paragraphs.
320             This is a linked list of paragraph, this list holds the
321             whole contents of the document.
322          */
323         ParagraphList & paragraphs();
324         ParagraphList const & paragraphs() const;
325
326         /// LyX version control object.
327         LyXVC & lyxvc();
328         LyXVC const & lyxvc() const;
329
330         /// Where to put temporary files.
331         std::string const & temppath() const;
332
333         /// Used when typesetting to place errorboxes.
334         TexRow const & texrow() const;
335
336         ///
337         ParIterator par_iterator_begin();
338         ///
339         ParConstIterator par_iterator_begin() const;
340         ///
341         ParIterator par_iterator_end();
342         ///
343         ParConstIterator par_iterator_end() const;
344
345         /** \returns true only when the file is fully loaded.
346          *  Used to prevent the premature generation of previews
347          *  and by the citation inset.
348          */
349         bool isFullyLoaded() const;
350         /// Set by buffer_funcs' newFile.
351         void setFullyLoaded(bool);
352
353         /// Our main text (inside the top InsetText)
354         Text & text() const;
355
356         /// Our top InsetText
357         Inset & inset() const;
358
359         //
360         // Macro handling
361         //
362         /// Collect macros in paragraphs
363         void updateMacros();
364         /// Look for macro defined before par (or in the master buffer)
365         bool hasMacro(docstring const & name, Paragraph const & par) const;
366         /// Look for macro defined anywhere in the buffer (or in the master buffer)
367         bool hasMacro(docstring const & name) const;
368         /// Return macro defined before par (or in the master buffer)
369         MacroData const & getMacro(docstring const & name, Paragraph const & par) const;
370         /// Return macro defined anywhere in the buffer (or in the master buffer)
371         MacroData const & getMacro(docstring const & name) const;
372
373         /// Replace the inset contents for insets which InsetCode is equal
374         /// to the passed \p inset_code.
375         void changeRefsIfUnique(docstring const & from, docstring const & to,
376                 InsetCode code);
377
378         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
379         /// including preamble
380         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
381                 bool full_source);
382
383         /// Access to error list.
384         /// This method is used only for GUI visualisation of Buffer related
385         /// errors (like parsing or LateX compilation). This method is const
386         /// because modifying the returned ErrorList does not touch the document
387         /// contents.
388         ErrorList & errorList(std::string const & type) const;
389
390         /// The Toc backend.
391         /// This is useful only for screen visualisation of the Buffer. This
392         /// method is const because modifying this backend does not touch
393         /// the document contents.
394         TocBackend & tocBackend() const;
395         
396         //@{
397         EmbeddedFiles & embeddedFiles();
398         EmbeddedFiles const & embeddedFiles() const;
399         //@}
400
401         Undo & undo();
402        
403         /// This function is called when the buffer is changed.
404         void changed() const;
405         /// This function is called when the buffer structure is changed.
406         void structureChanged() const;
407         /// This function is called when some parsing error shows up.
408         void errors(std::string const & err) const;
409         /// This function is called when the buffer busy status change.
410         void setBusy(bool on) const;
411         /// This function is called when the buffer readonly status change.
412         void setReadOnly(bool on) const;
413         /// Update window titles of all users.
414         void updateTitles() const;
415         /// Reset autosave timers for all users.
416         void resetAutosaveTimers() const;
417         ///
418         void message(docstring const & msg) const;
419
420         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
421
422         ///
423         void autoSave() const;
424         ///
425         void loadChildDocuments() const;
426         ///
427         void resetChildDocuments(bool close_them) const;
428
429         /// return the format of the buffer on a string
430         std::string bufferFormat() const;
431
432         ///
433         bool doExport(std::string const & format, bool put_in_tempdir,
434                 std::string & result_file) const;
435         ///
436         bool doExport(std::string const & format, bool put_in_tempdir) const;
437         ///
438         bool preview(std::string const & format) const;
439         ///
440         bool isExportable(std::string const & format) const;
441         ///
442         std::vector<Format const *> exportableFormats(bool only_viewable) const;
443
444 private:
445   /// 
446         bool readFileHelper(support::FileName const & s);
447         ///
448         std::vector<std::string> backends() const;
449         /** Inserts a file into a document
450             \return \c false if method fails.
451         */
452         ReadStatus readFile(Lexer &, support::FileName const & filename,
453                             bool fromString = false);
454
455         /// Use the Pimpl idiom to hide the internals.
456         class Impl;
457         /// The pointer never changes although *pimpl_'s contents may.
458         Impl * const d;
459
460         frontend::GuiBufferDelegate * gui_;
461 };
462
463
464 } // namespace lyx
465
466 #endif