# HG changeset patch
# User Neil <nyamatongwe@gmail.com>
# Date 1516962874 -39600
#      Fri Jan 26 21:34:34 2018 +1100
# Node ID 467e298ac546e78fb5b40398eb2f28034aa327c4
# Parent  7f62c564bab393e3b0b5b8df484f378e946a5af9
Add SC_DOCUMENTOPTION_LARGE option for documents larger than 2 GigaBytes.

diff -r 7f62c564bab3 -r 467e298ac546 cocoa/ScintillaCocoa.h
--- a/cocoa/ScintillaCocoa.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/cocoa/ScintillaCocoa.h	Fri Jan 26 21:34:34 2018 +1100
@@ -107,8 +107,8 @@
 
 	bool GetPasteboardData(NSPasteboard *board, SelectionText *selectedText);
 	void SetPasteboardData(NSPasteboard *board, const SelectionText &selectedText);
-	int TargetAsUTF8(char *text);
-	int EncodedFromUTF8(char *utf8, char *encoded) const;
+	ptrdiff_t TargetAsUTF8(char *text);
+	ptrdiff_t EncodedFromUTF8(char *utf8, char *encoded) const;
 
 	int scrollSpeed;
 	int scrollTicks;
diff -r 7f62c564bab3 -r 467e298ac546 cocoa/ScintillaCocoa.mm
--- a/cocoa/ScintillaCocoa.mm	Fri Jan 26 20:45:31 2018 +1100
+++ b/cocoa/ScintillaCocoa.mm	Fri Jan 26 21:34:34 2018 +1100
@@ -1320,7 +1320,7 @@
 		}
 	} else {
 		rcSel.top = rcSel.bottom = rcSel.right = rcSel.left = -1;
-		for (int l = startLine; l <= endLine; l++) {
+		for (Sci::Line l = startLine; l <= endLine; l++) {
 			startPos = WndProc(SCI_GETLINESELSTARTPOSITION, l, 0);
 			endPos = WndProc(SCI_GETLINESELENDPOSITION, l, 0);
 			if (endPos == startPos) continue;
@@ -1571,8 +1571,8 @@
 
 // Returns the target converted to UTF8.
 // Return the length in bytes.
-int ScintillaCocoa::TargetAsUTF8(char *text) {
-	const int targetLength = targetEnd - targetStart;
+ptrdiff_t ScintillaCocoa::TargetAsUTF8(char *text) {
+	const Sci::Position targetLength = targetEnd - targetStart;
 	if (IsUnicodeMode()) {
 		if (text)
 			pdoc->GetCharRange(text, targetStart, targetLength);
@@ -1588,7 +1588,7 @@
 		if (text)
 			memcpy(text, tmputf.c_str(), tmputf.length());
 		CFRelease(cfsVal);
-		return static_cast<int>(tmputf.length());
+		return static_cast<ptrdiff_t>(tmputf.length());
 	}
 	return targetLength;
 }
@@ -1615,7 +1615,7 @@
 
 // Return character range of a line.
 NSRange ScintillaCocoa::RangeForVisibleLine(NSInteger lineVisible) {
-	const Range posRangeLine = RangeDisplayLine(static_cast<int>(lineVisible));
+	const Range posRangeLine = RangeDisplayLine(static_cast<Sci::Line>(lineVisible));
 	return CharactersFromPositions(NSMakeRange(posRangeLine.First(),
 				       posRangeLine.Last() - posRangeLine.First()));
 }
@@ -1625,7 +1625,7 @@
 // Returns visible line number of a text position in characters.
 NSInteger ScintillaCocoa::VisibleLineForIndex(NSInteger index) {
 	const NSRange rangePosition = PositionsFromCharacters(NSMakeRange(index, 0));
-	const int lineVisible = DisplayFromPosition(static_cast<int>(rangePosition.location));
+	const Sci::Line lineVisible = DisplayFromPosition(static_cast<Sci::Position>(rangePosition.location));
 	return lineVisible;
 }
 
@@ -1672,12 +1672,12 @@
 
 // Translates a UTF8 string into the document encoding.
 // Return the length of the result in bytes.
-int ScintillaCocoa::EncodedFromUTF8(char *utf8, char *encoded) const {
-	const int inputLength = (lengthForEncode >= 0) ? lengthForEncode : static_cast<int>(strlen(utf8));
+ptrdiff_t ScintillaCocoa::EncodedFromUTF8(char *utf8, char *encoded) const {
+	const size_t inputLength = (lengthForEncode >= 0) ? lengthForEncode : strlen(utf8);
 	if (IsUnicodeMode()) {
 		if (encoded)
 			memcpy(encoded, utf8, inputLength);
-		return inputLength;
+		return static_cast<ptrdiff_t>(inputLength);
 	} else {
 		// Need to convert
 		const CFStringEncoding encoding = EncodingFromCharacterSet(IsUnicodeMode(),
@@ -1688,7 +1688,7 @@
 		if (encoded)
 			memcpy(encoded, sEncoded.c_str(), sEncoded.length());
 		CFRelease(cfsVal);
-		return static_cast<int>(sEncoded.length());
+		return static_cast<ptrdiff_t>(sEncoded.length());
 	}
 }
 
@@ -1769,14 +1769,14 @@
 void ScintillaCocoa::WillDraw(NSRect rect) {
 	RefreshStyleData();
 	PRectangle rcWillDraw = NSRectToPRectangle(rect);
-	const int posAfterArea = PositionAfterArea(rcWillDraw);
-	const int posAfterMax = PositionAfterMaxStyling(posAfterArea, true);
+	const Sci::Position posAfterArea = PositionAfterArea(rcWillDraw);
+	const Sci::Position posAfterMax = PositionAfterMaxStyling(posAfterArea, true);
 	pdoc->StyleToAdjustingLineDuration(posAfterMax);
 	StartIdleStyling(posAfterMax < posAfterArea);
 	NotifyUpdateUI();
 	if (WrapLines(WrapScope::wsVisible)) {
 		// Wrap may have reduced number of lines so more lines may need to be styled
-		const int posAfterAreaWrapped = PositionAfterArea(rcWillDraw);
+		const Sci::Position posAfterAreaWrapped = PositionAfterArea(rcWillDraw);
 		pdoc->EnsureStyledTo(posAfterAreaWrapped);
 		// The wrapping process has changed the height of some lines so redraw all.
 		Redraw();
diff -r 7f62c564bab3 -r 467e298ac546 doc/ScintillaDoc.html
--- a/doc/ScintillaDoc.html	Fri Jan 26 20:45:31 2018 +1100
+++ b/doc/ScintillaDoc.html	Fri Jan 26 21:34:34 2018 +1100
@@ -5786,7 +5786,9 @@
     <code>SC_DOCUMENTOPTION_DEFAULT</code> (0) choosing standard options.
     <code>SC_DOCUMENTOPTION_NOSTYLES</code> (1) stops allocation of memory to style characters
     which saves significant memory, often 40% with the whole document treated as being style 0.
-    Lexers may still produce visual styling by using indicators.</p>
+    Lexers may still produce visual styling by using indicators.
+    <code>SC_DOCUMENTOPTION_LARGE</code> (2) accomodates documents larger than 2 GigaBytes.
+    </p>
 
 <h4>ILoader</h4>
 
diff -r 7f62c564bab3 -r 467e298ac546 doc/ScintillaHistory.html
--- a/doc/ScintillaHistory.html	Fri Jan 26 20:45:31 2018 +1100
+++ b/doc/ScintillaHistory.html	Fri Jan 26 21:34:34 2018 +1100
@@ -540,6 +540,9 @@
 	Add SC_DOCUMENTOPTION_NOSTYLES option to stop allocating memory for character styles.
 	</li>
 	<li>
+	Add SC_DOCUMENTOPTION_LARGE option to accomodate documents larger than 2 GigaBytes.
+	</li>
+	<li>
 	Add SCI_GETMOVEEXTENDSSELECTION to allow applications to add more
 	complex selection commands.
 	</li>
diff -r 7f62c564bab3 -r 467e298ac546 include/Scintilla.h
--- a/include/Scintilla.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/include/Scintilla.h	Fri Jan 26 21:34:34 2018 +1100
@@ -960,6 +960,7 @@
 #define SCI_GETTECHNOLOGY 2631
 #define SC_DOCUMENTOPTION_DEFAULT 0
 #define SC_DOCUMENTOPTION_NOSTYLES 1
+#define SC_DOCUMENTOPTION_LARGE 2
 #define SCI_CREATELOADER 2632
 #define SCI_FINDINDICATORSHOW 2640
 #define SCI_FINDINDICATORFLASH 2641
diff -r 7f62c564bab3 -r 467e298ac546 include/Scintilla.iface
--- a/include/Scintilla.iface	Fri Jan 26 20:45:31 2018 +1100
+++ b/include/Scintilla.iface	Fri Jan 26 21:34:34 2018 +1100
@@ -2542,6 +2542,7 @@
 enu DocumentOption=SC_DOCUMENTOPTION_
 val SC_DOCUMENTOPTION_DEFAULT=0
 val SC_DOCUMENTOPTION_NOSTYLES=1
+val SC_DOCUMENTOPTION_LARGE=2
 
 # Create an ILoader*.
 fun int CreateLoader=2632(int bytes, int documentOption)
diff -r 7f62c564bab3 -r 467e298ac546 qt/ScintillaEdit/ScintillaDocument.cpp
--- a/qt/ScintillaEdit/ScintillaDocument.cpp	Fri Jan 26 20:45:31 2018 +1100
+++ b/qt/ScintillaEdit/ScintillaDocument.cpp	Fri Jan 26 21:34:34 2018 +1100
@@ -91,7 +91,7 @@
 ScintillaDocument::ScintillaDocument(QObject *parent, void *pdoc_) :
     QObject(parent), pdoc(pdoc_), docWatcher(0) {
     if (!pdoc) {
-        pdoc = new Document();
+        pdoc = new Document(SC_DOCUMENTOPTION_DEFAULT);
     }
     docWatcher = new WatcherHelper(this);
     (static_cast<Document *>(pdoc))->AddRef();
diff -r 7f62c564bab3 -r 467e298ac546 qt/ScintillaEditBase/ScintillaQt.h
--- a/qt/ScintillaEditBase/ScintillaQt.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/qt/ScintillaEditBase/ScintillaQt.h	Fri Jan 26 21:34:34 2018 +1100
@@ -107,7 +107,7 @@
 	bool ValidCodePage(int codePage) const override;
 
 private:
-	void ScrollText(int linesToMove) override;
+	void ScrollText(Sci::Line linesToMove) override;
 	void SetVerticalScrollPos() override;
 	void SetHorizontalScrollPos() override;
 	bool ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) override;
diff -r 7f62c564bab3 -r 467e298ac546 scripts/HeaderOrder.txt
--- a/scripts/HeaderOrder.txt	Fri Jan 26 20:45:31 2018 +1100
+++ b/scripts/HeaderOrder.txt	Fri Jan 26 21:34:34 2018 +1100
@@ -28,6 +28,7 @@
 #include <ctime>
 #include <cmath>
 #include <climits>
+#include <cinttypes>
 
 // C++ standard library
 #include <stdexcept>
diff -r 7f62c564bab3 -r 467e298ac546 src/CellBuffer.cxx
--- a/src/CellBuffer.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/CellBuffer.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -364,12 +364,15 @@
 	currentAction++;
 }
 
-CellBuffer::CellBuffer(bool hasStyles_) :
-	hasStyles(hasStyles_) {
+CellBuffer::CellBuffer(bool hasStyles_, bool largeDocument_) :
+	hasStyles(hasStyles_), largeDocument(largeDocument_) {
 	readOnly = false;
 	utf8LineEnds = 0;
 	collectingUndo = true;
-	plv.reset(new LineVector<Sci::Position>());
+	if (largeDocument)
+		plv.reset(new LineVector<Sci::Position>());
+	else
+		plv.reset(new LineVector<int>());
 }
 
 CellBuffer::~CellBuffer() {
diff -r 7f62c564bab3 -r 467e298ac546 src/CellBuffer.h
--- a/src/CellBuffer.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/CellBuffer.h	Fri Jan 26 21:34:34 2018 +1100
@@ -108,6 +108,7 @@
 class CellBuffer {
 private:
 	bool hasStyles;
+	bool largeDocument;
 	SplitVector<char> substance;
 	SplitVector<char> style;
 	bool readOnly;
@@ -126,7 +127,7 @@
 
 public:
 
-	CellBuffer(bool hasStyles_);
+	CellBuffer(bool hasStyles_, bool largeDocument_);
 	// Deleted so CellBuffer objects can not be copied.
 	CellBuffer(const CellBuffer &) = delete;
 	void operator=(const CellBuffer &) = delete;
diff -r 7f62c564bab3 -r 467e298ac546 src/Document.cxx
--- a/src/Document.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/Document.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -10,6 +10,7 @@
 #include <cassert>
 #include <cstring>
 #include <cstdio>
+#include <cmath>
 
 #include <stdexcept>
 #include <string>
@@ -90,7 +91,7 @@
 }
 
 Document::Document(int options) :
-	cb((options & SC_DOCUMENTOPTION_NOSTYLES) == 0) {
+	cb((options & SC_DOCUMENTOPTION_NOSTYLES) == 0, (options & SC_DOCUMENTOPTION_LARGE) != 0) {
 	refCount = 0;
 #ifdef _WIN32
 	eolMode = SC_EOL_CRLF;
@@ -560,7 +561,7 @@
 }
 
 Sci::Position Document::ClampPositionIntoDocument(Sci::Position pos) const {
-	return Sci::clamp(pos, 0, static_cast<Sci::Position>(Length()));
+	return Sci::clamp(pos, static_cast<Sci::Position>(0), static_cast<Sci::Position>(Length()));
 }
 
 bool Document::IsCrLf(Sci::Position pos) const {
@@ -581,7 +582,7 @@
 		const int widthCharBytes = UTF8BytesOfLead[leadByte];
 		Sci::Position lengthDoc = static_cast<Sci::Position>(Length());
 		if ((pos + widthCharBytes) > lengthDoc)
-			return lengthDoc - pos;
+			return static_cast<int>(lengthDoc - pos);
 		else
 			return widthCharBytes;
 	} else if (dbcsCodePage) {
@@ -828,7 +829,7 @@
 			Sci::Position startUTF = position;
 			Sci::Position endUTF = position;
 			if (InGoodUTF8(position, startUTF, endUTF)) {
-				const int widthCharBytes = endUTF - startUTF;
+				const int widthCharBytes = static_cast<int>(endUTF - startUTF);
 				unsigned char charBytes[UTF8MaxBytes] = { 0, 0, 0, 0 };
 				for (int b = 0; b<widthCharBytes; b++)
 					charBytes[b] = static_cast<unsigned char>(cb.CharAt(startUTF + b));
@@ -878,7 +879,7 @@
 			const Sci::Position posNext = NextPosition(pos, increment);
 			if (posNext == pos)
 				return INVALID_POSITION;
-			if (abs(pos-posNext) > 3)	// 4 byte character = 2*UTF16.
+			if (std::abs(pos-posNext) > 3)	// 4 byte character = 2*UTF16.
 				characterOffset -= increment;
 			pos = posNext;
 			characterOffset -= increment;
@@ -1341,7 +1342,7 @@
 			if (ch == ' ')
 				indent++;
 			else if (ch == '\t')
-				indent = NextTab(indent, tabInChars);
+				indent = static_cast<int>(NextTab(indent, tabInChars));
 			else
 				return indent;
 		}
@@ -1843,7 +1844,7 @@
  * searches (just pass minPos > maxPos to do a backward search)
  * Has not been tested with backwards DBCS searches yet.
  */
-long Document::FindText(Sci::Position minPos, Sci::Position maxPos, const char *search,
+Sci::Position Document::FindText(Sci::Position minPos, Sci::Position maxPos, const char *search,
                         int flags, Sci::Position *length) {
 	if (*length <= 0)
 		return minPos;
@@ -2513,7 +2514,7 @@
 	~BuiltinRegex() override {
 	}
 
-	long FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
+	Sci::Position FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
                         bool caseSensitive, bool word, bool wordStart, int flags,
                         Sci::Position *length) override;
 
@@ -2973,7 +2974,7 @@
 
 }
 
-long BuiltinRegex::FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
+Sci::Position BuiltinRegex::FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
                         bool caseSensitive, bool, bool, int flags,
                         Sci::Position *length) {
 
diff -r 7f62c564bab3 -r 467e298ac546 src/Document.h
--- a/src/Document.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/Document.h	Fri Jan 26 21:34:34 2018 +1100
@@ -88,7 +88,7 @@
 public:
 	virtual ~RegexSearchBase() {}
 
-	virtual long FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
+	virtual Sci::Position FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
                         bool caseSensitive, bool word, bool wordStart, int flags, Sci::Position *length) = 0;
 
 	///@return String with the substitutions, must remain valid until the next call or destruction
@@ -403,7 +403,7 @@
 	bool MatchesWordOptions(bool word, bool wordStart, Sci::Position pos, Sci::Position length) const;
 	bool HasCaseFolder() const;
 	void SetCaseFolder(CaseFolder *pcf_);
-	long FindText(Sci::Position minPos, Sci::Position maxPos, const char *search, int flags, Sci::Position *length);
+	Sci::Position FindText(Sci::Position minPos, Sci::Position maxPos, const char *search, int flags, Sci::Position *length);
 	const char *SubstituteByPosition(const char *text, Sci::Position *length);
 	Sci::Line LinesTotal() const;
 
diff -r 7f62c564bab3 -r 467e298ac546 src/EditView.cxx
--- a/src/EditView.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/EditView.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -12,6 +12,7 @@
 #include <cctype>
 #include <cstdio>
 #include <cmath>
+#include <cinttypes>
 
 #include <stdexcept>
 #include <string>
@@ -339,7 +340,7 @@
 	PLATFORM_ASSERT(posLineEnd >= posLineStart);
 	Sci::Line lineCaret = static_cast<Sci::Line>(model.pdoc->LineFromPosition(model.sel.MainCaret()));
 	return llc.Retrieve(lineNumber, lineCaret,
-		posLineEnd - posLineStart, model.pdoc->GetStyleClock(),
+		static_cast<int>(posLineEnd - posLineStart), model.pdoc->GetStyleClock(),
 		model.LinesOnScreen() + 1, model.pdoc->LinesTotal());
 }
 
@@ -410,19 +411,20 @@
 		ll->widthLine = LineLayout::wrapWidthInfinite;
 		ll->lines = 1;
 		if (vstyle.edgeState == EDGE_BACKGROUND) {
-			ll->edgeColumn = model.pdoc->FindColumn(line, vstyle.theEdge.column);
-			if (ll->edgeColumn >= posLineStart) {
-				ll->edgeColumn -= posLineStart;
+			Sci::Position edgePosition = model.pdoc->FindColumn(line, vstyle.theEdge.column);
+			if (edgePosition >= posLineStart) {
+				edgePosition -= posLineStart;
 			}
+			ll->edgeColumn = static_cast<int>(edgePosition);
 		} else {
 			ll->edgeColumn = -1;
 		}
 
 		// Fill base line layout
-		const int lineLength = posLineEnd - posLineStart;
+		const int lineLength = static_cast<int>(posLineEnd - posLineStart);
 		model.pdoc->GetCharRange(ll->chars.get(), posLineStart, lineLength);
 		model.pdoc->GetStyleRange(ll->styles.get(), posLineStart, lineLength);
-		const int numCharsBeforeEOL = static_cast<Sci::Position>(model.pdoc->LineEnd(line)) - posLineStart;
+		const int numCharsBeforeEOL = static_cast<int>(model.pdoc->LineEnd(line) - posLineStart);
 		const int numCharsInLine = (vstyle.viewEOL) ? lineLength : numCharsBeforeEOL;
 		for (Sci::Position styleInLine = 0; styleInLine < numCharsInLine; styleInLine++) {
 			const unsigned char styleByte = ll->styles[styleInLine];
@@ -541,10 +543,10 @@
 				ll->wrapIndent = vstyle.aveCharWidth; // Indent to show start visual
 			ll->lines = 0;
 			// Calculate line start positions based upon width.
-			int lastGoodBreak = 0;
-			int lastLineStart = 0;
+			Sci::Position lastGoodBreak = 0;
+			Sci::Position lastLineStart = 0;
 			XYACCUMULATOR startOffset = 0;
-			int p = 0;
+			Sci::Position p = 0;
 			while (p < ll->numCharsInLine) {
 				if ((ll->positions[p + 1] - startOffset) >= width) {
 					if (lastGoodBreak == lastLineStart) {
@@ -561,7 +563,7 @@
 					}
 					lastLineStart = lastGoodBreak;
 					ll->lines++;
-					ll->SetLineStart(ll->lines, lastGoodBreak);
+					ll->SetLineStart(ll->lines, static_cast<int>(lastGoodBreak));
 					startOffset = ll->positions[lastGoodBreak];
 					// take into account the space for start wrap mark and indent
 					startOffset -= ll->wrapIndent;
@@ -604,7 +606,7 @@
 	AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
 	if (surface && ll) {
 		LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
-		const int posInLine = pos.Position() - posLineStart;
+		const int posInLine = static_cast<int>(pos.Position() - posLineStart);
 		pt = ll->PointFromPosition(posInLine, vs.lineHeight, pe);
 		pt.y += (lineVisible - topLine) * vs.lineHeight;
 		pt.x += vs.textStart - model.xOffset;
@@ -624,7 +626,7 @@
 	if (surface && ll) {
 		LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
 		const Sci::Line lineStartSet = model.cs.DisplayFromDoc(lineDoc);
-		const int subLine = lineVisible - lineStartSet;
+		const int subLine = static_cast<int>(lineVisible - lineStartSet);
 		if (subLine < ll->lines) {
 			rangeSubLine = ll->SubLineRange(subLine);
 			if (subLine == ll->lines-1) {
@@ -654,7 +656,7 @@
 	if (surface && ll) {
 		LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
 		const Sci::Line lineStartSet = model.cs.DisplayFromDoc(lineDoc);
-		const int subLine = visibleLine - lineStartSet;
+		const int subLine = static_cast<int>(visibleLine - lineStartSet);
 		if (subLine < ll->lines) {
 			const Range rangeSubLine = ll->SubLineRange(subLine);
 			const XYPOSITION subLineStart = ll->positions[rangeSubLine.start];
@@ -787,7 +789,8 @@
 
 void EditView::DrawIndentGuide(Surface *surface, Sci::Line lineVisible, int lineHeight, Sci::Position start, PRectangle rcSegment, bool highlight) {
 	Point from = Point::FromInts(0, ((lineVisible & 1) && (lineHeight & 1)) ? 1 : 0);
-	PRectangle rcCopyArea = PRectangle::FromInts(start + 1, static_cast<int>(rcSegment.top), start + 2, static_cast<int>(rcSegment.bottom));
+	PRectangle rcCopyArea = PRectangle::FromInts(static_cast<int>(start + 1), static_cast<int>(rcSegment.top),
+		static_cast<int>(start + 2), static_cast<int>(rcSegment.bottom));
 	surface->Copy(rcCopyArea, from,
 		highlight ? *pixmapIndentGuideHighlight : *pixmapIndentGuide);
 }
@@ -1305,7 +1308,7 @@
 	FontAlias fontText = vsDraw.styles[styleMain].font;
 	surface->DrawTextClipped(rcCaret, fontText,
 		rcCaret.top + vsDraw.maxAscent, &ll->chars[offsetFirstChar],
-		numCharsToDraw, vsDraw.styles[styleMain].back,
+		static_cast<int>(numCharsToDraw), vsDraw.styles[styleMain].back,
 		caretColour);
 }
 
@@ -1326,7 +1329,7 @@
 			else
 				posCaret.SetPosition(model.pdoc->MovePositionOutsideChar(posCaret.Position()-1, -1));
 		}
-		const int offset = posCaret.Position() - posLineStart;
+		const int offset = static_cast<int>(posCaret.Position() - posLineStart);
 		const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
 		const XYPOSITION virtualOffset = posCaret.VirtualSpace() * spaceWidth;
 		if (ll->InLine(offset, subLine) && offset <= ll->numCharsBeforeEOL) {
@@ -1740,11 +1743,11 @@
 					if (phasesDraw != phasesOne) {
 						surface->DrawTextTransparent(rcSegment, textFont,
 							rcSegment.top + vsDraw.maxAscent, &ll->chars[ts.start],
-							i - ts.start + 1, textFore);
+							static_cast<int>(i - ts.start + 1), textFore);
 					} else {
 						surface->DrawTextNoClip(rcSegment, textFont,
 							rcSegment.top + vsDraw.maxAscent, &ll->chars[ts.start],
-							i - ts.start + 1, textFore, textBack);
+							static_cast<int>(i - ts.start + 1), textFore, textBack);
 					}
 				}
 				if (vsDraw.viewWhitespace != wsInvisible ||
@@ -1821,7 +1824,7 @@
 		// Find the most recent line with some text
 
 		Sci::Line lineLastWithText = line;
-		while (lineLastWithText > std::max(line - 20, 0) && model.pdoc->IsWhiteLine(lineLastWithText)) {
+		while (lineLastWithText > std::max(line - 20, static_cast<Sci::Line>(0)) && model.pdoc->IsWhiteLine(lineLastWithText)) {
 			lineLastWithText--;
 		}
 		if (lineLastWithText < line) {
@@ -2038,7 +2041,7 @@
 				// Only visible lines should be handled by the code within the loop
 				PLATFORM_ASSERT(model.cs.GetVisible(lineDoc));
 				const Sci::Line lineStartSet = model.cs.DisplayFromDoc(lineDoc);
-				const int subLine = visibleLine - lineStartSet;
+				const int subLine = static_cast<int>(visibleLine - lineStartSet);
 
 				// Copy this line and its styles from the document into local arrays
 				// and determine the x position at which each character starts.
@@ -2189,7 +2192,7 @@
 	return ColourDesired(std::min(r, 0xffu), std::min(g, 0xffu), std::min(b, 0xffu));
 }
 
-long EditView::FormatRange(bool draw, Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
+Sci::Position EditView::FormatRange(bool draw, Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
 	const EditModel &model, const ViewStyle &vs) {
 	// Can't use measurements cached for screen
 	posCache.Clear();
@@ -2298,7 +2301,7 @@
 
 		// Copy this line and its styles from the document into local arrays
 		// and determine the x position at which each character starts.
-		LineLayout ll(static_cast<Sci::Position>(model.pdoc->LineStart(lineDoc + 1) - model.pdoc->LineStart(lineDoc) + 1));
+		LineLayout ll(static_cast<int>(model.pdoc->LineStart(lineDoc + 1) - model.pdoc->LineStart(lineDoc) + 1));
 		LayoutLine(model, lineDoc, surfaceMeasure, vsPrint, &ll, widthPrint);
 
 		ll.containsCaret = false;
@@ -2330,7 +2333,7 @@
 			(ypos + vsPrint.lineHeight <= pfr->rc.bottom) &&
 			(visibleLine >= 0)) {
 			char number[100];
-			sprintf(number, "%d" lineNumberPrintSpace, lineDoc + 1);
+			sprintf(number, "%" PRIdPTR lineNumberPrintSpace, lineDoc + 1);
 			PRectangle rcNumber = rcLine;
 			rcNumber.right = rcNumber.left + lineNumberWidth;
 			// Right justify
diff -r 7f62c564bab3 -r 467e298ac546 src/EditView.h
--- a/src/EditView.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/EditView.h	Fri Jan 26 21:34:34 2018 +1100
@@ -145,7 +145,7 @@
 		const ViewStyle &vsDraw);
 	void FillLineRemainder(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
 		Sci::Line line, PRectangle rcArea, int subLine) const;
-	long FormatRange(bool draw, Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
+	Sci::Position FormatRange(bool draw, Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
 		const EditModel &model, const ViewStyle &vs);
 };
 
diff -r 7f62c564bab3 -r 467e298ac546 src/Editor.cxx
--- a/src/Editor.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/Editor.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -11,8 +11,8 @@
 #include <cstring>
 #include <cctype>
 #include <cstdio>
-
 #include <cmath>
+
 #include <stdexcept>
 #include <string>
 #include <vector>
@@ -900,11 +900,11 @@
 		Sci::Line lineDisplay = cs.DisplayFromDoc(lineDoc);
 		if (moveDir > 0) {
 			// lineDisplay is already line before fold as lines in fold use display line of line after fold
-			lineDisplay = Sci::clamp(lineDisplay, 0, cs.LinesDisplayed());
+			lineDisplay = Sci::clamp(lineDisplay, static_cast<Sci::Line>(0), cs.LinesDisplayed());
 			return SelectionPosition(static_cast<Sci::Position>(
 				pdoc->LineStart(cs.DocFromDisplay(lineDisplay))));
 		} else {
-			lineDisplay = Sci::clamp(lineDisplay - 1, 0, cs.LinesDisplayed());
+			lineDisplay = Sci::clamp(lineDisplay - 1, static_cast<Sci::Line>(0), cs.LinesDisplayed());
 			return SelectionPosition(static_cast<Sci::Position>(
 				pdoc->LineEnd(cs.DocFromDisplay(lineDisplay))));
 		}
@@ -925,16 +925,16 @@
  */
 void Editor::SetLastXChosen() {
 	Point pt = PointMainCaret();
-	lastXChosen = static_cast<Sci::Position>(pt.x) + xOffset;
+	lastXChosen = static_cast<int>(pt.x) + xOffset;
 }
 
 void Editor::ScrollTo(Sci::Line line, bool moveThumb) {
-	const Sci::Line topLineNew = Sci::clamp(line, 0, MaxScrollPos());
+	const Sci::Line topLineNew = Sci::clamp(line, static_cast<Sci::Line>(0), MaxScrollPos());
 	if (topLineNew != topLine) {
 		// Try to optimise small scrolls
 #ifndef UNDER_CE
 		const Sci::Line linesToMove = topLine - topLineNew;
-		const bool performBlit = (abs(linesToMove) <= 10) && (paintState == notPainting);
+		const bool performBlit = (std::abs(linesToMove) <= 10) && (paintState == notPainting);
 		willRedrawAll = !performBlit;
 #endif
 		SetTopLine(topLineNew);
@@ -1073,7 +1073,7 @@
 	} else if ((pt.y + vs.lineHeight - 1) > rcClient.bottom) {
 		Sci::Position yOfLastLineFullyDisplayed = static_cast<Sci::Position>(rcClient.top) + (LinesOnScreen() - 1) * vs.lineHeight;
 		MovePositionTo(SPositionFromLocation(
-		            Point::FromInts(lastXChosen - xOffset, static_cast<int>(rcClient.top) + yOfLastLineFullyDisplayed),
+		            Point::FromInts(lastXChosen - xOffset, static_cast<int>(rcClient.top + yOfLastLineFullyDisplayed)),
 					false, false, UserVirtualSpace()),
 		        Selection::noSel, ensureVisible);
 	}
@@ -1150,7 +1150,7 @@
 	if ((options & xysVertical) && (pt.y < rcClient.top || ptBottomCaret.y >= rcClient.bottom || (caretYPolicy & CARET_STRICT) != 0)) {
 		const Sci::Line lineCaret = DisplayFromPosition(range.caret.Position());
 		const Sci::Line linesOnScreen = LinesOnScreen();
-		const Sci::Line halfScreen = std::max(linesOnScreen - 1, 2) / 2;
+		const Sci::Line halfScreen = std::max(linesOnScreen - 1, static_cast<Sci::Line>(2)) / 2;
 		const bool bSlop = (caretYPolicy & CARET_SLOP) != 0;
 		const bool bStrict = (caretYPolicy & CARET_STRICT) != 0;
 		const bool bJump = (caretYPolicy & CARET_JUMPS) != 0;
@@ -1169,7 +1169,7 @@
 				} else {
 					// yMarginT must equal to caretYSlop, with a minimum of 1 and
 					// a maximum of slightly less than half the heigth of the text area.
-					yMarginT = Sci::clamp(caretYSlop, 1, halfScreen);
+					yMarginT = Sci::clamp(static_cast<Sci::Line>(caretYSlop), static_cast<Sci::Line>(1), halfScreen);
 					if (bEven) {
 						yMarginB = yMarginT;
 					} else {
@@ -1179,7 +1179,7 @@
 				yMoveT = yMarginT;
 				if (bEven) {
 					if (bJump) {
-						yMoveT = Sci::clamp(caretYSlop * 3, 1, halfScreen);
+						yMoveT = Sci::clamp(static_cast<Sci::Line>(caretYSlop * 3), static_cast<Sci::Line>(1), halfScreen);
 					}
 					yMoveB = yMoveT;
 				} else {
@@ -1194,7 +1194,7 @@
 				}
 			} else {	// Not strict
 				yMoveT = bJump ? caretYSlop * 3 : caretYSlop;
-				yMoveT = Sci::clamp(yMoveT, 1, halfScreen);
+				yMoveT = Sci::clamp(yMoveT, static_cast<Sci::Line>(1), halfScreen);
 				if (bEven) {
 					yMoveB = yMoveT;
 				} else {
@@ -1244,7 +1244,7 @@
 				newXY.topLine = std::min(newXY.topLine, lineCaret);
 			}
 		}
-		newXY.topLine = Sci::clamp(newXY.topLine, 0, MaxScrollPos());
+		newXY.topLine = Sci::clamp(newXY.topLine, static_cast<Sci::Line>(0), MaxScrollPos());
 	}
 
 	// Horizontal positioning
@@ -1357,8 +1357,8 @@
 				newXY.xOffset = std::max(newXY.xOffset, minOffset);
 			} else {
 				// Shift to right to show anchor or as much of range as possible
-				const int minOffset = static_cast<Sci::Position>(ptAnchor.x + xOffset - rcClient.right) + 1;
-				const int maxOffset = static_cast<Sci::Position>(pt.x + xOffset - rcClient.left) - 1;
+				const int minOffset = static_cast<int>(ptAnchor.x + xOffset - rcClient.right) + 1;
+				const int maxOffset = static_cast<int>(pt.x + xOffset - rcClient.left) - 1;
 				newXY.xOffset = std::max(newXY.xOffset, minOffset);
 				newXY.xOffset = std::min(newXY.xOffset, maxOffset);
 			}
@@ -1384,7 +1384,7 @@
 				const PRectangle rcText = GetTextRectangle();
 				if (horizontalScrollBarVisible &&
 					rcText.Width() + xOffset > scrollWidth) {
-					scrollWidth = xOffset + static_cast<Sci::Position>(rcText.Width());
+					scrollWidth = xOffset + static_cast<int>(rcText.Width());
 					SetScrollBars();
 				}
 			}
@@ -1508,7 +1508,7 @@
 		Sci::Line lineToWrap = wrapPending.start;
 		Sci::Line lineToWrapEnd = std::min(wrapPending.end, pdoc->LinesTotal());
 		const Sci::Line lineDocTop = cs.DocFromDisplay(topLine);
-		const int subLineTop = topLine - cs.DisplayFromDoc(lineDocTop);
+		const int subLineTop = static_cast<int>(topLine - cs.DisplayFromDoc(lineDocTop));
 		if (ws == WrapScope::wsVisible) {
 			lineToWrap = Sci::clamp(lineDocTop-5, wrapPending.start, pdoc->LinesTotal());
 			// Priority wrap to just after visible area.
@@ -1566,7 +1566,7 @@
 
 	if (wrapOccurred) {
 		SetScrollBars();
-		SetTopLine(Sci::clamp(goodTopLine, 0, MaxScrollPos()));
+		SetTopLine(Sci::clamp(goodTopLine, static_cast<Sci::Line>(0), MaxScrollPos()));
 		SetVerticalScrollPos();
 	}
 
@@ -1779,7 +1779,7 @@
 // This is mostly copied from the Paint method but with some things omitted
 // such as the margin markers, line numbers, selection and caret
 // Should be merged back into a combined Draw method.
-long Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
+Sci::Position Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
 	if (!pfr)
 		return 0;
 
@@ -1819,7 +1819,7 @@
 	// TODO: ensure always showing as many lines as possible
 	// May not be, if, for example, window made larger
 	if (topLine > MaxScrollPos()) {
-		SetTopLine(Sci::clamp(topLine, 0, MaxScrollPos()));
+		SetTopLine(Sci::clamp(topLine, static_cast<Sci::Line>(0), MaxScrollPos()));
 		SetVerticalScrollPos();
 		Redraw();
 	}
@@ -2613,7 +2613,7 @@
 		if (mh.modificationType & SC_MOD_CHANGEANNOTATION) {
 			Sci::Line lineDoc = static_cast<Sci::Line>(pdoc->LineFromPosition(mh.position));
 			if (vs.annotationVisible) {
-				if (cs.SetHeight(lineDoc, cs.GetHeight(lineDoc) + mh.annotationLinesAdded)) {
+				if (cs.SetHeight(lineDoc, static_cast<int>(cs.GetHeight(lineDoc) + mh.annotationLinesAdded))) {
 					SetScrollBars();
 				}
 				Redraw();
@@ -2623,7 +2623,7 @@
 		if (mh.linesAdded != 0) {
 			// Avoid scrolling of display if change before current display
 			if (mh.position < posTopLine && !CanDeferToLastStep(mh)) {
-				Sci::Line newTop = Sci::clamp(topLine + mh.linesAdded, 0, MaxScrollPos());
+				Sci::Line newTop = Sci::clamp(topLine + mh.linesAdded, static_cast<Sci::Line>(0), MaxScrollPos());
 				if (newTop != topLine) {
 					SetTopLine(newTop);
 					SetVerticalScrollPos();
@@ -2683,7 +2683,7 @@
 		scn.line = mh.line;
 		scn.foldLevelNow = mh.foldLevelNow;
 		scn.foldLevelPrev = mh.foldLevelPrev;
-		scn.token = mh.token;
+		scn.token = static_cast<int>(mh.token);
 		scn.annotationLinesAdded = mh.annotationLinesAdded;
 		NotifyParent(scn);
 	}
@@ -2843,7 +2843,7 @@
 	const Sci::Line topStutterLine = topLine + caretYSlop;
 	const Sci::Line bottomStutterLine = static_cast<Sci::Line>(
 	    pdoc->LineFromPosition(PositionFromLocation(
-	                Point::FromInts(lastXChosen - xOffset, direction * vs.lineHeight * LinesToScroll())))
+	                Point::FromInts(lastXChosen - xOffset, direction * vs.lineHeight * static_cast<int>(LinesToScroll()))))
 	    - caretYSlop - 1);
 
 	if (stuttered && (direction < 0 && currentLine > topStutterLine)) {
@@ -2853,16 +2853,17 @@
 
 	} else if (stuttered && (direction > 0 && currentLine < bottomStutterLine)) {
 		topLineNew = topLine;
-		newPos = SPositionFromLocation(Point::FromInts(lastXChosen - xOffset, vs.lineHeight * (LinesToScroll() - caretYSlop)),
+		newPos = SPositionFromLocation(Point::FromInts(lastXChosen - xOffset, vs.lineHeight * static_cast<int>(LinesToScroll() - caretYSlop)),
 			false, false, UserVirtualSpace());
 
 	} else {
 		Point pt = LocationFromPosition(sel.MainCaret());
 
 		topLineNew = Sci::clamp(
-		            topLine + direction * LinesToScroll(), 0, MaxScrollPos());
+		            topLine + direction * LinesToScroll(), static_cast<Sci::Line>(0), MaxScrollPos());
 		newPos = SPositionFromLocation(
-			Point::FromInts(lastXChosen - xOffset, static_cast<int>(pt.y) + direction * (vs.lineHeight * LinesToScroll())),
+			Point::FromInts(lastXChosen - xOffset, static_cast<int>(pt.y) +
+				direction * (vs.lineHeight * static_cast<int>(LinesToScroll()))),
 			false, false, UserVirtualSpace());
 	}
 
@@ -3091,10 +3092,10 @@
 
 	const Sci::Line newY = static_cast<Sci::Line>(pt.y) + (1 + skipLines) * direction * vs.lineHeight;
 	if (lastX < 0) {
-		lastX = static_cast<Sci::Position>(pt.x) + xOffset;
+		lastX = static_cast<int>(pt.x) + xOffset;
 	}
 	SelectionPosition posNew = SPositionFromLocation(
-		Point::FromInts(lastX - xOffset, newY), false, false, UserVirtualSpace());
+		Point::FromInts(lastX - xOffset, static_cast<int>(newY)), false, false, UserVirtualSpace());
 
 	if (direction < 0) {
 		// Line wrapping may lead to a location on the same line, so
@@ -3973,7 +3974,7 @@
  * Search of a text in the document, in the given range.
  * @return The position of the found text, -1 if not found.
  */
-long Editor::FindText(
+Sci::Position Editor::FindText(
     uptr_t wParam,		///< Search modes : @c SCFIND_MATCHCASE, @c SCFIND_WHOLEWORD,
     ///< @c SCFIND_WORDSTART, @c SCFIND_REGEXP or @c SCFIND_POSIX.
     sptr_t lParam) {	///< @c Sci_TextToFind structure: The text to search for in the given range.
@@ -3983,15 +3984,15 @@
 	if (!pdoc->HasCaseFolder())
 		pdoc->SetCaseFolder(CaseFolderForEncoding());
 	try {
-		long pos = pdoc->FindText(
+		Sci::Position pos = pdoc->FindText(
 			static_cast<Sci::Position>(ft->chrg.cpMin),
 			static_cast<Sci::Position>(ft->chrg.cpMax),
 			ft->lpstrText,
 			static_cast<int>(wParam),
 			&lengthFound);
 		if (pos != -1) {
-			ft->chrgText.cpMin = pos;
-			ft->chrgText.cpMax = pos + lengthFound;
+			ft->chrgText.cpMin = static_cast<Sci_PositionCR>(pos);
+			ft->chrgText.cpMax = static_cast<Sci_PositionCR>(pos + lengthFound);
 		}
 		return static_cast<int>(pos);
 	} catch (RegexError &) {
@@ -4020,14 +4021,14 @@
  * Used for next text and previous text requests.
  * @return The position of the found text, -1 if not found.
  */
-long Editor::SearchText(
+Sci::Position Editor::SearchText(
     unsigned int iMessage,		///< Accepts both @c SCI_SEARCHNEXT and @c SCI_SEARCHPREV.
     uptr_t wParam,				///< Search modes : @c SCFIND_MATCHCASE, @c SCFIND_WHOLEWORD,
     ///< @c SCFIND_WORDSTART, @c SCFIND_REGEXP or @c SCFIND_POSIX.
     sptr_t lParam) {			///< The text to search for.
 
 	const char *txt = reinterpret_cast<char *>(lParam);
-	long pos;
+	Sci::Position pos;
 	Sci::Position lengthFound = istrlen(txt);
 	if (!pdoc->HasCaseFolder())
 		pdoc->SetCaseFolder(CaseFolderForEncoding());
@@ -4073,13 +4074,13 @@
  * Search for text in the target range of the document.
  * @return The position of the found text, -1 if not found.
  */
-long Editor::SearchInTarget(const char *text, Sci::Position length) {
+Sci::Position Editor::SearchInTarget(const char *text, Sci::Position length) {
 	Sci::Position lengthFound = length;
 
 	if (!pdoc->HasCaseFolder())
 		pdoc->SetCaseFolder(CaseFolderForEncoding());
 	try {
-		long pos = pdoc->FindText(targetStart, targetEnd, text,
+		Sci::Position pos = pdoc->FindText(targetStart, targetEnd, text,
 				searchFlags,
 				&lengthFound);
 		if (pos != -1) {
@@ -5359,18 +5360,18 @@
 		const Sci::Line lineDisplay = cs.DisplayFromDoc(lineDoc);
 		if (visiblePolicy & VISIBLE_SLOP) {
 			if ((topLine > lineDisplay) || ((visiblePolicy & VISIBLE_STRICT) && (topLine + visibleSlop > lineDisplay))) {
-				SetTopLine(Sci::clamp(lineDisplay - visibleSlop, 0, MaxScrollPos()));
+				SetTopLine(Sci::clamp(lineDisplay - visibleSlop, static_cast<Sci::Line>(0), MaxScrollPos()));
 				SetVerticalScrollPos();
 				Redraw();
 			} else if ((lineDisplay > topLine + LinesOnScreen() - 1) ||
 			        ((visiblePolicy & VISIBLE_STRICT) && (lineDisplay > topLine + LinesOnScreen() - 1 - visibleSlop))) {
-				SetTopLine(Sci::clamp(lineDisplay - LinesOnScreen() + 1 + visibleSlop, 0, MaxScrollPos()));
+				SetTopLine(Sci::clamp(lineDisplay - LinesOnScreen() + 1 + visibleSlop, static_cast<Sci::Line>(0), MaxScrollPos()));
 				SetVerticalScrollPos();
 				Redraw();
 			}
 		} else {
 			if ((topLine > lineDisplay) || (lineDisplay > topLine + LinesOnScreen() - 1) || (visiblePolicy & VISIBLE_STRICT)) {
-				SetTopLine(Sci::clamp(lineDisplay - LinesOnScreen() / 2 + 1, 0, MaxScrollPos()));
+				SetTopLine(Sci::clamp(lineDisplay - LinesOnScreen() / 2 + 1, static_cast<Sci::Line>(0), MaxScrollPos()));
 				SetVerticalScrollPos();
 				Redraw();
 			}
diff -r 7f62c564bab3 -r 467e298ac546 src/Editor.h
--- a/src/Editor.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/Editor.h	Fri Jan 26 21:34:34 2018 +1100
@@ -377,7 +377,7 @@
 	void PaintSelMargin(Surface *surfaceWindow, PRectangle &rc);
 	void RefreshPixMaps(Surface *surfaceWindow);
 	void Paint(Surface *surfaceWindow, PRectangle rcArea);
-	long FormatRange(bool draw, Sci_RangeToFormat *pfr);
+	Sci::Position FormatRange(bool draw, Sci_RangeToFormat *pfr);
 	int TextWidth(int style, const char *text);
 
 	virtual void SetVerticalScrollPos() = 0;
@@ -472,10 +472,10 @@
 	void Indent(bool forwards);
 
 	virtual CaseFolder *CaseFolderForEncoding();
-	long FindText(uptr_t wParam, sptr_t lParam);
+	Sci::Position FindText(uptr_t wParam, sptr_t lParam);
 	void SearchAnchor();
-	long SearchText(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
-	long SearchInTarget(const char *text, Sci::Position length);
+	Sci::Position SearchText(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
+	Sci::Position SearchInTarget(const char *text, Sci::Position length);
 	void GoToLine(Sci::Line lineNo);
 
 	virtual void CopyToClipboard(const SelectionText &selectedText) = 0;
diff -r 7f62c564bab3 -r 467e298ac546 src/MarginView.cxx
--- a/src/MarginView.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/MarginView.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -12,6 +12,7 @@
 #include <cctype>
 #include <cstdio>
 #include <cmath>
+#include <cinttypes>
 
 #include <stdexcept>
 #include <string>
@@ -370,7 +371,7 @@
 					if (firstSubLine) {
 						char number[100] = "";
 						if (lineDoc >= 0)
-							sprintf(number, "%d", lineDoc + 1);
+							sprintf(number, "%" PRIdPTR, static_cast<intptr_t>(lineDoc + 1));
 						if (model.foldFlags & (SC_FOLDFLAG_LEVELNUMBERS | SC_FOLDFLAG_LINESTATE)) {
 							if (model.foldFlags & SC_FOLDFLAG_LEVELNUMBERS) {
 								const int lev = model.pdoc->GetLevel(lineDoc);
diff -r 7f62c564bab3 -r 467e298ac546 src/Position.h
--- a/src/Position.h	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/Position.h	Fri Jan 26 21:34:34 2018 +1100
@@ -17,8 +17,8 @@
 
 namespace Sci {
 
-typedef int Position;
-typedef int Line;
+typedef ptrdiff_t Position;
+typedef ptrdiff_t Line;
 
 const Position invalidPosition = -1;
 
diff -r 7f62c564bab3 -r 467e298ac546 src/PositionCache.cxx
--- a/src/PositionCache.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/PositionCache.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -142,14 +142,14 @@
 void LineLayout::SetBracesHighlight(Range rangeLine, const Sci::Position braces[],
                                     char bracesMatchStyle, int xHighlight, bool ignoreStyle) {
 	if (!ignoreStyle && rangeLine.ContainsCharacter(braces[0])) {
-		int braceOffset = braces[0] - rangeLine.start;
+		Sci::Position braceOffset = braces[0] - rangeLine.start;
 		if (braceOffset < numCharsInLine) {
 			bracePreviousStyles[0] = styles[braceOffset];
 			styles[braceOffset] = bracesMatchStyle;
 		}
 	}
 	if (!ignoreStyle && rangeLine.ContainsCharacter(braces[1])) {
-		int braceOffset = braces[1] - rangeLine.start;
+		Sci::Position braceOffset = braces[1] - rangeLine.start;
 		if (braceOffset < numCharsInLine) {
 			bracePreviousStyles[1] = styles[braceOffset];
 			styles[braceOffset] = bracesMatchStyle;
@@ -163,13 +163,13 @@
 
 void LineLayout::RestoreBracesHighlight(Range rangeLine, const Sci::Position braces[], bool ignoreStyle) {
 	if (!ignoreStyle && rangeLine.ContainsCharacter(braces[0])) {
-		int braceOffset = braces[0] - rangeLine.start;
+		Sci::Position braceOffset = braces[0] - rangeLine.start;
 		if (braceOffset < numCharsInLine) {
 			styles[braceOffset] = bracePreviousStyles[0];
 		}
 	}
 	if (!ignoreStyle && rangeLine.ContainsCharacter(braces[1])) {
-		int braceOffset = braces[1] - rangeLine.start;
+		Sci::Position braceOffset = braces[1] - rangeLine.start;
 		if (braceOffset < numCharsInLine) {
 			styles[braceOffset] = bracePreviousStyles[1];
 		}
@@ -192,7 +192,7 @@
 
 
 int LineLayout::FindPositionFromX(XYPOSITION x, Range range, bool charPosition) const {
-	int pos = FindBefore(x, range.start, range.end);
+	int pos = FindBefore(x, static_cast<int>(range.start), static_cast<int>(range.end));
 	while (pos < range.end) {
 		if (charPosition) {
 			if (x < (positions[pos + 1])) {
@@ -205,7 +205,7 @@
 		}
 		pos++;
 	}
-	return range.end;
+	return static_cast<int>(range.end);
 }
 
 Point LineLayout::PointFromPosition(int posInLine, int lineHeight, PointEnd pe) const {
@@ -438,7 +438,7 @@
 	ll(ll_),
 	lineRange(lineRange_),
 	posLineStart(posLineStart_),
-	nextBreak(lineRange_.start),
+	nextBreak(static_cast<int>(lineRange_.start)),
 	saeCurrentPos(0),
 	saeNext(0),
 	subBreak(-1),
@@ -449,7 +449,7 @@
 	// Search for first visible break
 	// First find the first visible character
 	if (xStart > 0.0f)
-		nextBreak = ll->FindBefore(static_cast<XYPOSITION>(xStart), lineRange.start, lineRange.end);
+		nextBreak = ll->FindBefore(static_cast<XYPOSITION>(xStart), static_cast<int>(lineRange.start), static_cast<int>(lineRange.end));
 	// Now back to a style break
 	while ((nextBreak > lineRange.start) && (ll->styles[nextBreak] == ll->styles[nextBreak - 1])) {
 		nextBreak--;
@@ -463,9 +463,9 @@
 			const SelectionSegment portion = psel->Range(r).Intersect(segmentLine);
 			if (!(portion.start == portion.end)) {
 				if (portion.start.IsValid())
-					Insert(portion.start.Position() - posLineStart);
+					Insert(static_cast<int>(portion.start.Position() - posLineStart));
 				if (portion.end.IsValid())
-					Insert(portion.end.Position() - posLineStart);
+					Insert(static_cast<int>(portion.end.Position() - posLineStart));
 			}
 		}
 	}
@@ -474,14 +474,14 @@
 			if (pvsDraw->indicators[deco->Indicator()].OverridesTextFore()) {
 				Sci::Position startPos = deco->rs.EndRun(posLineStart);
 				while (startPos < (posLineStart + lineRange.end)) {
-					Insert(startPos - posLineStart);
+					Insert(static_cast<int>(startPos - posLineStart));
 					startPos = deco->rs.EndRun(startPos);
 				}
 			}
 		}
 	}
 	Insert(ll->edgeColumn);
-	Insert(lineRange.end);
+	Insert(static_cast<int>(lineRange.end));
 	saeNext = (!selAndEdge.empty()) ? selAndEdge[0] : -1;
 }
 
@@ -494,7 +494,8 @@
 		while (nextBreak < lineRange.end) {
 			int charWidth = 1;
 			if (encodingFamily == efUnicode)
-				charWidth = UTF8DrawBytes(reinterpret_cast<unsigned char *>(&ll->chars[nextBreak]), lineRange.end - nextBreak);
+				charWidth = UTF8DrawBytes(reinterpret_cast<unsigned char *>(&ll->chars[nextBreak]),
+					static_cast<int>(lineRange.end - nextBreak));
 			else if (encodingFamily == efDBCS)
 				charWidth = pdoc->IsDBCSLeadByte(ll->chars[nextBreak]) ? 2 : 1;
 			const Representation *repr = preprs->RepresentationFromCharacter(&ll->chars[nextBreak], charWidth);
@@ -503,7 +504,7 @@
 					(nextBreak == saeNext)) {
 				while ((nextBreak >= saeNext) && (saeNext < lineRange.end)) {
 					saeCurrentPos++;
-					saeNext = (saeCurrentPos < selAndEdge.size()) ? selAndEdge[saeCurrentPos] : lineRange.end;
+					saeNext = static_cast<int>((saeCurrentPos < selAndEdge.size()) ? selAndEdge[saeCurrentPos] : lineRange.end);
 				}
 				if ((nextBreak > prev) || repr) {
 					// Have a segment to report
diff -r 7f62c564bab3 -r 467e298ac546 src/ScintillaBase.cxx
--- a/src/ScintillaBase.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/ScintillaBase.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -424,7 +424,7 @@
 		endPos = pdoc->ExtendWordSelect(endPos, 1, true);
 	if (endPos < firstPos)
 		return;
-	AutoCompleteInsert(firstPos, endPos - firstPos, selected.c_str(), static_cast<int>(selected.length()));
+	AutoCompleteInsert(firstPos, static_cast<int>(endPos - firstPos), selected.c_str(), static_cast<int>(selected.length()));
 	SetLastXChosen();
 
 	scn.nmhdr.code = SCN_AUTOCCOMPLETED;
diff -r 7f62c564bab3 -r 467e298ac546 src/ViewStyle.cxx
--- a/src/ViewStyle.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/src/ViewStyle.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -458,7 +458,7 @@
 }
 
 int ViewStyle::GetFrameWidth() const {
-	return Sci::clamp(caretLineFrame, 1, lineHeight / 3);
+	return static_cast<int>(Sci::clamp(caretLineFrame, 1, lineHeight / 3));
 }
 
 bool ViewStyle::IsLineFrameOpaque(bool caretActive, bool lineContainsCaret) const {
diff -r 7f62c564bab3 -r 467e298ac546 test/unit/testCellBuffer.cxx
--- a/test/unit/testCellBuffer.cxx	Fri Jan 26 20:45:31 2018 +1100
+++ b/test/unit/testCellBuffer.cxx	Fri Jan 26 21:34:34 2018 +1100
@@ -25,7 +25,7 @@
 	const char sText[] = "Scintilla";
 	const Sci::Position sLength = static_cast<Sci::Position>(strlen(sText));
 
-	CellBuffer cb(true);
+	CellBuffer cb(true, false);
 	
 	SECTION("InsertOneLine") {
 		bool startSequence = false;
