From 80fcb26867ee7f89b0c1e7db9c9e59dc4c9aeb58 Mon Sep 17 00:00:00 2001
From: Adrian Lang <lang@cosmocode.de>
Date: Tue, 23 Mar 2010 11:00:20 +0100
Subject: [PATCH] Rewrite wikitext slicing for section edits

This commit adresses two issues:
  * rawWikiSlices used to drop the first byte of the suffix (usually a newline,
    but custom section edits may not be bound to newlines)
  * con used to insert way too much newlines: the newline that got
    dropped by the bug in rawWikiSlices and one additional newline in prefix
    and text each if they are not terminated by a newline. Now con only inserts
    newlines if there are absolutely no newlines between prefix and text and
    text and suffix.
---
 inc/common.php | 29 +++++++++++++++++------------
 1 file changed, 17 insertions(+), 12 deletions(-)

diff --git a/inc/common.php b/inc/common.php
index 5904dc69b..2877bc00e 100644
--- a/inc/common.php
+++ b/inc/common.php
@@ -894,22 +894,24 @@ function parsePageTemplate($data) {
  * @author Andreas Gohr <andi@splitbrain.org>
  */
 function rawWikiSlices($range,$id,$rev=''){
-    list($from,$to) = explode('-',$range,2);
     $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
-    if(!$from) $from = 0;
-    if(!$to)   $to   = strlen($text)+1;
 
-    $slices[0] = substr($text,0,$from-1);
-    $slices[1] = substr($text,$from-1,$to-$from);
-    $slices[2] = substr($text,$to);
+    // Parse range
+    list($from,$to) = explode('-',$range,2);
+    // Make range zero-based, use defaults if marker is missing
+    $from = !$from ? 0 : ($from - 1);
+    $to   = !$to ? strlen($text) : ($to - 1);
 
+    $slices[0] = substr($text, 0, $from);
+    $slices[1] = substr($text, $from, $to-$from);
+    $slices[2] = substr($text, $to);
     return $slices;
 }
 
 /**
  * Joins wiki text slices
  *
- * function to join the text slices with correct lineendings again.
+ * function to join the text slices.
  * When the pretty parameter is set to true it adds additional empty
  * lines between sections if needed (used on saving).
  *
@@ -917,13 +919,16 @@ function rawWikiSlices($range,$id,$rev=''){
  */
 function con($pre,$text,$suf,$pretty=false){
     if($pretty){
-        if($pre && substr($pre,-1) != "\n") $pre .= "\n";
-        if($suf && substr($text,-1) != "\n") $text .= "\n";
+        if ($pre !== '' && substr($pre, -1) !== "\n" &&
+            substr($text, 0, 1) !== "\n") {
+            $pre .= "\n";
+        }
+        if ($suf !== '' && substr($text, -1) !== "\n" &&
+            substr($suf, 0, 1) !== "\n") {
+            $text .= "\n";
+        }
     }
 
-    // Avoid double newline above section when saving section edit
-    //if($pre) $pre .= "\n";
-    if($suf) $text .= "\n";
     return $pre.$text.$suf;
 }
 
-- 
GitLab