PageRenderTime 65ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/src/NUnit/UiException/CodeFormatters/PlainTextCodeFormatter.cs

#
C# | 100 lines | 60 code | 18 blank | 22 comment | 5 complexity | 133a00732dadddd26485d811845509d4 MD5 | raw file
Possible License(s): GPL-2.0
  1. // ****************************************************************
  2. // This is free software licensed under the NUnit license. You may
  3. // obtain a copy of the license at http://nunit.org
  4. // ****************************************************************
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Text;
  8. using NUnit.UiException.CodeFormatters;
  9. namespace NUnit.UiException.CodeFormatters
  10. {
  11. /// <summary>
  12. /// Create a default FormattedCode for any string value.
  13. /// This should be used as a last resort when there is not ICodeFormatter
  14. /// that fit source code for an ErrorItem.
  15. /// </summary>
  16. public class PlainTextCodeFormatter :
  17. ICodeFormatter
  18. {
  19. #region ICodeFormatter Membres
  20. /// <summary>
  21. /// Returns "Plain text"
  22. /// </summary>
  23. public string Language
  24. {
  25. get { return ("Plain text"); }
  26. }
  27. public FormattedCode Format(string sourceCode)
  28. {
  29. DefaultTextManager text;
  30. byte[] byteArray;
  31. int[] strArray;
  32. int[] lineArray;
  33. int index;
  34. int posLineStart;
  35. int posChar;
  36. UiExceptionHelper.CheckNotNull(sourceCode, "sourceCode");
  37. sourceCode = PreProcess(sourceCode);
  38. text = new DefaultTextManager();
  39. text.Text = sourceCode;
  40. strArray = new int[text.LineCount];
  41. lineArray = new int[text.LineCount];
  42. index = 0;
  43. posLineStart = 0;
  44. posChar = 0;
  45. foreach (char c in sourceCode)
  46. {
  47. if (c == '\n')
  48. {
  49. strArray[index] = posLineStart;
  50. lineArray[index] = index;
  51. posLineStart = posChar + 1;
  52. index++;
  53. }
  54. posChar++;
  55. }
  56. if (index <= text.LineCount - 1)
  57. {
  58. strArray[index] = posLineStart;
  59. lineArray[index] = index;
  60. }
  61. byteArray = new byte[text.LineCount];
  62. return (new FormattedCode(sourceCode, strArray, byteArray, lineArray));
  63. }
  64. #endregion
  65. /// <summary>
  66. /// Prepare input text for the parsing stage.
  67. /// </summary>
  68. /// <param name="text">The text to be pre-processed.</param>
  69. /// <returns>A string ready to be parsed.</returns>
  70. public string PreProcess(string text)
  71. {
  72. if (text == null)
  73. return (null);
  74. // this replace tabulation by space sequences. The reason is
  75. // that the technique used to measure strings at rendering time
  76. // fail to measure '\t' correctly and lines of text containing those
  77. // characters are badly aligned.
  78. // The simplest thing to fix that is to remove tabs altogether.
  79. return (text.Replace("\t", " "));
  80. }
  81. }
  82. }