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