function isNull(v){
	if( v=="null" ) return true;
	if( v==null ) return true;
	if( v=="" ) return true;
	return false;
}

function countSpace(line) {
	var cnt=0;
	for(var i=0; i<line.length; i++){
		var s = line.substr(i, 1);
		if(s==" ")
			cnt++;
		else if(s=="\t")
			cnt+=4;
		else
			break;

		if(cnt>=4)
			break;
	}
	return cnt;
}

function ltrim(txt){
	return txt.replace(/(^\s*)/g,"");
}

function run(){
	var doc=App.ActiveDoc;
	var pos=doc.CaretPos;
	if( pos.Line<=0 )
		return;

	pos.Line--;
	var txt = doc.GetLineText(pos.Line);
	var indent="";

	if( countSpace(txt)<=3 && doc.Scope!="md.codeblock" ){
		// 删除上一个是空的有序,无序,任务列表
		if( !isNull( txt.match(/^\s*[\-\*\+]\s*$/) + "" ) || 
			!isNull(txt.match(/^\s*\d+\.\s*$/) + "") || 
			!isNull(txt.match(/^\s*- \[[xX ]\]\s*$/) + "") ||
			!isNull(txt.match(/^\s*[\u2611|\u2B1C]\s*$/) + "")
		){
			doc.Delete(pos.Line, 0, pos.Line, txt.length);
			doc.SetCaretPos(pos.Line+1, 0, true);
			return;
		}

		indent=txt.match(/^\s*[\u2611|\u2B1C]\s*/) + "";
		if( isNull(indent) ){
			indent=txt.match(/^\s*- \[[xX ]\]\s*/) + "";
			if( isNull(indent) ){
				indent=txt.match(/^\s*[\-\*\+] /) + "";
				if( isNull(indent) ){
					indent=txt.match(/^\s*\d+\. /) + "";
					if( !isNull(indent) ){
						indent = indent.replace(/\d+/g, function($1) {
						   return parseInt($1)+1;
						});
					}
				}
			}
		}
	}

	if( !isNull(indent) ){
		indent = ltrim(indent);
	}

	if( !isNull(indent) ){
		doc.Insert( indent );
	}
}

run();
