Browse Source

Merge branch 'master' of git://repo.or.cz/org-mode

Dan Davison 15 years ago
parent
commit
20256569ab

+ 2 - 0
Makefile

@@ -107,6 +107,7 @@ LISPF      = 	org.el			\
 		org-rmail.el		\
 		org-src.el		\
 		org-table.el		\
+		org-taskjuggler.el	\
 		org-timer.el		\
 		org-vm.el		\
 		org-w3m.el              \
@@ -388,6 +389,7 @@ lisp/org-remember.elc:	lisp/org.el
 lisp/org-rmail.elc:	lisp/org.el
 lisp/org-src.elc:	lisp/org-macs.el lisp/org-compat.el
 lisp/org-table.elc:	lisp/org.el
+lisp/org-taskjuggler.elc: lisp/org.el lisp/org-exp.el
 lisp/org-timer.elc:	lisp/org.el
 lisp/org-vm.elc:	lisp/org.el
 lisp/org-w3m.elc:	lisp/org.el

+ 2 - 1
ORGWEBPAGE/index.org

@@ -117,7 +117,8 @@ a look at our [[http://orgmode.org/worg/org-quotes.php][collected quotes about O
 #+ATTR_HTML: style="float:right;"
   [[http://mobileorg.ncogni.to/][http://mobileorg.ncogni.to/images/screenshot-browse.png]]
 
-- <2010-05-21 Fri>: iPhone App [[http://mobileorg.ncogni.to/][MobileOrg]] version 1.2 available
+- <2010-06-06 Sun>: iPhone App [[http://mobileorg.ncogni.to/][MobileOrg]] version 1.3 introduces
+  DropBox support, for vastly easier setup.
 - <2010-04-06 Tue>: Release 6.35
 - <2010-01-10 Sun>: Release 6.34
 

+ 8 - 92
ORGWEBPAGE/todo.org

@@ -41,25 +41,19 @@ something.
 
 ** Structure
 *** TODO Get rid of all the \r instances, which were used only for XEmacs.
-*** TODO proper visibility cycling for items
+*** WISH proper visibility cycling for items
     Make them not hide the text after the final list item.
     This is not trivial, we cannot usenormal outline stuff,
-    needs a separate implementaiton.
-*** WISH Inline TODO entries
-    A way to put a TODO entry without starting a new section.
+    needs a separate implementation.
 
 ** Agenda issues
-*** WISH Make more modes changeable from the agenda
-    These could be made available for toggling, just like
-    follow-mode. Examples:
-    - org-agenda-todo-list-sublevels
-    - org-tags-match-list-sublevels
-    - org-agenda-todo-ignore-scheduled
 
 ** Links
 *** WISH Variable of standard links for completion with C-c C-l
     Or something like that, to make standard links fast.
+
 *** IDEA Find all links to a specific file
+
 *** IDEA Make info HTML links work for links to Info files
     Info links of course only work inside Emacs.  However, many info
     documents are on the web, so the HTML exporter could try to be
@@ -70,11 +64,6 @@ something.
     question is, is this URL going to be stable so that it makes sense
     to actually put this into org.el?
 
-*** TODO Remove irretrievable links from /published/ HTML output
-    This is on David's table, and he will hopefully integrate a
-    mechanism for this into org-publish.el.  The discussion about this
-    was started by [[http://thread.gmane.org/gmane.emacs.orgmode/281][Austin Frank]]
-
 *** TODO Document the character protection in links
     I don't think this is really covered anywhere.
     Maybe we also should protect characters in the visible part, to
@@ -90,80 +79,18 @@ something.
     @4=.....
 
 *** WISH Make a variable that current line should be recomputed always
-    in each table, skipping headers of course.
-
-*** BUG When computing in a narrowed column, aligning may go wrong.
-    Computing changes fields and does not yet see correctly if the column
-    width has changed, in the case of a narrowed column.
+    In each table.  Skipping headers of course.
 
-** Compatibility issues
-*** Emacs 21 compatibility
-    This is being phased out.  Almost everything works under Emacs 21,
-    but in the future I will make little effort to support it.
-
-*** XEmacs compatibility
 
 ** Exporting
-*** IDEA Convert links to footnotes for ASCII export.
-    But the question is:  where should these footnotes be placed?
 
 ** Publishing
 
-We need to simplify the publishing options.  Here are some of the
-options for publishing projects
-
-*** Publishing options
-
-:`:base-directory'       Directory containing publishing source files
-:
-:`:publishing-directory' Directory (possibly remote) where output files
-:                        will be published.
-:
-:`:preparation-function' Function called before starting publishing
-:                        process, for example to run `make' for updating
-:                        files to be published.
-:
-:`:base-extension'  Extension (without the dot!) of source files.  This
-:                   actually is a regular expression.
-:
-:`:exclude'         Regular expression to match file names that should
-:                   not be published, even though they have been selected
-:                   on the basis of their extension.
-:
-:`:include'         List of files to be included regardless of
-:                   `:base-extension' and `:exclude'.
-:
-:`:publishing-function' Function executing the publication of a file.
-:                       This may also be a list of functions, which will
-:                       all be called in turn.
-:
-:`:link-validation-function'   Function to validate links
-:
-:`:auto-index'      When non-nil, publish an index during
-:                   org-publish-current-project or org-publish-all.
-:
-:`:index-filename'  Filename for output of index. Defaults to `index.org'
-:                   (which becomes `index.html').
-:
-:`:index-title'     Title of index page. Defaults to name of file.
-:
-:`:index-function'  Plug-in function to use for generation of index.
-:                   Defaults to `org-publish-org-index', which generates
-:                   a plain list of links to all files in the project.
-
-*** TODO Document the :recursive option
-*** QUESTION Does anyone use the index related options
-*** QUESTION Remove :base-extension and only use :include
-*** WISH Simple interaction between :include :exclude :recursive
-*** QUESTION Use an export-directory option per file?
-
-For now we use publishing-directory but this is not consistent with the
-convention of using "publishing" when there is a /project/ to publish.
+
+*** TODO Document the :recursive option for org-publish
 
 ** Miscellaneous Stuff
 *** BUG Comments cannot be filled
-*** WISH Inlining of images in Org-mode files
-*** TODO Fixup outline-magic.el, so that it can be used.
     
 *** TODO Use the new argument of bibtex-url
     Roland Winkler was kind enough to implement a new argument to the
@@ -180,6 +107,7 @@ convention of using "publishing" when there is a /project/ to publish.
 *** Priorities
     Here is some information about priorities, which is not yet
     documented.  Actually, I am not sur if the list here is correct
+    either
 **** QUOTE Priorities
     TODO entries: 1 or 1,2,...
     DEADLINE is 10-ddays, i.e. it is 10 on the due day
@@ -195,22 +123,10 @@ convention of using "publishing" when there is a /project/ to publish.
 
     Priority * 1000
 
-*** INCONSISTENCY: items don't grow/shrink due to promotion.
-    In plain lists, multiple demote/promote commands executed directly
-    after each other don't change the scope of the command - the
-    initially selected text continues to be selected.  This is
-    inconsistent with the behavior of outline sections, were the subtree
-    for promotion/demotion is newly defined after each command.  Which
-    convention is better?  Should this be consistent between trees and
-    plain lists?
-
 *** QUESTION grep on directory does not yet work.
     I am actually not sure, I might have addressed this already, but
     my memory is failing me.  Needs some checking.
 
-
-* Archive
-** Archived Tasks
 * COMMENT HTML style specifications
 
 # Local Variables: 

+ 34 - 0
contrib/babel/library-of-babel.org

@@ -35,6 +35,40 @@
   The raw Org-mode text of this file can be downloaded at
   [[repofile:contrib/babel/library-of-babel.org][library-of-babel.org]]
 
+* Simple
+A collection of simple utility functions
+
+#+srcname: echo
+#+begin_src emacs-lisp :var input="echo'd"
+  input
+#+end_src
+
+* File I/O
+** reading and writing files
+Read the contents of the file at =path= into a string.
+#+srcname: read
+#+begin_src emacs-lisp :var path=""
+  (with-temp-filebuffer path
+    (buffer-substring (point-min) (point-max)))
+#+end_src
+
+Read the lines of the file at =path= into a list.
+#+srcname: read-lines
+#+begin_src emacs-lisp :var path=""
+  (split-string
+   (with-temp-filebuffer path
+     (buffer-substring (point-min) (point-max))))
+#+end_src
+
+Write =data= to a file at =path=.  If =data= is a list, then write it
+as a table in traditional Org-mode table syntax.
+#+srcname: write
+#+begin_src emacs-lisp :var data="" :var path=""
+  (with-temp-file path
+    (org-babel-insert-result data))
+  nil
+#+end_src
+
 * Plotting code
 
 ** R

+ 27 - 16
contrib/babel/lisp/langs/org-babel-ruby.el

@@ -65,13 +65,15 @@ called by `org-babel-execute-src-block'."
          (result-params (third processed-params))
          (result-type (fourth processed-params))
          (full-body (org-babel-expand-body:ruby
-                     body params processed-params)) ;; then the source block body
+                     body params processed-params))
          (result (org-babel-ruby-evaluate session full-body result-type)))
     (or (cdr (assoc :file params))
         (org-babel-reassemble-table
          result
-         (org-babel-pick-name (nth 4 processed-params) (cdr (assoc :colnames params)))
-         (org-babel-pick-name (nth 5 processed-params) (cdr (assoc :rownames params)))))))
+         (org-babel-pick-name (nth 4 processed-params)
+			      (cdr (assoc :colnames params)))
+         (org-babel-pick-name (nth 5 processed-params)
+			      (cdr (assoc :rownames params)))))))
 
 (defun org-babel-prep-session:ruby (session params)
   "Prepare SESSION according to the header arguments specified in PARAMS."
@@ -129,9 +131,10 @@ Emacs-lisp table, otherwise return the results as a string."
   "If there is not a current inferior-process-buffer in SESSION
 then create.  Return the initialized session."
   (unless (string= session "none")
-    (let ((session-buffer (save-window-excursion (run-ruby nil session) (current-buffer))))
+    (let ((session-buffer (save-window-excursion
+			    (run-ruby nil session) (current-buffer))))
       (if (org-babel-comint-buffer-livep session-buffer)
-          session-buffer
+	  (progn (sit-for .25) session-buffer)
         (sit-for .5)
         (org-babel-ruby-initiate-session session)))))
 
@@ -175,24 +178,30 @@ last statement in BODY, as elisp."
            (with-temp-buffer
              (insert body)
              ;; (message "buffer=%s" (buffer-string)) ;; debugging
-             (org-babel-shell-command-on-region (point-min) (point-max) "ruby" 'current-buffer 'replace)
+             (org-babel-shell-command-on-region
+	      (point-min) (point-max) "ruby" 'current-buffer 'replace)
              (buffer-string)))
           (value
-           (let* ((tmp-file (make-temp-file "ruby-functional-results")) exit-code
+           (let* ((tmp-file (make-temp-file "ruby-functional-results"))
+		  exit-code
 		  (stderr
 		   (with-temp-buffer
 		     (insert (format (if (member "pp" result-params)
 					 org-babel-ruby-pp-wrapper-method
-				       org-babel-ruby-wrapper-method) body tmp-file))
-		     ;; (message "buffer=%s" (buffer-string)) ;; debugging
+				       org-babel-ruby-wrapper-method)
+				     body tmp-file))
 		     (setq exit-code
-			   (org-babel-shell-command-on-region (point-min) (point-max) "ruby" nil 'replace (current-buffer)))
+			   (org-babel-shell-command-on-region
+			    (point-min) (point-max) "ruby"
+			    nil 'replace (current-buffer)))
 		     (buffer-string))))
 	     (if (> exit-code 0) (org-babel-error-notify exit-code stderr))
              (let ((raw (with-temp-buffer
-			  (insert-file-contents (org-babel-maybe-remote-file tmp-file))
+			  (insert-file-contents
+			   (org-babel-maybe-remote-file tmp-file))
 			  (buffer-string))))
-               (if (or (member "code" result-params) (member "pp" result-params))
+               (if (or (member "code" result-params)
+		       (member "pp" result-params))
                    raw
                  (org-babel-ruby-table-or-string raw)))))))
     ;; comint session evaluation
@@ -203,11 +212,13 @@ last statement in BODY, as elisp."
                             org-babel-ruby-pp-last-value-eval
                           org-babel-ruby-last-value-eval)
                    org-babel-ruby-eoe-indicator) "\n"))
-           (raw (org-babel-comint-with-output buffer org-babel-ruby-eoe-indicator t
+           (raw (org-babel-comint-with-output
+		    buffer org-babel-ruby-eoe-indicator t
                   (insert full-body) (comint-send-input nil t)))
-           (results (cdr (member org-babel-ruby-eoe-indicator
-                                 (reverse (mapcar #'org-babel-ruby-read-string
-                                                  (mapcar #'org-babel-trim raw)))))))
+           (results (cdr (member
+			  org-babel-ruby-eoe-indicator
+			  (reverse (mapcar #'org-babel-ruby-read-string
+					   (mapcar #'org-babel-trim raw)))))))
       (case result-type
         (output (mapconcat #'identity (reverse (cdr results)) "\n"))
         (value

+ 24 - 9
contrib/babel/lisp/org-babel-comint.el

@@ -52,38 +52,53 @@ body inside the protection of `save-window-excursion' and
        (set-buffer ,buffer)
        ,@body)))
 
-(defmacro org-babel-comint-with-output (buffer eoe-indicator remove-echo &rest body)
+(defmacro org-babel-comint-with-output
+  (buffer eoe-indicator remove-echo &rest body)
   "Evaluate BODY in BUFFER, wait until EOE-INDICATOR appears in
 output, then return all process output.  This ensures that the
 filter is removed in case of an error or user `keyboard-quit'
 during execution of body."
   (declare (indent 3))
   `(org-babel-comint-in-buffer ,buffer
-     (let ((string-buffer ""))
+     (let ((string-buffer "") dangling-text)
        (flet ((my-filt (text) (setq string-buffer (concat string-buffer text))))
          ;; setup filter
          (add-hook 'comint-output-filter-functions 'my-filt)
          (unwind-protect
              (progn
-               ;; pass FULL-BODY to process
+               ;; got located, and save dangling text
                (goto-char (process-mark (get-buffer-process (current-buffer))))
+	       (let ((start (point))
+		     (end (point-max)))
+		 (setq dangling-text (buffer-substring start end))
+		 (delete-region start end))
+	       ;; pass FULL-BODY to process
                ,@body
                ;; wait for end-of-evaluation indicator
                (while (progn
                         (goto-char comint-last-input-end)
                         (not (save-excursion
-			       (and (re-search-forward comint-prompt-regexp nil t)
-				    (re-search-forward (regexp-quote ,eoe-indicator) nil t)))))
+			       (and (re-search-forward
+				     comint-prompt-regexp nil t)
+				    (re-search-forward
+				     (regexp-quote ,eoe-indicator) nil t)))))
                  (accept-process-output (get-buffer-process (current-buffer)))
-                 ;; ;; thought this would allow async background running, but I was wrong...
-                 ;; (run-with-timer .5 .5 'accept-process-output (get-buffer-process (current-buffer)))
-                 ))
+                 ;; thought the following this would allow async
+                 ;; background running, but I was wrong...
+                 ;; (run-with-timer .5 .5 'accept-process-output
+		 ;; 		 (get-buffer-process (current-buffer)))
+                 )
+	       ;; replace cut dangling text
+	       (goto-char (process-mark (get-buffer-process (current-buffer))))
+	       (insert dangling-text))
            ;; remove filter
            (remove-hook 'comint-output-filter-functions 'my-filt)))
        ;; remove echo'd FULL-BODY from input
        (if (and ,remove-echo
 		(string-match
-		 (replace-regexp-in-string "\n" "\r\n" (regexp-quote ,full-body)) string-buffer))
+		 (replace-regexp-in-string
+		  "\n" "[\r\n]+" (regexp-quote ,full-body))
+		 string-buffer))
            (setq raw (substring string-buffer (match-end 0))))
        (split-string string-buffer comint-prompt-regexp))))
 

+ 86 - 41
contrib/babel/lisp/org-babel-exp.el

@@ -76,7 +76,16 @@ none ----- do not display either code or results upon export"
   (when (member (first headers) org-babel-interpreters)
     (save-excursion
       (goto-char (match-beginning 0))
-      (org-babel-exp-do-export (org-babel-get-src-block-info) 'block))))
+      (let* ((info (org-babel-get-src-block-info))
+	     (params (third info)))
+	;; expand noweb references in the original file
+	(setf (second info)
+	      (if (and (cdr (assoc :noweb params))
+		       (string= "yes" (cdr (assoc :noweb params))))
+		  (org-babel-expand-noweb-references
+		   info (get-file-buffer org-current-export-file))
+		(second info)))
+	(org-babel-exp-do-export info 'block)))))
 
 (defun org-babel-exp-inline-src-blocks (start end)
   "Process inline src blocks between START and END for export.
@@ -88,10 +97,32 @@ options and are taken from `org-babel-defualt-inline-header-args'."
     (while (and (< (point) end)
                 (re-search-forward org-babel-inline-src-block-regexp end t))
       (let* ((info (save-match-data (org-babel-parse-inline-src-block-match)))
-             (replacement (save-match-data
-                            (org-babel-exp-do-export info 'inline))))
-        (setq end (+ end (- (length replacement) (length (match-string 1)))))
-        (replace-match replacement t t nil 1)))))
+	     (params (third info))
+	     (replacement
+	      (save-match-data
+		(if (org-babel-in-example-or-verbatim)
+		    (buffer-substring (match-beginning 0) (match-end 0))
+		  ;; expand noweb references in the original file
+		  (setf (second info)
+			(if (and (cdr (assoc :noweb params))
+				 (string= "yes" (cdr (assoc :noweb params))))
+			    (org-babel-expand-noweb-references
+			     info (get-file-buffer org-current-export-file))
+			  (second info)))
+		  (org-babel-exp-do-export info 'inline)))))
+	(setq end (+ end (- (length replacement) (length (match-string 1)))))
+	(replace-match replacement t t nil 1)))))
+
+(defun org-babel-in-example-or-verbatim ()
+  "Return true if the point is currently in an escaped portion of
+an org-mode buffer code which should be treated as normal
+org-mode text."
+  (or (org-in-indented-comment-line) 
+      (save-excursion
+	(save-match-data
+	  (goto-char (point-at-bol))
+	  (looking-at "[ \t]*:[ \t]")))
+      (org-in-regexps-block-p "^[ \t]*#\\+begin_src" "^[ \t]*#\\+end_src")))
 
 (defun org-babel-exp-lob-one-liners (start end)
   "Process #+lob (Library of Babel) calls between START and END for export.
@@ -104,35 +135,44 @@ options are taken from `org-babel-default-header-args'."
       (while (and (< (point) end)
 		  (re-search-forward org-babel-lob-one-liner-regexp nil t))
 	(setq replacement
-	      (save-match-data
-		(org-babel-exp-do-export
-		 (list "emacs-lisp" "results"
-		       (org-babel-merge-params
-			org-babel-default-header-args
-			(org-babel-parse-header-arguments
-			 (org-babel-clean-text-properties
-			  (concat ":var results="
-				  (mapconcat #'identity
-					     (org-babel-lob-get-info) " "))))))
-		 'lob)))
+	      (let ((lob-info (org-babel-lob-get-info)))
+		(save-match-data
+		  (org-babel-exp-do-export
+		   (list "emacs-lisp" "results"
+			 (org-babel-merge-params
+			  org-babel-default-header-args
+			  (org-babel-parse-header-arguments
+			   (org-babel-clean-text-properties
+			    (concat ":var results="
+				    (mapconcat #'identity
+					       (butlast lob-info) " ")))))
+			 (car (last lob-info)))
+		   'lob))))
 	(setq end (+ end (- (length replacement) (length (match-string 0)))))
 	(replace-match replacement t t)))))
 
 (defun org-babel-exp-do-export (info type)
   "Return a string containing the exported content of the current
 code block respecting the value of the :exports header argument."
-  (case (intern (or (cdr (assoc :exports (third info))) "code"))
-    ('none "")
-    ('code (org-babel-exp-code info type))
-    ('results (org-babel-exp-results info type))
-    ('both (concat (org-babel-exp-code info type)
-                   "\n\n"
-                   (org-babel-exp-results info type)))))
+  (flet ((silently () (let ((session (cdr (assoc :session (third info)))))
+			(when (and session
+				   (not (equal "none" session))
+				   (not (assoc :noeval (third info))))
+			  (org-babel-exp-results info type 'silent))))
+	 (clean () (org-babel-remove-result info)))
+    (case (intern (or (cdr (assoc :exports (third info))) "code"))
+      ('none (silently) (clean) "")
+      ('code (silently) (clean) (org-babel-exp-code info type))
+      ('results (org-babel-exp-results info type))
+      ('both (concat (org-babel-exp-code info type)
+		     "\n\n"
+		     (org-babel-exp-results info type))))))
 
 (defun org-babel-exp-code (info type)
   "Return the code the current code block in a manner suitable
 for exportation by org-mode.  This function is called by
-`org-babel-exp-do-export'."
+`org-babel-exp-do-export'.  The code block will not be
+evaluated."
   (let ((lang (first info))
         (body (second info))
         (switches (fourth info))
@@ -165,10 +205,12 @@ for exportation by org-mode.  This function is called by
 		   call-line))
           ((t (format ": %s\n" call-line)))))))))
 
-(defun org-babel-exp-results (info type)
+(defun org-babel-exp-results (info type &optional silent)
   "Return the results of the current code block in a manner
 suitable for exportation by org-mode.  This function is called by
-`org-babel-exp-do-export'."
+`org-babel-exp-do-export'.  The code block will be evaluated.
+Optional argument SILENT can be used to inhibit insertion of
+results into the buffer."
   (let ((lang (first info))
 	(body (second info))
 	(params
@@ -189,28 +231,31 @@ suitable for exportation by org-mode.  This function is called by
         (let ((raw (org-babel-execute-src-block
                     nil info '((:results . "silent"))))
               (result-params (split-string (cdr (assoc :results params)))))
-          (cond ;; respect the value of the :results header argument
-           ((member "file" result-params)
-            (org-babel-result-to-file raw))
-           ((or (member "raw" result-params) (member "org" result-params))
-            (format "%s" raw))
-           ((member "code" result-params)
-            (format "src_%s{%s}" lang raw))
-           (t
-            (if (stringp raw)
-		(if (= 0 (length raw)) "=(no results)="
-		  (format "=%s=" raw))
-	      (format "=%S=" raw))))))
+          (unless silent
+	    (cond ;; respect the value of the :results header argument
+	     ((member "file" result-params)
+	      (org-babel-result-to-file raw))
+	     ((or (member "raw" result-params) (member "org" result-params))
+	      (format "%s" raw))
+	     ((member "code" result-params)
+	      (format "src_%s{%s}" lang raw))
+	     (t
+	      (if (stringp raw)
+		  (if (= 0 (length raw)) "=(no results)="
+		    (format "%s" raw))
+		(format "%S" raw)))))))
       ('block
           (org-babel-execute-src-block
-           nil nil (org-babel-merge-params params '((:results . "replace"))))
+	   nil info (org-babel-merge-params
+		     params `((:results . ,(if silent "silent" "replace")))))
         "")
       ('lob
        (save-excursion
 	 (re-search-backward org-babel-lob-one-liner-regexp nil t)
 	 (org-babel-execute-src-block
-	  nil (list lang body (org-babel-merge-params
-			       params '((:results . "replace"))))) "")))))
+	  nil info (org-babel-merge-params
+		    params `((:results . ,(if silent "silent" "replace")))))
+	 "")))))
 
 (provide 'org-babel-exp)
 ;;; org-babel-exp.el ends here

+ 10 - 8
contrib/babel/lisp/org-babel-lob.el

@@ -59,9 +59,9 @@ add files to this list use the `org-babel-lob-ingest' command."
   function. If you change the value of this variable then your
   files may become unusable by other org-babel users, and vice
   versa.")
-  
+
 (defconst org-babel-lob-one-liner-regexp
-  (concat "^[ \t]*#\\+\\(?:"
+  (concat "^\\([ \t]*\\)#\\+\\(?:"
 	  (mapconcat #'regexp-quote org-babel-lob-call-aliases "\\|")
 	  "\\):[ \t]+\\([^\(\)\n]+\\)\(\\([^\n]*\\)\)[ \t]*\\([^\n]*\\)")
   "Regexp to match calls to predefined source block functions")
@@ -92,19 +92,21 @@ the word 'call'."
     (save-excursion
       (beginning-of-line 1)
       (if (looking-at org-babel-lob-one-liner-regexp)
-          (mapcar #'org-babel-clean-text-properties 
-		  (list (format "%s(%s)" (match-string 1) (match-string 2))
-			(match-string 3)))))))
+          (append (mapcar #'org-babel-clean-text-properties 
+			  (list (format "%s(%s)" (match-string 2) (match-string 3))
+				(match-string 4)))
+		  (list (length (match-string 1))))))))
   
 (defun org-babel-lob-execute (info)
   (let ((params (org-babel-merge-params
 		 org-babel-default-header-args
+		 (org-babel-params-from-buffer)
                  (org-babel-params-from-properties)
 		 (org-babel-parse-header-arguments
 		  (org-babel-clean-text-properties
-		   (concat ":var results=" (mapconcat #'identity info " ")))))))
-    ;; (message "lob-params=%S" params) ;; debugging
-    (org-babel-execute-src-block nil (list "emacs-lisp" "results" params))))
+		   (concat ":var results=" (mapconcat #'identity (butlast info) " ")))))))
+    (org-babel-execute-src-block
+     nil (list "emacs-lisp" "results" params nil nil (third info)))))
 
 (provide 'org-babel-lob)
 ;;; org-babel-lob.el ends here

+ 44 - 42
contrib/babel/lisp/org-babel-ref.el

@@ -120,47 +120,49 @@ return nil."
         (setq split-file (match-string 1 ref))
         (setq split-ref (match-string 2 ref))
         (find-file split-file) (setq ref split-ref))
-      (goto-char (point-min))
-      (if (let ((result_regexp (concat "^#\\+\\(TBLNAME\\|RESNAME\\|RESULTS\\):[ \t]*"
-                                       (regexp-quote ref) "[ \t]*$"))
-                (regexp (concat org-babel-source-name-regexp
-                                (regexp-quote ref) "\\(\(.*\)\\)?" "[ \t]*$")))
-            ;; goto ref in the current buffer
-            (or (and (not args)
-                     (or (re-search-forward result_regexp nil t)
-                         (re-search-backward result_regexp nil t)))
-                (re-search-forward regexp nil t)
-                (re-search-backward regexp nil t)
-                ;; check the Library of Babel
-                (setq lob-info (cdr (assoc (intern ref) org-babel-library-of-babel)))))
-          (unless lob-info (goto-char (match-beginning 0)))
-        ;; ;; TODO: allow searching for names in other buffers
-        ;; (setq id-loc (org-id-find ref 'marker)
-        ;;       buffer (marker-buffer id-loc)
-        ;;       loc (marker-position id-loc))
-        ;; (move-marker id-loc nil)
-        (progn (message (format "reference '%s' not found in this buffer" ref))
-               (error (format "reference '%s' not found in this buffer" ref))))
-      (if lob-info
-          (setq type 'lob)
-        (while (not (setq type (org-babel-ref-at-ref-p)))
-          (forward-line 1)
-          (beginning-of-line)
-          (if (or (= (point) (point-min)) (= (point) (point-max)))
-              (error "reference not found"))))
-      (setq params (org-babel-merge-params params args '((:results . "silent"))))
-      (setq result
-	    (case type
-	      ('results-line (org-babel-read-result))
-	      ('table (org-babel-read-table))
-              ('file (org-babel-read-file))
-	      ('source-block (org-babel-execute-src-block nil nil params))
-	      ('lob (org-babel-execute-src-block nil lob-info params))))
-      (if (symbolp result)
-          (format "%S" result)
-        (if (and index (listp result))
-            (org-babel-ref-index-list index result)
-          result)))))
+      (save-restriction
+	(widen)
+	(goto-char (point-min))
+	(if (let ((result_regexp (concat "^[ \t]*#\\+\\(TBLNAME\\|RESNAME\\|RESULTS\\):[ \t]*"
+					 (regexp-quote ref) "[ \t]*$"))
+		  (regexp (concat org-babel-source-name-regexp
+				  (regexp-quote ref) "\\(\(.*\)\\)?" "[ \t]*$")))
+	      ;; goto ref in the current buffer
+	      (or (and (not args)
+		       (or (re-search-forward result_regexp nil t)
+			   (re-search-backward result_regexp nil t)))
+		  (re-search-forward regexp nil t)
+		  (re-search-backward regexp nil t)
+		  ;; check the Library of Babel
+		  (setq lob-info (cdr (assoc (intern ref) org-babel-library-of-babel)))))
+	    (unless lob-info (goto-char (match-beginning 0)))
+	  ;; ;; TODO: allow searching for names in other buffers
+	  ;; (setq id-loc (org-id-find ref 'marker)
+	  ;;       buffer (marker-buffer id-loc)
+	  ;;       loc (marker-position id-loc))
+	  ;; (move-marker id-loc nil)
+	  (progn (message (format "reference '%s' not found in this buffer" ref))
+		 (error (format "reference '%s' not found in this buffer" ref))))
+	(if lob-info
+	    (setq type 'lob)
+	  (while (not (setq type (org-babel-ref-at-ref-p)))
+	    (forward-line 1)
+	    (beginning-of-line)
+	    (if (or (= (point) (point-min)) (= (point) (point-max)))
+		(error "reference not found"))))
+	(setq params (org-babel-merge-params params args '((:results . "silent"))))
+	(setq result
+	      (case type
+		('results-line (org-babel-read-result))
+		('table (org-babel-read-table))
+		('file (org-babel-read-file))
+		('source-block (org-babel-execute-src-block nil nil params))
+		('lob (org-babel-execute-src-block nil lob-info params))))
+	(if (symbolp result)
+	    (format "%S" result)
+	  (if (and index (listp result))
+	      (org-babel-ref-index-list index result)
+	    result))))))
 
 (defun org-babel-ref-index-list (index lis)
   "Return the subset of LIS indexed by INDEX.  If INDEX is
@@ -211,7 +213,7 @@ which case the entire range is returned."
 of the supported reference types are found.  Supported reference
 types are tables and source blocks."
   (cond ((org-at-table-p) 'table)
-        ((looking-at "^#\\+BEGIN_SRC") 'source-block)
+        ((looking-at "^[ \t]*#\\+BEGIN_SRC") 'source-block)
         ((looking-at org-bracket-link-regexp) 'file)
         ((looking-at org-babel-result-regexp) 'results-line)))
 

+ 2 - 1
contrib/babel/lisp/org-babel-tangle.el

@@ -255,7 +255,8 @@ form
 					 "no")
                               (fifth spec)))))
       (insert-comment (format "[[%s][%s]]" (org-link-escape link) source-name))
-      (insert (format "\n%s\n" (org-babel-chomp body)))
+      (insert (format "\n%s\n" (replace-regexp-in-string
+				"^," "" (org-babel-chomp body))))
       (insert-comment (format "%s ends here" source-name)))))
 
 (provide 'org-babel-tangle)

+ 159 - 94
contrib/babel/lisp/org-babel.el

@@ -46,7 +46,9 @@ then run `org-babel-execute-src-block'."
 then run `org-babel-expand-src-block'."
   (interactive)
   (let ((info (org-babel-get-src-block-info)))
-    (if info (progn (org-babel-expand-src-block current-prefix-arg info) t) nil)))
+    (if info
+	(progn (org-babel-expand-src-block current-prefix-arg info) t)
+      nil)))
 
 (defadvice org-edit-special (around org-babel-prep-session-for-edit activate)
   "Prepare the current source block's session according to it's
@@ -75,7 +77,9 @@ to `org-open-at-point'."
 then run `org-babel-load-in-session'."
   (interactive)
   (let ((info (org-babel-get-src-block-info)))
-    (if info (progn (org-babel-load-in-session current-prefix-arg info) t) nil)))
+    (if info
+	(progn (org-babel-load-in-session current-prefix-arg info) t)
+      nil)))
 
 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
 
@@ -89,7 +93,8 @@ then run `org-babel-pop-to-session'."
 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
 
 (defconst org-babel-header-arg-names
-  '(cache cmdline colnames dir exports file noweb results session tangle var)
+  '(cache cmdline colnames dir exports file noweb results
+	  session tangle var noeval)
   "Common header arguments used by org-babel.  Note that
 individual languages may define their own language specific
 header arguments as well.")
@@ -103,6 +108,9 @@ header arguments as well.")
   '((:session . "none") (:results . "silent") (:exports . "results"))
   "Default arguments to use when evaluating an inline source block.")
 
+(defvar org-babel-current-buffer-properties)
+(make-variable-buffer-local 'org-babel-current-buffer-properties)
+
 (defvar org-babel-src-block-regexp nil
   "Regexp used to test when inside of a org-babel src-block")
 
@@ -145,19 +153,19 @@ can not be resolved.")
   (set-default var value)
   (setq
    org-babel-src-block-regexp
-   (concat "^[ \t]*#\\+begin_src[ \t]+\\("       ;; (1)   lang
+   (concat "^\\([ \t]*\\)#\\+begin_src[ \t]+\\(" ;; (1) indentation (2)   lang
            (mapconcat 'regexp-quote value "\\|")
            "\\)[ \t]*"
-           "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)" ;; (2)   switches
-           "\\([^\n]*\\)\n"                      ;; (3)   header arguments
-           "\\([^\000]+?\n\\)[ \t]*#\\+end_src"));; (4)   body
+           "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)" ;; (3)   switches
+           "\\([^\n]*\\)\n"                      ;; (4)   header arguments
+           "\\([^\000]+?\n\\)[ \t]*#\\+end_src"));; (5)   body
   (setq org-babel-inline-src-block-regexp
 	(concat "[ \f\t\n\r\v]\\(src_"                ;; (1)   replacement target
 		"\\("                                 ;; (2)   lang
 		(mapconcat 'regexp-quote value "\\|")
 		"\\)"
-                "\\(\\|\\[\\(.*\\)\\]\\)"             ;; (3,4) (unused, headers)
-                "{\\([^\f\n\r\v]+\\)}"                ;; (5)   body
+                "\\(\\|\\[\\(.*?\\)\\]\\)"            ;; (3,4) (unused, headers)
+                "{\\([^\f\n\r\v]+?\\)}"               ;; (5)   body
 		"\\)")))
 
 (defun org-babel-add-interpreter (interpreter)
@@ -210,7 +218,6 @@ Optionally supply a value for PARAMS which will be merged with
 the header arguments specified at the front of the source code
 block."
   (interactive)
-  ;; (message "supplied params=%S" params) ;; debugging
   (let* ((info (or info (org-babel-get-src-block-info)))
          (lang (first info))
 	 (params (setf (third info)
@@ -225,7 +232,8 @@ block."
          (body (setf (second info)
 		     (if (and (cdr (assoc :noweb params))
                               (string= "yes" (cdr (assoc :noweb params))))
-                         (org-babel-expand-noweb-references info) (second info))))
+                         (org-babel-expand-noweb-references info)
+		       (second info))))
          (result-params (split-string (or (cdr (assoc :results params)) "")))
          (result-type (cond ((member "output" result-params) 'output)
 			    ((member "value" result-params) 'value)
@@ -237,6 +245,7 @@ block."
 	 (call-process-region-original
 	  (if (boundp 'call-process-region-original) call-process-region-original
 	    (symbol-function 'call-process-region)))
+	 (indent (car (last info)))
          result)
     (unwind-protect
         (flet ((call-process-region (&rest args)
@@ -257,7 +266,7 @@ block."
                                       (not (listp result)))
                                  (list (list result))
                                result)))
-            (org-babel-insert-result result result-params info new-hash)
+            (org-babel-insert-result result result-params info new-hash indent)
             (run-hooks 'org-babel-after-execute-hook)
             result))
       (setq call-process-region 'call-process-region-original))))
@@ -272,7 +281,6 @@ org-babel-expand-body:lang function." body)
   "Expand the current source code block according to it's header
 arguments, and pop open the results in a preview buffer."
   (interactive)
-  ;; (message "supplied params=%S" params) ;; debugging
   (let* ((info (or info (org-babel-get-src-block-info)))
          (lang (first info))
 	 (params (setf (third info)
@@ -349,7 +357,8 @@ results already exist."
       (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
                      (progn (org-babel-execute-src-block)
                             (org-babel-where-is-src-block-result))))
-      (end-of-line 1) (forward-char 1)
+      (end-of-line 1)
+      (while (looking-at "[\n\r\t\f ]") (forward-char 1))
       ;; open the results
       (if (looking-at org-bracket-link-regexp)
           ;; file results
@@ -384,45 +393,52 @@ the current buffer."
   "Call `org-babel-execute-src-block' on every source block in
 the current subtree."
   (interactive "P")
-  (save-excursion
-    (org-narrow-to-subtree)
-    (org-babel-execute-buffer)
-    (widen)))
+  (save-restriction
+    (save-excursion
+      (org-narrow-to-subtree)
+      (org-babel-execute-buffer)
+      (widen))))
 
 (defun org-babel-get-src-block-info (&optional header-vars-only)
   "Get information of the current source block.
 Returns a list
- (language body header-arguments-alist switches name function-args).
+ (language body header-arguments-alist switches name function-args indent).
 Unless HEADER-VARS-ONLY is non-nil, any variable
 references provided in 'function call style' (i.e. in a
 parenthesised argument list following the src block name) are
 added to the header-arguments-alist."
-  (let ((case-fold-search t) head info args)
+  (let ((case-fold-search t) head info args indent)
     (if (setq head (org-babel-where-is-src-block-head))
         (save-excursion
 	  (goto-char head)
 	  (setq info (org-babel-parse-src-block-match))
+	  (setq indent (car (last info)))
+	  (setq info (butlast info))
 	  (forward-line -1)
-	  (when (looking-at
-                 (concat org-babel-source-name-regexp
-                         "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
-	    (setq info (append info (list (org-babel-clean-text-properties
-                                           (match-string 2)))))
-	    ;; Note that e.g. "name()" and "name( )" result in ((:var . "")).
-	    ;; We maintain that behaviour, and the resulting non-nil sixth
-	    ;; element is relied upon in org-babel-exp-code to detect
-	    ;; a functional-style block in those cases. However,
-	    ;; "name" without any parentheses would result in the same
-	    ;; thing, so we explicitly avoid that.
-	    (if (setq args (match-string 4))
-                (setq info
-                      (append info (list
-                                    (mapcar (lambda (ref) (cons :var ref))
-                                            (org-babel-ref-split-args args))))))
-	    (unless header-vars-only
-	      (setf (third info)
-		    (org-babel-merge-params (sixth info) (third info)))))
-	  info)
+	  (if (looking-at
+	       (concat org-babel-source-name-regexp
+		       "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
+	      (progn
+		(setq info (append info (list (org-babel-clean-text-properties
+					       (match-string 2)))))
+		;; Note that e.g. "name()" and "name( )" result in
+		;; ((:var . "")).  We maintain that behaviour, and the
+		;; resulting non-nil sixth element is relied upon in
+		;; org-babel-exp-code to detect a functional-style
+		;; block in those cases. However, "name" without any
+		;; parentheses would result in the same thing, so we
+		;; explicitly avoid that.
+		(if (setq args (match-string 4))
+		    (setq info
+			  (append info (list
+					(mapcar
+					 (lambda (ref) (cons :var ref))
+					 (org-babel-ref-split-args args))))))
+		(unless header-vars-only
+		  (setf (third info)
+			(org-babel-merge-params (sixth info) (third info)))))
+	    (setq info (append info (list nil nil))))
+	  (append info (list indent)))
       (if (save-excursion ;; inline source block
             (re-search-backward "[ \f\t\n\r\v]" nil t)
             (looking-at org-babel-inline-src-block-regexp))
@@ -478,7 +494,7 @@ added as the last element of the kill ring.  This can be called
 with C-c C-c."
   (interactive)
   (let ((hash (car (delq nil (mapcar
-                               (lambda (ol) (overlay-get ol 'babel-hash))
+			      (lambda (ol) (overlay-get ol 'babel-hash))
                               (overlays-at (or point (point))))))))
     (when hash (kill-new hash) (message hash))))
 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
@@ -557,7 +573,7 @@ with C-c C-c."
 ;; Remove overlays when changing major mode
 (add-hook 'org-mode-hook
 	  (lambda () (org-add-hook 'change-major-mode-hook
-				   'org-babel-show-result-all 'append 'local)))
+			      'org-babel-show-result-all 'append 'local)))
 
 (defmacro org-babel-map-source-blocks (file &rest body)
   "Evaluate BODY forms on each source-block in FILE."
@@ -597,11 +613,26 @@ may be specified in the properties of the current outline entry."
 		 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
 		 (and (boundp sym) (eval sym))))))))))
 
+(defun org-babel-params-from-buffer ()
+  "Return an association list of any source block params which
+may be specified at the top of the current buffer."
+  (or org-babel-current-buffer-properties
+      (setq org-babel-current-buffer-properties
+	    (save-excursion
+	      (save-restriction
+		(widen)
+		(goto-char (point-min))
+		(when (re-search-forward
+		       (org-make-options-regexp (list "BABEL")) nil t)
+		  (org-babel-parse-header-arguments
+		   (org-match-string-no-properties 2))))))))
+
 (defun org-babel-parse-src-block-match ()
-  (let* ((lang (org-babel-clean-text-properties (match-string 1)))
+  (let* ((block-indentation (length (match-string 1)))
+	 (lang (org-babel-clean-text-properties (match-string 2)))
          (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
-	 (switches (match-string 2))
-         (body (org-babel-clean-text-properties (match-string 4)))
+	 (switches (match-string 3))
+         (body (org-babel-clean-text-properties (match-string 5)))
 	 (preserve-indentation (or org-src-preserve-indentation
 				   (string-match "-i\\>" switches))))
     (list lang
@@ -613,11 +644,13 @@ may be specified in the properties of the current outline entry."
               (buffer-string)))
 	  (org-babel-merge-params
 	   org-babel-default-header-args
+	   (org-babel-params-from-buffer)
            (org-babel-params-from-properties lang)
 	   (if (boundp lang-headers) (eval lang-headers) nil)
 	   (org-babel-parse-header-arguments
-            (org-babel-clean-text-properties (or (match-string 3) ""))))
-	  switches)))
+            (org-babel-clean-text-properties (or (match-string 4) ""))))
+	  switches
+	  block-indentation)))
 
 (defun org-babel-parse-inline-src-block-match ()
   (let* ((lang (org-babel-clean-text-properties (match-string 2)))
@@ -627,6 +660,7 @@ may be specified in the properties of the current outline entry."
            (org-babel-clean-text-properties (match-string 5)))
           (org-babel-merge-params
            org-babel-default-inline-header-args
+	   (org-babel-params-from-buffer)
            (org-babel-params-from-properties lang)
            (if (boundp lang-headers) (eval lang-headers) nil)
            (org-babel-parse-header-arguments
@@ -814,7 +848,7 @@ buffer or nil if no such result exists."
                    "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
       (beginning-of-line 0) (point))))
 
-(defun org-babel-where-is-src-block-result (&optional insert info hash)
+(defun org-babel-where-is-src-block-result (&optional insert info hash indent)
   "Return the point at the beginning of the result of the current
 source block.  Specifically at the beginning of the results line.
 If no result exists for this block then create a results line
@@ -822,7 +856,8 @@ following the source block."
   (save-excursion
     (let* ((on-lob-line (progn (beginning-of-line 1)
 			       (looking-at org-babel-lob-one-liner-regexp)))
-	   (name (if on-lob-line (first (org-babel-lob-get-info))
+	   (name (if on-lob-line
+		     (first (org-babel-lob-get-info))
 		   (fifth (or info (org-babel-get-src-block-info)))))
 	   (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
       (when head (goto-char head))
@@ -843,10 +878,16 @@ following the source block."
                             (goto-char end)
 			    (if (looking-at "[\n\r]")
                                 (forward-char 1) (insert "\n"))
-                            (insert (concat "#+results"
-                                            (when hash (concat "["hash"]"))
-                                            ":"
-                                            (when name (concat " " name)) "\n"))
+                            (insert (concat
+				     (if indent
+					 (mapconcat
+					  (lambda (el) " ")
+					  (number-sequence 1 indent) "")
+				       "")
+				     "#+results"
+				     (when hash (concat "["hash"]"))
+				     ":"
+				     (when name (concat " " name)) "\n"))
                             (beginning-of-line 0)
                             (if hash (org-babel-hide-hash)) t)))
                (point))))))
@@ -858,13 +899,13 @@ following the source block."
      ((org-at-table-p) (org-babel-read-table))
      ((looking-at org-bracket-link-regexp) (org-babel-read-link))
      ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
-     ((looking-at ": ")
+     ((looking-at "^[ \t]*: ")
       (setq result-string
 	    (org-babel-trim
 	     (mapconcat (lambda (line)
                           (if (and (> (length line) 1)
-                                   (string= ": " (substring line 0 2)))
-                              (substring line 2)
+                                   (string-match "^[ \t]*: \\(.+\\)" line))
+                              (match-string 1 line)
                             line))
 			(split-string
 			 (buffer-substring
@@ -896,7 +937,7 @@ link is a file path it is expanded using `expand-file-name'."
            (expand-file-name (match-string 2 raw))))
      (t raw))))
 
-(defun org-babel-insert-result (result &optional result-params info hash)
+(defun org-babel-insert-result (result &optional result-params info hash indent)
   "Insert RESULT into the current buffer after the end of the
 current source block.  With optional argument RESULT-PARAMS
 controls insertion of results in the org-mode file.
@@ -934,38 +975,50 @@ code ---- the results are extracted in the syntax of the source
         (when (member "file" result-params)
           (setq result (org-babel-result-to-file result))))
     (unless (listp result) (setq result (format "%S" result))))
-  (if (and result-params (member "replace" result-params)
-           (not (member "silent" result-params)))
-      (org-babel-remove-result info))
   (if (= (length result) 0)
       (if (member "value" result-params)
 	  (message "No result returned by source block")
 	(message "Source block produced no output"))
     (if (and result-params (member "silent" result-params))
-        (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
-               result)
+        (progn
+	  (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
+	  result)
       (when (and (stringp result) ;; ensure results end in a newline
                  (not (or (string-equal (substring result -1) "\n")
                           (string-equal (substring result -1) "\r"))))
         (setq result (concat result "\n")))
       (save-excursion
-	(let ((existing-result (org-babel-where-is-src-block-result t info hash))
+	(let ((existing-result (org-babel-where-is-src-block-result
+				t info hash indent))
 	      (results-switches
-               (cdr (assoc :results_switches (third info)))) beg)
-	  (when existing-result (goto-char existing-result) (forward-line 1))
+               (cdr (assoc :results_switches (third info))))
+	      beg end)
+	  (when existing-result
+	    (goto-char existing-result)
+	    (save-excursion
+	      (re-search-forward "#" nil t)
+	      (setq indent (- (current-column) 1)))
+	    (forward-line 1)
+	    (setq beg (point))
+	    (cond
+	     ((member "replace" result-params)
+	      (delete-region (point) (org-babel-result-end)))
+	     ((member "append" result-params)
+	      (goto-char (org-babel-result-end)) (setq beg (point)))
+	     ((member "prepend" result-params) ;; already there
+	      )))
 	  (setq results-switches
                 (if results-switches (concat " " results-switches) ""))
 	  (cond
 	   ;; assume the result is a table if it's not a string
 	   ((not (stringp result))
-	    (setq beg (point))
 	    (insert (concat (orgtbl-to-orgtbl
 			     (if (or (eq 'hline (car result))
 				     (and (listp (car result))
 					  (listp (cdr (car result)))))
 				 result (list result))
 			     '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
-	    (goto-char beg) (org-cycle))
+	    (goto-char beg) (org-table-align))
 	   ((member "file" result-params)
 	    (insert result))
 	   ((member "html" result-params)
@@ -981,7 +1034,14 @@ code ---- the results are extracted in the syntax of the source
 	    (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
 	   (t
 	    (org-babel-examplize-region
-             (point) (progn (insert result) (point)) results-switches)))))
+	     (point) (progn (insert result) (point)) results-switches)))
+	  ;; possibly indent the results to match the #+results line
+	  (setq end (if (listp result) (org-table-end) (point)))
+	  (when (and indent (> indent 0)
+		     ;; in this case `table-align' does the work for us
+		     (not (and (listp result)
+			       (member "append" result-params))))
+	    (indent-rigidly beg end indent))))
       (message "finished"))))
 
 (defun org-babel-result-to-org-string (result)
@@ -1005,19 +1065,19 @@ relies on `org-babel-insert-result'."
         (progn (goto-char (org-table-end)) (point))
       (let ((case-fold-search t))
         (cond
-         ((looking-at "#\\+begin_latex")
-          (search-forward "#+end_latex" nil t)
+         ((looking-at "[ \t]*#\\+begin_latex")
+          (search-forward "[ \t]*#\\+end_latex" nil t)
           (forward-line 1))
-         ((looking-at "#\\+begin_html")
-          (search-forward "#+end_html" nil t)
+         ((looking-at "[ \t]*#\\+begin_html")
+          (search-forward "[ \t]*#\\+end_html" nil t)
           (forward-line 1))
-         ((looking-at "#\\+begin_example")
-          (search-forward "#+end_example" nil t)
+         ((looking-at "[ \t]*#\\+begin_example")
+          (search-forward "[ \t]*#\\+end_example" nil t)
           (forward-line 1))
-         ((looking-at "#\\+begin_src")
-          (search-forward "#+end_src" nil t)
+         ((looking-at "[ \t]*#\\+begin_src")
+          (search-forward "[ \t]*#\\+end_src" nil t)
           (forward-line 1))
-         (t (progn (while (looking-at "\\(: \\|\\[\\[\\)")
+         (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
                      (forward-line 1))))))
       (point))))
 
@@ -1063,7 +1123,7 @@ parameters when merging lists."
   (let ((results-exclusive-groups
 	 '(("file" "vector" "table" "scalar" "raw" "org"
             "html" "latex" "code" "pp")
-	   ("replace" "silent")
+	   ("replace" "silent" "append" "prepend")
 	   ("output" "value")))
 	(exports-exclusive-groups
 	 '(("code" "results" "both" "none")))
@@ -1218,21 +1278,24 @@ block but are passed literally to the \"example-block\"."
                           (let ((raw (org-babel-ref-resolve-reference
                                       source-name nil)))
                             (if (stringp raw) raw (format "%S" raw)))
-                        (let ((point (org-babel-find-named-block source-name)))
-                          (if point
-                              (save-excursion
-                                (goto-char point)
-                                (org-babel-trim
-                                 (org-babel-expand-noweb-references
-                                  (org-babel-get-src-block-info))))
-                            ;; optionally raise an error if named
-                            ;; source-block doesn't exist
-                            (if (member lang org-babel-noweb-error-langs)
-                                (error
-                                 (concat "<<%s>> could not be resolved "
-                                         "(see `org-babel-noweb-error-langs')")
-                                 source-name)
-                              "")))) "[\n\r]") (concat "\n" prefix)))))
+			(save-restriction
+			  (widen)
+			  (let ((point (org-babel-find-named-block source-name)))
+			    (if point
+				(save-excursion
+				  (goto-char point)
+				  (org-babel-trim
+				   (org-babel-expand-noweb-references
+				    (org-babel-get-src-block-info))))
+			      ;; optionally raise an error if named
+			      ;; source-block doesn't exist
+			      (if (member lang org-babel-noweb-error-langs)
+				  (error
+				   (concat "<<%s>> could not be resolved "
+					   "(see `org-babel-noweb-error-langs')")
+				   source-name)
+				"")))))
+		      "[\n\r]") (concat "\n" prefix)))))
         (nb-add (buffer-substring index (point-max)))))
     new-body))
 
@@ -1272,7 +1335,9 @@ This is taken almost directly from `org-read-prop'."
 (defun org-babel-number-p (string)
   "Return t if STRING represents a number"
   (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
-           (= (match-end 0) (length string)))
+           (= (length (substring string (match-beginning 0)
+				 (match-end 0)))
+	      (length string)))
       (string-to-number string)))
 
 (defun org-babel-import-elisp-from-file (file-name)

+ 5 - 0
doc/ChangeLog

@@ -1,3 +1,8 @@
+2010-06-03  Christian Egli  <christian.egli@sbszh.ch>
+
+	* org.texi (TaskJuggler export): Added documentation for the
+	TaskJuggler exporter.
+
 2010-05-19  Carsten Dominik  <carsten.dominik@gmail.com>
 
 	* org.texi (Column attributes): Document that the ":" operator

+ 141 - 8
doc/org.texi

@@ -339,6 +339,7 @@ Exporting
 * HTML export::                 Exporting to HTML
 * LaTeX and PDF export::        Exporting to La@TeX{}, and processing to PDF
 * DocBook export::              Exporting to DocBook
+* TaskJuggler export::          Exporting to TaskJuggler
 * Freemind export::             Exporting to Freemind mind maps
 * XOXO export::                 Exporting to XOXO
 * iCalendar export::            Exporting in iCalendar format
@@ -6439,9 +6440,9 @@ Archived trees are not exported (@pxref{Exporting}), only the headline
 is.  Configure the details using the variable
 @code{org-export-with-archived-trees}.
 @item
-@vindex org-columns-skip-arrchived-trees
+@vindex org-columns-skip-archived-trees
 Archived trees are excluded from column view unless the variable
-@code{org-columns-skip-arrchived-trees} is configured to @code{nil}.
+@code{org-columns-skip-archived-trees} is configured to @code{nil}.
 @end itemize
 
 The following commands help managing the ARCHIVE tag:
@@ -8957,10 +8958,11 @@ the web, while the XOXO format provides a solid base for exchange with a
 broad range of other applications. La@TeX{} export lets you use Org mode and
 its structured editing functions to easily create La@TeX{} files.  DocBook
 export makes it possible to convert Org files to many other formats using
-DocBook tools.  To incorporate entries with associated times like deadlines
-or appointments into a desktop calendar program like iCal, Org mode can also
-produce extracts in the iCalendar format.  Currently Org mode only supports
-export, not import of these different formats.
+DocBook tools.  For project management you can create gantt and resource
+charts by using TaskJuggler export.  To incorporate entries with associated
+times like deadlines or appointments into a desktop calendar program like
+iCal, Org mode can also produce extracts in the iCalendar format.  Currently
+Org mode only supports export, not import of these different formats.
 
 Org supports export of selected regions when @code{transient-mark-mode} is
 enabled (default in Emacs 23).
@@ -8973,6 +8975,7 @@ enabled (default in Emacs 23).
 * HTML export::                 Exporting to HTML
 * LaTeX and PDF export::        Exporting to La@TeX{}, and processing to PDF
 * DocBook export::              Exporting to DocBook
+* TaskJuggler export::          Exporting to TaskJuggler
 * Freemind export::             Exporting to Freemind mind maps
 * XOXO export::                 Exporting to XOXO
 * iCalendar export::            Exporting in iCalendar format
@@ -9898,7 +9901,7 @@ Here is a simple example Org document that is intended for beamer export.
 
 For more information, see the documentation on Worg.
 
-@node DocBook export, Freemind export, LaTeX and PDF export, Exporting
+@node DocBook export, TaskJuggler export, LaTeX and PDF export, Exporting
 @section DocBook export
 @cindex DocBook export
 @cindex PDF export
@@ -10098,7 +10101,137 @@ special characters included in XHTML entities:
 "
 @end example
 
-@node Freemind export, XOXO export, DocBook export, Exporting
+@node  TaskJuggler export, Freemind export, DocBook export, Exporting
+@section TaskJuggler export
+@cindex TaskJuggler export
+@cindex Project management
+
+@uref{http://www.taskjuggler.org/, TaskJuggler} is a project management tool.
+It provides an optimizing scheduler that computes your project time lines and
+resource assignments based on the project outline and the constraints that
+you have provided.
+
+The TaskJuggler exporter is a bit different from other exporters, such as the
+HTML and LaTeX exporters for example, in that it does not export all the
+nodes of a document or strictly follow the order of the nodes in the
+document.
+
+Instead the TaskJuggler exporter looks for a tree that defines the tasks and
+a optionally tree that defines the resources for this project. It then
+creates a TaskJuggler file based on these trees and the attributes defined in
+all the nodes.
+
+@subsection TaskJuggler export commands
+
+@table @kbd
+@kindex C-c C-e j
+@item C-c C-e j
+Export as TaskJuggler file.
+
+@kindex C-c C-e J
+@item C-c C-e J
+Export as TaskJuggler file and then open the file with TaskJugglerUI.
+@end table
+
+@subsection Tasks
+
+@vindex org-export-taskjuggler-project-tag
+Create your tasks as you usually do with Org-mode. Assign efforts to each
+task using properties (it's easiest to do this in the column view). You
+should end up with something similar to the example by Peter Jones in
+@url{http://www.contextualdevelopment.com/static/artifacts/articles/2008/project-planning/project-planning.org}.
+Now mark the top node of your tasks with a tag named
+@code{:taskjuggler_project:} (or whatever you customized
+@code{org-export-taskjuggler-project-tag} to). You are now ready to export
+the project plan with @kbd{C-c C-e J} which will export the project plan and
+open a gantt chart in TaskJugglerUI.
+
+@subsection Resources
+
+@vindex org-export-taskjuggler-resource-tag
+Next you can define resources and assign those to work on specific tasks. You
+can group your resources hierarchically. Tag the top node of the resources
+with @code{:taskjuggler_resource:} (or whatever you customized
+@code{org-export-taskjuggler-resource-tag} to). You can optionally assign an
+identifier (named @samp{resource_id}) to the resources (using the standard
+Org properties commands, @pxref{Property syntax}) or you can let the exporter
+generate identifiers automatically (the exporter picks the first word of the
+headline as the identifier as long as it is unique, see the documentation of
+@code{org-taskjuggler-get-unique-id}). Using that identifier you can then
+allocate resources to tasks. This is again done with the @samp{allocate}
+property on the tasks. Do this in column view or when on the task type
+@kbd{C-c C-x p allocate @key{RET} <resource_id> @key{RET}}.
+
+Once the allocations are done you can again export to TaskJuggler and check
+in the Resource Allocation Graph which person is working on what task at what
+time.
+
+@subsection Export of properties
+
+The exporter also takes TODO state information into consideration, i.e. if a
+task is marked as done it will have the corresponding attribute in
+TaskJuggler (@samp{complete 100}). Also it will export any property on a task
+resource or resource node which is known to TaskJuggler, such as
+@samp{limits}, @samp{vacation}, @samp{shift}, @samp{booking},
+@samp{efficiency}, @samp{journalentry}, @samp{rate} for resources or
+@samp{account}, @samp{start}, @samp{note}, @samp{duration}, @samp{end},
+@samp{journalentry}, @samp{milestone}, @samp{reference}, @samp{responsible},
+@samp{scheduling}, etc for tasks.
+
+@subsection Dependencies
+
+The exporter will handle dependencies that are defined in the tasks either
+with the @samp{ORDERED} attribute (@pxref{TODO dependencies}), with the
+@samp{BLOCKER} attribute (see org-depend.el) or alternatively with a
+@samp{depends} attribute. Both the @samp{BLOCKER} and the @samp{depends}
+attribute can be either @samp{previous-sibling} or a reference to an
+identifier (named @samp{task_id}) which is defined for another task in the
+project. @samp{BLOCKER} and the @samp{depends} attribute can define multiple
+dependencies separated by either space or comma. You can also specify
+optional attributes on the dependency by simply appending it. The following
+examples should illustrate this:
+
+@example
+* Preparation
+  :PROPERTIES:
+  :task_id:  preparation
+  :ORDERED:  t
+  :END:
+* Training material
+  :PROPERTIES:
+  :task_id:  training_material
+  :ORDERED:  t
+  :END:
+** Markup Guidelines
+   :PROPERTIES:
+   :Effort:   2.0
+   :END:
+** Workflow Guidelines
+   :PROPERTIES:
+   :Effort:   2.0
+   :END:
+* Presentation
+  :PROPERTIES:
+  :Effort:   2.0
+  :BLOCKER:  training_material @{ gapduration 1d @} preparation
+  :END:
+@end example
+
+@subsection Reports
+
+@vindex org-export-taskjuggler-default-reports
+TaskJuggler can produce many kinds of reports (e.g. gantt chart, resource
+allocation, etc). The user defines what kind of reports should be generated
+for a project in the TaskJuggler file. The exporter will automatically insert
+some default reports in the file. These defaults are defined in
+@code{org-export-taskjuggler-default-reports}. They can be modified using
+customize along with a number of other options. For a more complete list, see
+@kbd{M-x customize-group @key{RET} org-export-taskjuggler @key{RET}}.
+
+For more information and examples see the Org-taskjuggler tutorial at
+@uref{http://orgmode.org/worg/org-tutorials/org-taskjuggler.php}.
+
+@node Freemind export, XOXO export, TaskJuggler export, Exporting
 @section Freemind export
 @cindex Freemind export
 @cindex mind map

+ 33 - 0
lisp/ChangeLog

@@ -1,3 +1,17 @@
+2010-06-08  Christian Egli  <christian.egli@sbszh.ch>
+
+	* org-taskjuggler.el (org-export-taskjuggler-old-level):
+	define local variable to avoid compiler warning.
+
+2010-06-07  Christian Egli  <christian.egli@sbszh.ch>
+
+	* org-exp.el (org-export): Added taskjuggler export to the export
+	dispatcher.
+
+2010-06-08  Bastien Guerry  <bzg@altern.org>
+
+	* org-timer.el (org-timer-set-timer): Fix typo in the docstring.
+
 2010-05-28  Bastien Guerry  <bzg@altern.org>
 
 	* org-timer.el (org-timer-set-timer): Use a prefix argument.
@@ -291,6 +305,15 @@
 	* org-html.el (org-format-org-table-html): Test all columns
 	for number content.
 
+2010-04-28  Christian Egli  <christian.egli@sbszh.ch>
+
+	* org-taskjuggler.el (org-taskjuggler-find-task-with-id): Do not
+	use the ID property frivolously, i.e. use a property named
+	"task_id" instead as we do not search for ids across files.
+	(org-taskjuggler-resolve-explicit-dependencies): Issue a warning
+	if a dependency cannot be resolved.
+	(org-taskjuggler-open-resource): Add documentation.
+
 2010-04-28  Carsten Dominik  <carsten.dominik@gmail.com>
 
 	* org-latex.el (org-export-latex-treat-sub-super-char): Make
@@ -687,6 +710,11 @@
 	(org-export-latex-default-packages-alist): hyperref must be loaded
 	late.
 
+2010-04-07  Christian Egli  <christian.egli@sbszh.ch>
+
+	* org-taskjuggler.el (org-taskjuggler-tokenize-dependencies): Add
+	support for optional attributes on dependencies.
+
 2010-04-07  Carsten Dominik  <carsten.dominik@gmail.com>
 
 	* org-latex.el (org-export-latex-preprocess): Do not yet protect
@@ -825,6 +853,11 @@
 
 	* org-faces.el (org-faces): Change Customize group variable name
 
+2010-03-30  Christian Egli  <christian.egli@sbszh.ch>
+
+	* org-taskjuggler.el: Added a new exporter to export org-mode
+	projects to taskjuggler files.
+
 2010-03-29  Carsten Dominik  <carsten.dominik@gmail.com>
 
 	* org-agenda.el (org-diary-last-run-time): New variable.

+ 1 - 1
lisp/ChangeLog.01

@@ -3343,7 +3343,7 @@
 	`truncate-lines'.
 	(org-columns): Remember the value of `truncate-lines'.
 
-	* org.el (org-columns-skip-arrchived-trees): New option.
+	* org.el (org-columns-skip-archived-trees): New option.
 
 	* org-agenda.el (org-agenda-export-html-style): Define color for
 	org-agenda-done face.

+ 1 - 1
lisp/org-clock.el

@@ -1354,7 +1354,7 @@ With prefix arg SELECT, offer recently clocked tasks for selection."
   "Sum the times for each subtree.
 Puts the resulting times in minutes as a text property on each headline.
 TSTART and TEND can mark a time range to be considered.  HEADLINE-FILTER is a
-zero-arg function that, if specified, is called for each headline in the time 
+zero-arg function that, if specified, is called for each headline in the time
 range with point at the headline.  Headlines for which HEADLINE-FILTER returns
 nil are excluded from the clock summation."
   (interactive)

+ 22 - 17
lisp/org-exp.el

@@ -862,6 +862,8 @@ value of `org-export-run-in-background'."
 
 \[D] export as DocBook   [V] export as DocBook, process to PDF, and open
 
+\[j] export as TaskJuggler                         [J] ... and open
+
 \[m] export as Freemind mind map
 \[x] export as XOXO
 \[g] export using Wes Hardaker's generic exporter
@@ -888,6 +890,8 @@ value of `org-export-run-in-background'."
 	    (?g org-export-generic t)
 	    (?D org-export-as-docbook t)
 	    (?V org-export-as-docbook-pdf-and-open t)
+	    (?j org-export-as-taskjuggler t)
+	    (?J org-export-as-taskjuggler-and-open t)
 	    (?m org-export-as-freemind t)
 	    (?l org-export-as-latex t)
 	    (?p org-export-as-pdf t)
@@ -1668,22 +1672,23 @@ When it is nil, all comments will be removed."
   "Remove tables lines that are used for internal purposes."
   (goto-char (point-min))
   (while (re-search-forward "^[ \t]*|" nil t)
-    (beginning-of-line 1)
-    (if (or (looking-at "[ \t]*| *[!_^] *|")
-	    (not
-	     (memq
-	      nil
-	      (mapcar
-	       (lambda (f)
-		 (or (= (length f) 0)
-		     (string-match
-		      "\\`<\\([0-9]\\|[rl]\\|[rl][0-9]+\\)>\\'" f)))
-	       (org-split-string ;; FIXME, can't we do this without splitting???
-		(buffer-substring (point-at-bol) (point-at-eol))
-		"[ \t]*|[ \t]*")))))
-	(delete-region (max (point-min) (1- (point-at-bol)))
-		       (point-at-eol))
-      (end-of-line 1))))
+    (org-if-unprotected-at (1- (point))
+      (beginning-of-line 1)
+      (if (or (looking-at "[ \t]*| *[!_^] *|")
+	      (not
+	       (memq
+		nil
+		(mapcar
+		 (lambda (f)
+		   (or (= (length f) 0)
+		       (string-match
+			"\\`<\\([0-9]\\|[rl]\\|[rl][0-9]+\\)>\\'" f)))
+		 (org-split-string ;; FIXME, can't we do without splitting???
+		  (buffer-substring (point-at-bol) (point-at-eol))
+		  "[ \t]*|[ \t]*")))))
+	  (delete-region (max (point-min) (1- (point-at-bol)))
+			 (point-at-eol))
+	(end-of-line 1)))))
 
 (defun org-export-protect-sub-super (s)
   (save-match-data
@@ -2008,7 +2013,7 @@ take care of the block they are in."
       (goto-char (point-min))
       (while (not (eobp))
 	(insert (or prefix1 prefix))
-	(setq prefix1 nil)
+	(setq prefix1 "")
 	(beginning-of-line 2)))
     (buffer-string)
     (when (member markup '("src" "example"))

+ 35 - 35
lisp/org-html.el

@@ -535,7 +535,7 @@ in a window.  A non-interactive call will only return the buffer."
 (defvar org-par-open nil)
 
 ;;; org-html-cvt-link-fn
-(defconst org-html-cvt-link-fn 
+(defconst org-html-cvt-link-fn
    nil
    "Function to convert link URLs to exportable URLs.
 Takes two arguments, TYPE and PATH.
@@ -549,16 +549,16 @@ If TYPE is not file, just return `nil'.
 See variable `org-export-html-link-org-files-as-html'"
 
    (save-match-data
-      (and 
+      (and
 	 org-export-html-link-org-files-as-html
 	 (string= type "file")
 	 (string-match "\\.org$" path)
 	 (progn
 	    (list
 	       "http"
-	       (concat 
+	       (concat
 		  (substring path 0 (match-beginning 0))
-		  "." 
+		  "."
 		  (plist-get opt-plist :html-extension)))))))
 
 
@@ -569,12 +569,12 @@ current settings.
 DESCP is the boolean of whether there was a link description.
 See variables `org-export-html-inline-images' and
 `org-export-html-inline-image-extensions'."
-   (declare (special 
-	     org-export-html-inline-images 
+   (declare (special
+	     org-export-html-inline-images
 	     org-export-html-inline-image-extensions))
-   (or 
+   (or
       (eq t org-export-html-inline-images)
-      (and 
+      (and
 	 org-export-html-inline-images
 	 (not descp)))
    (org-file-image-p
@@ -582,7 +582,7 @@ See variables `org-export-html-inline-images' and
 
 ;;; org-html-make-link
 (defun org-html-make-link (opt-plist type path fragment desc attr
-			     may-inline-p) 
+			     may-inline-p)
    "Make an HTML link.
 OPT-PLIST is an options list.
 TYPE is the device-type of the link (THIS://foo.html)
@@ -603,8 +603,8 @@ MAY-INLINE-P allows inlining it as an image."
 			   type
 			   ;;Substitute just if original path was absolute.
 			   ;;(Otherwise path must remain relative)
-			   (if (file-name-absolute-p path) 
-			      (expand-file-name path) 
+			   (if (file-name-absolute-p path)
+			      (expand-file-name path)
 			      path)))
 		     ((string= type "")
 			(list nil path))
@@ -615,9 +615,9 @@ MAY-INLINE-P allows inlining it as an image."
 	       (components-2
 		  (or
 		     (and org-html-cvt-link-fn
-			(apply org-html-cvt-link-fn 
+			(apply org-html-cvt-link-fn
 			   opt-plist components-1))
-		     (apply #'org-html-cvt-org-as-html 
+		     (apply #'org-html-cvt-org-as-html
 			opt-plist components-1)
 		     components-1))
 	       (type    (first  components-2))
@@ -633,11 +633,11 @@ MAY-INLINE-P allows inlining it as an image."
 		(string= type "https"))
 	       (if fragment
 		  (setq thefile (concat thefile "#" fragment))))
-	       
+
 	    (t))
-	    
+
 	 ;;Final URL-build, for all types.
-	 (setq thefile 
+	 (setq thefile
 	    (let
 	       ((str (org-export-html-format-href thefile)))
 	      (if (and type (not (string= "file" type))
@@ -645,14 +645,14 @@ MAY-INLINE-P allows inlining it as an image."
 		  (concat type ":" str)
 		  str)))
 
-	 (if (and 
+	 (if (and
 		may-inline-p
 		;;Can't inline a URL with a fragment.
 		(not fragment))
 	    (progn
 	       (message "image %s %s" thefile org-par-open)
 	       (org-export-html-format-image thefile org-par-open))
-	    (concat 
+	    (concat
 	       "<a href=\"" thefile "\"" attr ">"
 	       (org-export-html-format-desc desc)
 	       "</a>")))))
@@ -1182,12 +1182,12 @@ lang=\"%s\" xml:lang=\"%s\">
 			     '(org-protected t))))
 	    (cond
 	     ((equal type "internal")
-		(let 
+		(let
 		   ((frag-0
-		       (if (= (string-to-char path) ?#) 
-			  (substring path 1) 
+		       (if (= (string-to-char path) ?#)
+			  (substring path 1)
 			  path)))
-		   (setq rpl 
+		   (setq rpl
 		      (org-html-make-link
 			 opt-plist
 			 ""
@@ -1202,11 +1202,11 @@ lang=\"%s\" xml:lang=\"%s\">
 	      ;; it would have become an internal link...)
 	      (save-match-data
 		(setq id-file (file-relative-name
-				 id-file 
+				 id-file
 				 (file-name-directory org-current-export-file)))
-		(setq rpl 
+		(setq rpl
 		   (org-html-make-link opt-plist
-		      "file" id-file 
+		      "file" id-file
 		      (concat (if (org-uuidgen-p path) "ID-") path)
 		       desc
 		      attr
@@ -1237,14 +1237,14 @@ lang=\"%s\" xml:lang=\"%s\">
 		   (setq rpl
 		      (org-html-make-link opt-plist
 			 type "" coderef-str
-			 (format 
-			    (org-export-get-coderef-format 
-			       path 
+			 (format
+			    (org-export-get-coderef-format
+			       path
 			       (and descp desc))
 			    (cdr (assoc path org-export-code-refs)))
 			 attr-1
 			 nil))))
-	       
+
 	     ((functionp (setq fnc (nth 2 (assoc type org-link-protocols))))
 	      ;; The link protocol has a function for format the link
 	      (setq rpl
@@ -1258,15 +1258,15 @@ lang=\"%s\" xml:lang=\"%s\">
 		      ((components
 			  (if
 			     (string-match "::\\(.*\\)" path)
-			     (list 
+			     (list
 				(replace-match "" t nil path)
 				(match-string 1 path))
 			     (list path nil)))
-			 
+
 			 ;;The proper path, without a fragment
 			 (path-1
 			    (first components))
-			 
+
 			 ;;The raw fragment
 			 (fragment-0
 			    (second components))
@@ -1291,7 +1291,7 @@ lang=\"%s\" xml:lang=\"%s\">
 				     (replace-match "" t t desc-1)
 				     desc-1))
 			       desc)))
-		      
+
 		      (setq rpl
 			 (if
 			    (and
@@ -1299,9 +1299,9 @@ lang=\"%s\" xml:lang=\"%s\">
 			       (not (funcall link-validate path-1 current-dir)))
 			    desc
 			    (org-html-make-link opt-plist
-			       "file" path-1 fragment-1 desc-2 attr 
+			       "file" path-1 fragment-1 desc-2 attr
 			       (org-html-should-inline-p path-1 descp)))))))
-	       
+
 	     (t
 	      ;; just publish the path, as default
 	      (setq rpl (concat "<i>&lt;" type ":"

+ 6 - 5
lisp/org-latex.el

@@ -144,7 +144,7 @@ class, you can use the following macro-like placeholders.
 
  [DEFAULT-PACKAGES]      \\usepackage statements for default packages
  [NO-DEFAULT-PACKAGES]   do not include any of the default packages
- [PACKAGES]              \\usepackage statements for packages 
+ [PACKAGES]              \\usepackage statements for packages
  [NO-PACKAGES]           do not include the packages
  [EXTRA]                 the stuff from #+LaTeX_HEADER
  [NO-EXTRA]              do not include #+LaTeX_HEADER stuff
@@ -1901,7 +1901,7 @@ The conversion is made depending of STRING-BEFORE and STRING-AFTER."
 	  (setq wrapp nil floatp t attr (replace-match "" t t attr)))
       (if (string-match "[ \t]*\\<multicolumn\\>" attr)
 	  (setq multicolumnp t attr (replace-match "" t t attr))))
-    
+
     (setq placement
 	  (cond
 	   (wrapp "{l}{0.5\\textwidth}")
@@ -1984,7 +1984,8 @@ The conversion is made depending of STRING-BEFORE and STRING-AFTER."
   ;; Preserve latex environments
   (goto-char (point-min))
   (while (re-search-forward "^[ \t]*\\\\begin{\\([a-zA-Z]+\\*?\\)}" nil t)
-    (let* ((start (progn (beginning-of-line) (point)))
+    (org-if-unprotected
+     (let* ((start (progn (beginning-of-line) (point)))
 	   (end (and (re-search-forward
 		      (concat "^[ \t]*\\\\end{"
 			      (regexp-quote (match-string 1))
@@ -1992,7 +1993,7 @@ The conversion is made depending of STRING-BEFORE and STRING-AFTER."
 		     (point-at-eol))))
       (if end
 	  (add-text-properties start end '(org-protected t))
-	(goto-char (point-at-eol)))))
+	(goto-char (point-at-eol))))))
 
   ;; Preserve math snippets
 
@@ -2074,7 +2075,7 @@ The conversion is made depending of STRING-BEFORE and STRING-AFTER."
 	     "\\(?:<[^<>\n]*>\\)*"
 	     "\\(" (org-create-multibrace-regexp "{" "}" 3) "\\)\\{1,3\\}")))
     (while (re-search-forward re nil t)
-      (unless (or 
+      (unless (or
 	       ;; check for comment line
 	       (save-excursion (goto-char (match-beginning 0))
 			       (org-in-indented-comment-line))

+ 2 - 1
lisp/org-table.el

@@ -2764,6 +2764,7 @@ Parameters get priority."
     (org-defkey map "\C-x\C-s"      'org-table-fedit-finish)
     (org-defkey map "\C-c\C-s"      'org-table-fedit-finish)
     (org-defkey map "\C-c\C-c"      'org-table-fedit-finish)
+    (org-defkey map "\C-c'"         'org-table-fedit-finish)
     (org-defkey map "\C-c\C-q"      'org-table-fedit-abort)
     (org-defkey map "\C-c?"	    'org-table-show-reference)
     (org-defkey map [(meta shift up)]    'org-table-fedit-line-up)
@@ -2860,7 +2861,7 @@ Parameters get priority."
     (if (eq org-table-use-standard-references t)
 	(org-table-fedit-toggle-ref-type))
     (org-goto-line startline)
-    (message "Edit formulas and finish with `C-c C-c'.  See menu for more commands.")))
+    (message "Edit formulas, finish with `C-c C-c' or `C-c ' '.  See menu for more commands.")))
 
 (defun org-table-fedit-post-command ()
   (when (not (memq this-command '(lisp-complete-symbol)))

+ 647 - 0
lisp/org-taskjuggler.el

@@ -0,0 +1,647 @@
+;;; org-taskjuggler.el --- TaskJuggler exporter for org-mode
+;;
+;; Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
+;;
+;; Emacs Lisp Archive Entry
+;; Filename: org-taskjuggler.el
+;; Version: 6.34trans
+;; Author: Christian Egli
+;; Maintainer: Christian Egli
+;; Keywords: org, taskjuggler, project planning
+;; Description: Converts an org-mode buffer into a taskjuggler project plan
+;; URL:
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
+
+;; Commentary:
+;;
+;; This library implements a TaskJuggler exporter for org-mode.
+;; TaskJuggler uses a text format to define projects, tasks and
+;; resources, so it is a natural fit for org-mode. It can produce all
+;; sorts of reports for tasks or resources in either HTML, CSV or PDF.
+;; The current version of TaskJuggler requires KDE but the next
+;; version is implemented in Ruby and should therefore run on any
+;; platform.
+;;
+;; The exporter is a bit different from other exporters, such as the
+;; HTML and LaTeX exporters for example, in that it does not export
+;; all the nodes of a document or strictly follow the order of the
+;; nodes in the document.
+;;
+;; Instead the TaskJuggler exporter looks for a tree that defines the
+;; tasks and a optionally tree that defines the resources for this
+;; project. It then creates a TaskJuggler file based on these trees
+;; and the attributes defined in all the nodes.
+;;
+;; * Installation
+;;
+;; Put this file into your load-path and the following line into your
+;; ~/.emacs:
+;;
+;;   (require 'org-taskjuggler)
+;;
+;; The interactive functions are similar to those of the HTML and LaTeX
+;; exporters:
+;;
+;; M-x `org-export-as-taskjuggler'
+;; M-x `org-export-as-taskjuggler-and-open'
+;;
+;; * Tasks
+;;
+;; Let's illustrate the usage with a small example. Create your tasks
+;; as you usually do with org-mode. Assign efforts to each task using
+;; properties (it's easiest to do this in the column view). You should
+;; end up with something similar to the example by Peter Jones in
+;; http://www.contextualdevelopment.com/static/artifacts/articles/2008/project-planning/project-planning.org.
+;; Now mark the top node of your tasks with a tag named
+;; "taskjuggler_project" (or whatever you customized
+;; `org-export-taskjuggler-project-tag' to). You are now ready to
+;; export the project plan with `org-export-as-taskjuggler-and-open'
+;; which will export the project plan and open a gant chart in
+;; TaskJugglerUI.
+;;
+;; * Resources
+;; 
+;; Next you can define resources and assign those to work on specific
+;; tasks. You can group your resources hierarchically. Tag the top
+;; node of the resources with "taskjuggler_resource" (or whatever you
+;; customized `org-export-taskjuggler-resource-tag' to). You can
+;; optionally assign an identifier (named "resource_id") to the
+;; resources (using the standard org properties commands) or you can
+;; let the exporter generate identifiers automatically (the exporter
+;; picks the first word of the headline as the identifier as long as
+;; it is unique, see the documentation of
+;; `org-taskjuggler-get-unique-id'). Using that identifier you can
+;; then allocate resources to tasks. This is again done with the
+;; "allocate" property on the tasks. Do this in column view or when on
+;; the task type
+;;
+;;  C-c C-x p allocate RET <resource_id> RET
+;;
+;; Once the allocations are done you can again export to TaskJuggler
+;; and check in the Resource Allocation Graph which person is working
+;; on what task at what time.
+;;
+;; * Export of properties
+;;
+;; The exporter also takes TODO state information into consideration,
+;; i.e. if a task is marked as done it will have the corresponding
+;; attribute in TaskJuggler ("complete 100"). Also it will export any
+;; property on a task resource or resource node which is known to
+;; TaskJuggler, such as limits, vacation, shift, booking, efficiency,
+;; journalentry, rate for resources or account, start, note, duration,
+;; end, journalentry, milestone, reference, responsible, scheduling,
+;; etc for tasks.
+;;
+;; * Dependencies
+;; 
+;; The exporter will handle dependencies that are defined in the tasks
+;; either with the ORDERED attribute (see TODO dependencies in the Org
+;; mode manual) or with the BLOCKER attribute (see org-depend.el) or
+;; alternatively with a depends attribute. Both the BLOCKER and the
+;; depends attribute can be either "previous-sibling" or a reference
+;; to an identifier (named "task_id") which is defined for another
+;; task in the project. BLOCKER and the depends attribute can define
+;; multiple dependencies separated by either space or comma. You can
+;; also specify optional attributes on the dependency by simply
+;; appending it. The following examples should illustrate this:
+;;
+;; * Training material
+;;   :PROPERTIES:
+;;   :task_id:  training_material
+;;   :ORDERED:  t
+;;   :END:
+;; ** Markup Guidelines
+;;    :PROPERTIES:
+;;    :Effort:   2.0
+;;    :END:
+;; ** Workflow Guidelines
+;;    :PROPERTIES:
+;;    :Effort:   2.0
+;;    :END:
+;; * Presentation
+;;   :PROPERTIES:
+;;   :Effort:   2.0
+;;   :BLOCKER:  training_material { gapduration 1d } some_other_task
+;;   :END:
+;; 
+;;;; * TODO
+;;   - Use SCHEDULED and DEADLINE information (not just start and end
+;;     properties).
+;;   - Look at org-file-properties, org-global-properties and
+;;     org-global-properties-fixed
+;;   - What about property inheritance and org-property-inherit-p?
+;;   - Use TYPE_TODO as an way to assign resources
+;;   - Make sure multiple dependency definitions (i.e. BLOCKER on
+;;     previous-sibling and on a specific task_id) in multiple
+;;     attributes are properly exported.
+;;
+;;; Code:
+
+(eval-when-compile
+  (require 'cl))
+
+(require 'org)
+(require 'org-exp)
+
+;;; User variables:
+
+(defgroup org-export-taskjuggler nil
+  "Options for exporting Org-mode files to TaskJuggler."
+  :tag "Org Export TaskJuggler"
+  :group 'org-export)
+
+(defcustom org-export-taskjuggler-extension ".tjp"
+  "Extension of TaskJuggler files."
+  :group 'org-export-taskjuggler
+  :type 'string)
+
+(defcustom org-export-taskjuggler-project-tag "taskjuggler_project"
+  "Tag, property or todo used to find the tree containing all
+the tasks for the project."
+  :group 'org-export-taskjuggler
+  :type 'string)
+
+(defcustom org-export-taskjuggler-resource-tag "taskjuggler_resource"
+  "Tag, property or todo used to find the tree containing all the
+resources for the project."
+  :group 'org-export-taskjuggler
+  :type 'string)
+
+(defcustom org-export-taskjuggler-default-project-version "1.0"
+  "Default version string for the project."
+  :group 'org-export-taskjuggler
+  :type 'string)
+
+(defcustom org-export-taskjuggler-default-project-duration 280
+  "Default project duration if no start and end date have been defined
+in the root node of the task tree, i.e. the tree that has been marked
+with `org-export-taskjuggler-project-tag'"
+  :group 'org-export-taskjuggler
+  :type 'integer)
+
+(defcustom org-export-taskjuggler-default-reports 
+  '("taskreport \"Gantt Chart\" {
+  headline \"Project Gantt Chart\"
+  columns hierarchindex, name, start, end, effort, duration, completed, chart
+  timeformat \"%Y-%m-%d\"
+  hideresource 1
+  loadunit shortauto
+}"
+"resourcereport \"Resource Graph\" {
+  headline \"Resource Allocation Graph\"
+  columns no, name, utilization, freeload, chart
+  loadunit shortauto
+  sorttasks startup
+  hidetask ~isleaf()
+}")
+  "Default reports for the project."
+  :group 'org-export-taskjuggler
+  :type '(repeat (string :tag "Report")))
+
+(defcustom org-export-taskjuggler-default-global-properties 
+  "shift s40 \"Part time shift\" {
+  workinghours wed, thu, fri off
+}
+"
+  "Default global properties for the project. Here you typically
+define global properties such as shifts, accounts, rates,
+vacation, macros and flags. Any property that is allowed within
+the TaskJuggler file can be inserted. You could for example
+include another TaskJuggler file. 
+
+The global properties are inserted after the project declaration
+but before any resource and task declarations."
+  :group 'org-export-taskjuggler
+  :type '(string :tag "Preamble"))
+
+;;; Hooks
+
+(defvar org-export-taskjuggler-final-hook nil
+  "Hook run at the end of TaskJuggler export, in the new buffer.")
+
+;;; Autoload functions:
+
+;; avoid compiler warning about free variable
+(defvar org-export-taskjuggler-old-level)
+
+;;;###autoload
+(defun org-export-as-taskjuggler ()
+  "Export parts of the current buffer as a TaskJuggler file.
+The exporter looks for a tree with tag, property or todo that
+matches `org-export-taskjuggler-project-tag' and takes this as
+the tasks for this project. The first node of this tree defines
+the project properties such as project name and project period.
+If there is a tree with tag, property or todo that matches
+`org-export-taskjuggler-resource-tag' this three is taken as
+resources for the project. If no resources are specified, a
+default resource is created and allocated to the project. Also
+the taskjuggler project will be created with default reports as
+defined in `org-export-taskjuggler-default-reports'."
+  (interactive)
+
+  (message "Exporting...")
+  (setq-default org-done-keywords org-done-keywords)
+  (let* ((tasks
+	  (org-taskjuggler-resolve-dependencies
+	   (org-taskjuggler-assign-task-ids 
+	    (org-map-entries 
+	     '(org-taskjuggler-components) 
+	     org-export-taskjuggler-project-tag nil 'archive 'comment))))
+	 (resources
+	  (org-taskjuggler-assign-resource-ids
+	   (org-map-entries 
+	    '(org-taskjuggler-components) 
+	    org-export-taskjuggler-resource-tag nil 'archive 'comment)))
+	 (filename (expand-file-name
+		    (concat
+		     (file-name-sans-extension
+		      (file-name-nondirectory buffer-file-name))
+		     org-export-taskjuggler-extension)))
+	 (buffer (find-file-noselect filename))
+	 (org-export-taskjuggler-old-level 0)
+	 task resource)
+    (unless tasks
+      (error "No tasks specified"))
+    ;; add a default resource
+    (unless resources
+      (setq resources 
+	    `((("resource_id" . ,(user-login-name)) 
+	       ("headline" . ,user-full-name) 
+	       ("level" . 1)))))
+    ;; add a default allocation to the first task if none was given
+    (unless (assoc "allocate" (car tasks))
+      (let ((task (car tasks))
+	    (resource-id (cdr (assoc "resource_id" (car resources)))))
+	(setcar tasks (push (cons "allocate" resource-id) task))))
+    ;; add a default start date to the first task if none was given
+    (unless (assoc "start" (car tasks))
+      (let ((task (car tasks))
+	    (time-string (format-time-string "%Y-%m-%d")))
+	(setcar tasks (push (cons "start" time-string) task))))
+    ;; add a default version if none was given
+    (unless (assoc "version" (car tasks))
+      (let ((task (car tasks))
+	    (version org-export-taskjuggler-default-project-version))
+	(setcar tasks (push (cons "version" version) task))))
+    (with-current-buffer buffer
+      (erase-buffer)
+      (org-taskjuggler-open-project (car tasks))
+      (insert org-export-taskjuggler-default-global-properties)
+      (insert "\n")
+      (dolist (resource resources)
+	(let ((level (cdr (assoc "level" resource))))
+	  (org-taskjuggler-close-maybe level)
+	  (org-taskjuggler-open-resource resource)
+	  (setq org-export-taskjuggler-old-level level)))
+      (org-taskjuggler-close-maybe 1)
+      (setq org-export-taskjuggler-old-level 0)
+      (dolist (task tasks)
+	(let ((level (cdr (assoc "level" task))))
+	  (org-taskjuggler-close-maybe level)
+	  (org-taskjuggler-open-task task)
+	  (setq org-export-taskjuggler-old-level level)))
+      (org-taskjuggler-close-maybe 1)
+      (org-taskjuggler-insert-reports)
+      (save-buffer)
+      (or (org-export-push-to-kill-ring "TaskJuggler")
+	  (message "Exporting... done"))
+      (current-buffer))))
+
+;;;###autoload
+(defun org-export-as-taskjuggler-and-open ()
+  "Export the current buffer as a TaskJuggler file and open it
+with the TaskJuggler GUI."
+  (interactive)
+  (let ((file-name (buffer-file-name (org-export-as-taskjuggler)))
+	(command "TaskJugglerUI"))
+    (start-process-shell-command command nil command file-name)))
+
+(defun org-taskjuggler-parent-is-ordered-p ()
+  "Return true if the parent of the current node has a property
+\"ORDERED\". Return nil otherwise."
+  (save-excursion
+    (and (org-up-heading-safe) (org-entry-get (point) "ORDERED"))))
+
+(defun org-taskjuggler-components ()
+  "Return an alist containing all the pertinent information for
+the current node such as the headline, the level, todo state
+information, all the properties, etc."
+  (let* ((props (org-entry-properties))
+	 (components (org-heading-components))
+	 (level (nth 1 components))
+	 (headline (nth 4 components))
+	 (parent-ordered (org-taskjuggler-parent-is-ordered-p)))
+    (push (cons "level" level) props)
+    (push (cons "headline" headline) props)
+    (push (cons "parent-ordered" parent-ordered) props)))
+
+(defun org-taskjuggler-assign-task-ids (tasks)
+  "Given a list of tasks return the same list assigning a unique id
+and the full path to each task. Taskjuggler takes hierarchical ids.
+For that reason we have to make ids locally unique and we have to keep
+a path to the current task."
+  (let ((previous-level 0)
+	unique-ids unique-id
+	path
+	task resolved-tasks tmp)
+    (dolist (task tasks resolved-tasks)
+      (let ((level (cdr (assoc "level" task))))
+	(cond
+	 ((< previous-level level) 
+	  (setq unique-id (org-taskjuggler-get-unique-id task (car unique-ids)))
+	  (dotimes (tmp (- level previous-level))
+	    (push (list unique-id) unique-ids)
+	    (push unique-id path)))
+	 ((= previous-level level) 
+	  (setq unique-id (org-taskjuggler-get-unique-id task (car unique-ids)))
+	  (push unique-id (car unique-ids))
+	  (setcar path unique-id))
+	 ((> previous-level level) 
+	  (dotimes (tmp (- previous-level level))
+	    (pop unique-ids)
+	    (pop path))
+	  (setq unique-id (org-taskjuggler-get-unique-id task (car unique-ids)))
+	  (push unique-id (car unique-ids))
+	  (setcar path unique-id)))
+	(push (cons "unique-id" unique-id) task)
+	(push (cons "path" (mapconcat 'identity (reverse path) ".")) task)
+	(setq previous-level level)
+	(setq resolved-tasks (append resolved-tasks (list task)))))))
+
+(defun org-taskjuggler-assign-resource-ids (resources &optional unique-ids)
+  "Given a list of resources return the same list, assigning a
+unique id to each resource."
+  (cond
+   ((null resources) nil)
+   (t 
+    (let* ((resource (car resources))
+	   (unique-id (org-taskjuggler-get-unique-id resource unique-ids)))
+      (push (cons "unique-id" unique-id) resource)
+      (cons resource 
+	    (org-taskjuggler-assign-resource-ids (cdr resources) 
+						 (cons unique-id unique-ids)))))))
+
+(defun org-taskjuggler-resolve-dependencies (tasks)
+  (let ((previous-level 0)
+	siblings
+	task resolved-tasks)
+    (dolist (task tasks resolved-tasks)
+      (let* ((level (cdr (assoc "level" task)))
+	     (depends (cdr (assoc "depends" task)))
+	     (parent-ordered (cdr (assoc "parent-ordered" task)))
+	     (blocker (cdr (assoc "BLOCKER" task)))
+	     (blocked-on-previous 
+	      (and blocker (string-match "previous-sibling" blocker)))
+	     (dependencies
+	      (org-taskjuggler-resolve-explicit-dependencies
+	       (append 
+		(and depends (org-taskjuggler-tokenize-dependencies depends))
+		(and blocker (org-taskjuggler-tokenize-dependencies blocker))) 
+	       tasks))
+	      previous-sibling)
+	; update previous sibling info
+	(cond
+	 ((< previous-level level) 
+	  (dotimes (tmp (- level previous-level))
+	    (push task siblings)))
+	 ((= previous-level level)
+	  (setq previous-sibling (car siblings))
+	  (setcar siblings task))
+	 ((> previous-level level) 
+	  (dotimes (tmp (- previous-level level))
+	    (pop siblings))
+	  (setq previous-sibling (car siblings))
+	  (setcar siblings task)))
+	; insert a dependency on previous sibling if the parent is
+	; ordered or if the tasks has a BLOCKER attribute with value "previous-sibling"
+	(when (or (and previous-sibling parent-ordered) blocked-on-previous)
+	  (push (format "!%s" (cdr (assoc "unique-id" previous-sibling))) dependencies))
+	; store dependency information
+	(when dependencies 
+	  (push (cons "depends" (mapconcat 'identity dependencies ", ")) task))
+	(setq previous-level level)
+	(setq resolved-tasks (append resolved-tasks (list task)))))))
+
+(defun org-taskjuggler-tokenize-dependencies (dependencies)
+  "Split a dependency property value DEPENDENCIES into the
+individual dependencies and return them as a list while keeping
+the optional arguments (such as gapduration) for the
+dependencies. A dependency will have to match `[-a-zA-Z0-9_]+'."
+  (cond 
+   ((string-match "^ *$" dependencies) nil)
+   ((string-match "^[ \t]*\\([-a-zA-Z0-9_]+\\([ \t]*{[^}]+}\\)?\\)[ \t,]*" dependencies)
+    (cons 
+     (substring dependencies (match-beginning 1) (match-end 1))
+     (org-taskjuggler-tokenize-dependencies (substring dependencies (match-end 0)))))
+   (t (error (format "invalid dependency id %s" dependencies)))))
+
+(defun org-taskjuggler-resolve-explicit-dependencies (dependencies tasks)
+  "For each dependency in DEPENDENCIES try to find a
+corresponding task with a matching property \"task_id\" in TASKS.
+Return a list containing the resolved links for all DEPENDENCIES
+where a matching tasks was found. If the dependency is
+\"previous-sibling\" it is ignored (as this is dealt with in
+`org-taskjuggler-resolve-dependencies'). If there is no matching
+task the dependency is ignored and a warning is displayed ."
+  (unless (null dependencies)
+    (let* 
+	;; the dependency might have optional attributes such as "{
+	;; gapduration 5d }", so only use the first string as id for the
+	;; dependency
+	((dependency (car dependencies))
+	 (id (car (split-string dependency)))
+	 (optional-attributes 
+	  (mapconcat 'identity (cdr (split-string dependency)) " "))
+	 (path (org-taskjuggler-find-task-with-id id tasks)))
+      (cond 
+       ;; ignore previous sibling dependencies
+       ((equal (car dependencies) "previous-sibling")
+	(org-taskjuggler-resolve-explicit-dependencies (cdr dependencies) tasks))
+       ;; if the id is found in another task use its path
+       ((not (null path)) 
+	(cons (mapconcat 'identity (list path optional-attributes) " ")
+	      (org-taskjuggler-resolve-explicit-dependencies 
+	       (cdr dependencies) tasks)))
+       ;; warn about dangling dependency but otherwise ignore it
+       (t (display-warning 
+	   'org-export-taskjuggler 
+	   (format "No task with matching property \"task_id\" found for id %s" id))
+	  (org-taskjuggler-resolve-explicit-dependencies (cdr dependencies) tasks))))))
+
+(defun org-taskjuggler-find-task-with-id (id tasks)
+  "Find ID in tasks. If found return the path of task. Otherwise
+return nil."
+  (let ((task-id (cdr (assoc "task_id" (car tasks))))
+	(path (cdr (assoc "path" (car tasks)))))
+    (cond 
+     ((null tasks) nil)
+     ((equal task-id id) path)
+     (t (org-taskjuggler-find-task-with-id id (cdr tasks))))))
+
+(defun org-taskjuggler-get-unique-id (item unique-ids)
+  "Return a unique id for an ITEM which can be a task or a resource.
+The id is derived from the headline and made unique against
+UNIQUE-IDS. If the (downcased) first token of the headline is not
+unique try to add more (downcased) tokens of the headline or
+finally add more underscore characters (\"_\")."
+  (let* ((headline (cdr (assoc "headline" item)))
+	 (parts (split-string headline))
+	 (id (org-taskjuggler-clean-id (downcase (pop parts)))))
+    ; try to add more parts of the headline to make it unique
+    (while (member id unique-ids)
+      (setq id (concat id "_" (org-taskjuggler-clean-id (downcase (pop parts))))))
+    ; if its still not unique add "_"
+    (while (member id unique-ids)
+      (setq id (concat id "_")))
+    id))
+	
+(defun org-taskjuggler-clean-id (id)
+  "Clean and return ID to make it acceptable for taskjuggler."
+  (and id (replace-regexp-in-string "[^a-zA-Z0-9_]" "_" id)))
+
+(defun org-taskjuggler-open-project (project)
+  "Insert the beginning of a project declaration. All valid
+attributes from the PROJECT alist are inserted. If no end date is
+specified it is calculated
+`org-export-taskjuggler-default-project-duration' days from now."
+  (let* ((unique-id (cdr (assoc "unique-id" project)))
+	(headline (cdr (assoc "headline" project)))
+	(version (cdr (assoc "version" project)))
+	(start (cdr (assoc "start" project)))
+	(end (cdr (assoc "end" project))))
+    (insert 
+     (format "project %s \"%s\" \"%s\" %s +%sd {\n }\n"
+	     unique-id headline version start
+	     org-export-taskjuggler-default-project-duration))))
+
+(defun org-taskjuggler-filter-and-join (items)
+  "Filter all nil elements from ITEMS and join the remaining ones
+with separator \"\n\"."
+  (let ((filtered-items (remq nil items)))
+    (and filtered-items (mapconcat 'identity filtered-items "\n"))))
+  
+(defun org-taskjuggler-get-attributes (item attributes)
+  "Return all attribute as a single formated string. ITEM is an
+alist representing either a resource or a task. ATTRIBUTES is a
+list of symbols. Only entries from ITEM are considered that are
+listed in ATTRIBUTES."
+  (org-taskjuggler-filter-and-join 
+   (mapcar
+    (lambda (attribute) 
+      (org-taskjuggler-filter-and-join 
+       (org-taskjuggler-get-attribute item attribute)))
+    attributes)))
+
+(defun org-taskjuggler-get-attribute (item attribute)
+  "Return a list of strings containing the properly formatted
+taskjuggler declaration for a given ATTRIBUTE in ITEM (an alist).
+If the ATTRIBUTE is not in ITEM return nil."
+  (cond 
+   ((null item) nil)
+   ((equal (symbol-name attribute) (car (car item)))
+    (cons (format "%s %s" (symbol-name attribute) (cdr (car item)))
+	  (org-taskjuggler-get-attribute (cdr item) attribute)))
+   (t (org-taskjuggler-get-attribute (cdr item) attribute))))
+
+(defun org-taskjuggler-open-resource (resource)
+  "Insert the beginning of a resource declaration. All valid
+attributes from the RESOURCE alist are inserted. If the RESOURCE
+defines a property \"resource_id\" it will be used as the id for
+this resource. Otherwise it will use the ID property. If neither
+is defined it will calculate a unique id for the resource using
+`org-taskjuggler-get-unique-id'."
+  (let ((id (org-taskjuggler-clean-id 
+	     (or (cdr (assoc "resource_id" resource)) 
+		 (cdr (assoc "ID" resource)) 
+		 (cdr (assoc "unique-id" resource)))))
+	(headline (cdr (assoc "headline" resource)))
+	(attributes '(limits vacation shift booking efficiency journalentry rate)))
+    (insert 
+     (concat 
+      "resource " id " \"" headline "\" {\n "
+      (org-taskjuggler-get-attributes resource attributes) "\n"))))
+
+(defun org-taskjuggler-clean-effort (effort)
+  "Translate effort strings into a format acceptable to taskjuggler,
+i.e. REAL UNIT. If the effort string is something like 5:30 it
+will be assumed to be hours and will be translated into 5.5h.
+Otherwise if it contains something like 3.0 it is assumed to be
+days and will be translated into 3.0d. Other formats that
+taskjuggler supports (like weeks, months and years) are currently
+not supported."
+  (cond 
+   ((null effort) effort)
+   ((string-match "\\([0-9]+\\):\\([0-9]+\\)" effort) 
+    (let ((hours (string-to-number (match-string 1 effort)))
+	  (minutes (string-to-number (match-string 2 effort))))
+      (format "%dh" (+ hours (/ minutes 60.0)))))
+   ((string-match "\\([0-9]+\\).\\([0-9]+\\)" effort) (concat effort "d"))
+   (t (error "Not a valid effort (%s)" effort))))
+
+(defun org-taskjuggler-get-priority (priority)
+  "Return a priority between 1 and 1000 based on PRIORITY, an
+org-mode priority string."
+  (max 1 (/ (* 1000 (- org-lowest-priority (string-to-char priority))) 
+	    (- org-lowest-priority org-highest-priority))))
+
+(defun org-taskjuggler-open-task (task)
+  (let* ((unique-id (cdr (assoc "unique-id" task)))
+	(headline (cdr (assoc "headline" task)))
+	(effort (org-taskjuggler-clean-effort (cdr (assoc org-effort-property task))))
+	(depends (cdr (assoc "depends" task)))
+	(allocate (cdr (assoc "allocate" task)))
+	(priority-raw (cdr (assoc "PRIORITY" task)))
+	(priority (and priority-raw (org-taskjuggler-get-priority priority-raw)))
+	(state (cdr (assoc "TODO" task)))
+	(complete (or (and (member state org-done-keywords) "100") 
+		      (cdr (assoc "complete" task))))
+	(parent-ordered (cdr (assoc "parent-ordered" task)))
+	(previous-sibling (cdr (assoc "previous-sibling" task)))
+	(attributes 
+	 '(account start note duration endbuffer endcredit end
+	   flags journalentry length maxend maxstart milestone
+	   minend minstart period reference responsible
+	   scheduling startbuffer startcredit statusnote)))
+    (insert
+     (concat 
+      "task " unique-id " \"" headline "\" {\n" 
+      (if (and parent-ordered previous-sibling)
+	  (format " depends %s\n" previous-sibling)
+	(and depends (format " depends %s\n" depends)))
+      (and allocate (format " purge allocations\n allocate %s\n" allocate))
+      (and complete (format " complete %s\n" complete))
+      (and effort (format " effort %s\n" effort))
+      (and priority (format " priority %s\n" priority))
+      
+      (org-taskjuggler-get-attributes task attributes)
+      "\n"))))
+
+(defun org-taskjuggler-close-maybe (level)
+  (while (> org-export-taskjuggler-old-level level) 
+    (insert "}\n")
+    (setq org-export-taskjuggler-old-level (1- org-export-taskjuggler-old-level)))
+  (when (= org-export-taskjuggler-old-level level)
+    (insert "}\n")))
+
+(defun org-taskjuggler-insert-reports ()
+  (let (report)
+    (dolist (report org-export-taskjuggler-default-reports)
+      (insert report "\n"))))
+
+(provide 'org-taskjuggler)
+
+;;; org-taskjuggler.el ends here

+ 3 - 3
lisp/org-timer.el

@@ -320,17 +320,17 @@ prompt the use if she wants to replace it.
 Called with a numeric prefix argument, use this numeric value as
 the duration of the timer.
 
-Called with a `C-u' prefix argument, use `org-timer-default-timer' 
+Called with a `C-u' prefix arguments, use `org-timer-default-timer'
 without prompting the user for a duration.
 
-With two `C-u' prefix argument, use `org-timer-default-timer'
+With two `C-u' prefix arguments, use `org-timer-default-timer'
 without prompting the user for a duration and automatically
 replace any running timer."
   (interactive "P")
   (let ((minutes (or (and (numberp opt) (number-to-string opt))
 		     (and (listp opt) (not (null opt))
 			  (number-to-string org-timer-default-timer))
-		     (read-from-minibuffer 
+		     (read-from-minibuffer
 		      "How many minutes left? "
 		      (if (not (eq org-timer-default-timer 0))
 			  (number-to-string org-timer-default-timer))))))

+ 13 - 10
lisp/org.el

@@ -259,6 +259,7 @@ to add the symbol `xyz', and the package must have a call to
 	(const :tag "C  sqlinsert:         Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
 	(const :tag "C  toc:               Table of contents for Org-mode buffer" org-toc)
 	(const :tag "C  track:             Keep up with Org-mode development" org-track)
+	(const :tag "C  TaskJuggler:       Export tasks to a TaskJuggler project" org-taskjuggler)
 	(repeat :tag "External packages" :inline t (symbol :tag "Package"))))
 
 (defcustom org-support-shift-select nil
@@ -1530,9 +1531,9 @@ you can use this variable to set the application for a given file
 extension.  The entries in this list are cons cells where the car identifies
 files and the cdr the corresponding command.  Possible values for the
 file identifier are
- \"string\"    A string as a file identifier can be interpreted in different 
+ \"string\"    A string as a file identifier can be interpreted in different
                ways, depending on its contents:
-               
+
                - Alphanumeric characters only:
                  Match links with this file extension.
                  Example: (\"pdf\" . \"evince %s\")
@@ -4977,7 +4978,8 @@ will be prompted for."
 	     '(font-lock-fontified t face org-meta-line))
 	    t)
 	   ((or (member dc1 '("begin:" "end:" "caption:" "label:"
-			      "orgtbl:" "tblfm:" "tblname:"))
+			      "orgtbl:" "tblfm:" "tblname:" "result:"
+			      "results:" "source:" "srcname:" "call:"))
 		(and (match-end 4) (equal dc3 "attr")))
 	    (add-text-properties
 	     beg (match-end 0)
@@ -5513,13 +5515,14 @@ and subscriipts."
 	     org-match-substring-regexp
 	   org-match-substring-with-braces-regexp)
 	 limit t)
-	(let* ((pos (point)) table-p comment-p emph-p)
+	(let* ((pos (point)) table-p comment-p emph-p link-p)
 	  (setq emph-p (get-text-property (match-beginning 3) 'org-emphasis))
+	  (setq link-p (get-text-property (match-beginning 3) 'mouse-face))
 	  (goto-char (point-at-bol))
 	  (setq table-p (org-looking-at-p org-table-dataline-regexp)
 		comment-p (org-looking-at-p "[ \t]*#"))
 	  (goto-char pos)
-	  (if (or comment-p emph-p)
+	  (if (or comment-p emph-p link-p)
 	      t
 	    (put-text-property (match-beginning 3) (match-end 0)
 			       'display
@@ -9993,7 +9996,7 @@ This can be done with a 0 prefix: `C-0 C-c C-w'"
 			  (< pos (save-excursion
 				   (org-end-of-subtree t t))))))
 	      (error "Cannot refile to position inside the tree or region"))
-	  
+
 	  (setq nbuf (or (find-buffer-visiting file)
 			 (find-file-noselect file)))
 	  (if goto
@@ -16859,16 +16862,16 @@ When in an #+include line, visit the include file.  Otherwise call
 `ffap' to visit the file at point."
   (interactive)
   (cond
-   ((org-at-table.el-p)
-    (org-edit-src-code))
-   ((org-at-table-p)
-    (call-interactively 'org-table-edit-formulas))
    ((save-excursion
       (beginning-of-line 1)
       (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
     (find-file (org-trim (match-string 1))))
    ((org-edit-src-code))
    ((org-edit-fixed-width-region))
+   ((org-at-table.el-p)
+    (org-edit-src-code))
+   ((org-at-table-p)
+    (call-interactively 'org-table-edit-formulas))
    (t (call-interactively 'ffap))))