CKEDITOR.plugins.add("sourcelocation", {
  init: function (editor) {
    var selectText = '';//选中的文字
   // var selectRange;//可视化编辑器选中的区域，用于source返回wysiwyg后的定位
    //var bookmark;

    editor.on("mode", function () {
      if (selectText !== '') {
        if (editor.mode === "wysiwyg") {
          //console.log(bookmark);
          //editor.getSelection().selectBookmarks( bookmark).scrollIntoView();
          //editor.getSelection().scrollIntoView();
        } else {
          if (selectText !== "") {
            var codemirror = window["codemirror_" + editor.id]; //编辑器的codemirror实例
            var find_start = -1;
            var find_str = selectText; //需要查找的字符串
            for (i = 0; i < codemirror.doc.lastLine(); i++) {
              line = codemirror.doc.getLineHandle(i);
              find_start = line.text.indexOf(find_str);
              if (find_start !== -1) {
                line_number = codemirror.doc.getLineNumber(line);
                //console.log(find_start,codemirror.doc.getLineNumber(line),line.text);
                codemirror.doc.setCursor(line_number + 10); //滚动到稍微远一点的行，选中的文本才可以展示在编辑器中间
                codemirror.doc.setSelection(
                  { line: line_number, ch: find_start },
                  { line: line_number, ch: find_start + find_str.length }
                );
                break;
              }
            }
          }
        }
      }
    });

    //监控source按钮按下之前的事件，获取当前选中的文字
    editor.on('beforeCommandExec', function (event) {
      var commandName = event.data.name;
      if (commandName == 'source') {
        if (editor.mode === "wysiwyg") {
          selectText = editor.getSelectedHtml(true);
          //selectRange = editor.getSelection().getRanges();
         // bookmark = editor.getSelection().createBookmarks();
          //console.log(bookmark);
        } else {
          selectText = window["codemirror_" + editor.id].doc.getSelection();
        }
      }
    });

  }
});
