module.exports = inlineCode
inlineCode.peek = inlineCodePeek

function inlineCode(node) {
  var value = node.value || ''
  var sequence = '`'
  var pad = ''

  // If there is a single grave accent on its own in the code, use a fence of
  // two.
  // If there are two in a row, use one.
  while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) {
    sequence += '`'
  }

  // If this is not just spaces or eols (tabs don’t count), and either the
  // first or last character are a space, eol, or tick, then pad with spaces.
  if (
    /[^ \r\n]/.test(value) &&
    (/[ \r\n`]/.test(value.charAt(0)) ||
      /[ \r\n`]/.test(value.charAt(value.length - 1)))
  ) {
    pad = ' '
  }

  return sequence + pad + value + pad + sequence
}

function inlineCodePeek() {
  return '`'
}
